Advertisement
johnmahugu

python auto VPN script

May 7th, 2016
1,381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.31 KB | None | 0 0
  1. #!/usr/bin/python
  2. """
  3. Copyright 2016 john kesh mahugu. All rights reserved.
  4.  
  5. Redistribution and use in source and binary forms, with or without modification, are
  6. permitted provided that the following conditions are met:
  7.  
  8.   1. Redistributions of source code must retain the above copyright notice, this list of
  9.      conditions and the following disclaimer.
  10.  
  11.   2. Redistributions in binary form must reproduce the above copyright notice, this list
  12.      of conditions and the following disclaimer in the documentation and/or other materials
  13.      provided with the distribution.
  14.  
  15. THIS SOFTWARE IS PROVIDED BY DOMEN KOZAR ''AS IS'' AND ANY EXPRESS OR IMPLIED
  16. WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DOMEN KOZAR OR
  18. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  19. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  20. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  21. ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  22. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  23. ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24.  
  25. The views and conclusions contained in the software and documentation are those of the
  26. authors and should not be interpreted as representing official policies, either expressed
  27. or implied, of DOMEN KOZAR.
  28.  
  29. USAGE
  30. =====
  31.  
  32. 1) clone gist somewhere (eg. /home/user/autovpn/)
  33. 2) add to /etc/rc.local: python /home/user/autovpn/autovpn.py "myvpn" 'Auto homenetwork,Auto worknetwork' > /var/log/autovpn.log&
  34. 3) reboot :-)
  35.  
  36. CHANGELOG
  37. =========
  38.  
  39.  
  40. 0.1 (1.1.2012)
  41. --------------
  42.  
  43. * bug: compatible with NM 0.9, dropped support for 0.8
  44. * feature: specify networks that vpn is not autoconnected
  45.  
  46. KNOWN ISSUES
  47. ============
  48.  
  49. * it will always use first active network connection
  50.  
  51. """
  52. import sys
  53.  
  54. from dbus.mainloop.glib import DBusGMainLoop
  55. import dbus
  56. import gobject
  57.  
  58.  
  59. class AutoVPN(object):
  60.     """Solves two jobs, tested with NetworkManager 0.9.x:
  61.  
  62.    * if VPN connection is not disconnected by user himself, reconnect (configurable max_attempts)
  63.    * on new active network connection, activate VPN
  64.  
  65.    :param vpn_name: Name of VPN connection that will be used for autovpn
  66.    :param ignore_networks: Comma separated network names in NM that will not force VPN usage
  67.    :param max_attempts: Maximum number of attempts of reconnection VPN session on failures
  68.    :param delay: Miliseconds to wait before reconnecting VPN
  69.  
  70.    """
  71.  
  72.     def __init__(self, vpn_name, ignore_networks='', max_attempts=5, delay=5000):
  73.         self.vpn_name = vpn_name
  74.         self.max_attempts = max_attempts
  75.         self.delay = delay
  76.         self.failed_attempts = 0
  77.         self.bus = dbus.SystemBus()
  78.         self.ignore_networks = filter(None, ignore_networks.split(','))
  79.         self.get_network_manager().connect_to_signal("StateChanged", self.onNetworkStateChanged)
  80.         print "Maintaining connection for %s, reattempting up to %d times with %d ms between retries" % (vpn_name, max_attempts, delay)
  81.  
  82.     def onNetworkStateChanged(self, state):
  83.         """Handles network status changes and activates the VPN on established connection."""
  84.         print "Network state changed: %d" % state
  85.         if state == 70:
  86.             self.activate_vpn()
  87.  
  88.     def onVpnStateChanged(self, state, reason):
  89.         """Handles different VPN status changes and eventually reconnects the VPN."""
  90.         # vpn connected or user disconnected manually?
  91.         if state == 5 or (state == 7 and reason == 2):
  92.             self.failed_attempts = 0
  93.             if state == 5:
  94.                 print "VPN connected"
  95.             else:
  96.                 print "User disconnected manually"
  97.             return
  98.         # connection failed or unknown?
  99.         elif state in [6, 7]:
  100.             # reconnect if we haven't reached max_attempts
  101.             if not self.max_attempts or self.failed_attempts < self.max_attempts:
  102.                 print "Connection failed, attempting to reconnect"
  103.                 self.failed_attempts += 1
  104.                 gobject.timeout_add(self.delay, self.activate_vpn)
  105.             else:
  106.                 print "Connection failed, exceeded %d max attempts." % self.max_attempts
  107.                 self.failed_attempts = 0
  108.  
  109.     def get_network_manager(self):
  110.         """Gets the network manager dbus interface."""
  111.         print "Getting NetworkManager DBUS interface"
  112.         proxy = self.bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
  113.         return dbus.Interface(proxy, 'org.freedesktop.NetworkManager')
  114.  
  115.     def get_vpn_interface(self, name):
  116.         'Gets the VPN connection interface with the specified name.'
  117.         print "Getting %s VPN connection DBUS interface" % name
  118.         proxy = self.bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager/Settings')
  119.         iface = dbus.Interface(proxy, 'org.freedesktop.NetworkManager.Settings')
  120.         connections = iface.ListConnections()
  121.         for connection in connections:
  122.             proxy = self.bus.get_object('org.freedesktop.NetworkManager', connection)
  123.             iface = dbus.Interface(proxy, 'org.freedesktop.NetworkManager.Settings.Connection')
  124.             con_settings = iface.GetSettings()['connection']
  125.             if con_settings['type'] == 'vpn' and con_settings['id'] == name:
  126.                 print "Got %s interface" % name
  127.                 return iface
  128.         print "Unable to acquire %s VPN interface. Does it exist?" % name
  129.         return None
  130.  
  131.     def get_active_connection(self):
  132.         """Gets the dbus interface of the first active
  133.        network connection or returns None.
  134.        """
  135.         print "Getting active network connection"
  136.         proxy = self.bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
  137.         iface = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')
  138.         active_connections = iface.Get('org.freedesktop.NetworkManager', 'ActiveConnections')
  139.         if len(active_connections) == 0:
  140.             print "No active connections found"
  141.             return None
  142.         print "Found %d active connection(s)" % len(active_connections)
  143.         return active_connections[0]
  144.  
  145.     def activate_vpn(self):
  146.         'Activates the vpn connection.'
  147.         print "Activating %s VPN connection" % self.vpn_name
  148.         vpn_con = self.get_vpn_interface(self.vpn_name)
  149.         active_con = self.get_active_connection()
  150.  
  151.         # check if we have to ignore vpn
  152.         proxy = self.bus.get_object('org.freedesktop.NetworkManager', active_con)
  153.         con = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties').Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection')
  154.         proxy = self.bus.get_object('org.freedesktop.NetworkManager', con)
  155.         settings = dbus.Interface(proxy, 'org.freedesktop.NetworkManager.Settings.Connection').GetSettings()
  156.         if settings['connection']['id'] in self.ignore_networks:
  157.             print "Ignored network connection %s based on settings" % settings['connection']['id']
  158.             return
  159.  
  160.         # activate vpn and watch for reconnects
  161.         if vpn_con and active_con:
  162.             new_con = self.get_network_manager().ActivateConnection(
  163.                 vpn_con,
  164.                 dbus.ObjectPath("/"),
  165.                 active_con,
  166.             )
  167.             proxy = self.bus.get_object('org.freedesktop.NetworkManager', new_con)
  168.             iface = dbus.Interface(proxy, 'org.freedesktop.NetworkManager.VPN.Connection')
  169.             iface.connect_to_signal('VpnStateChanged', self.onVpnStateChanged)
  170.             print "VPN %s should be active soon" % self.vpn_name
  171.  
  172.  
  173. if __name__ == '__main__':
  174.     if len(sys.argv) < 2:
  175.         print 'usage: autovpn VPN_CONNECTION_NAME <COMMA SEPARATED NAMES OF IGNORABLE NETWORKS>'
  176.         print '-> activates vpn if any network connection is active'
  177.         print '-> and reconnects VPN on failure'
  178.         sys.exit(0)
  179.  
  180.     # set up the main loop
  181.     DBusGMainLoop(set_as_default=True)
  182.     loop = gobject.MainLoop()
  183.     # TODO: argparse
  184.     if len(sys.argv) > 2:
  185.         AutoVPN(sys.argv[1], sys.argv[2])
  186.     else:
  187.         AutoVPN(sys.argv[1])
  188.     loop.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement