You are not logged in.

#1 2010-10-29 23:31:18

Fruity
Member
Registered: 2009-12-16
Posts: 198

[SOLVED] NetworkManager VPN auto connect

I was using this http://ubuntuforums.org/showthread.php?t=1316314 script to keep my VPN up all the time. It worked fine. I reinstalled everything (wanted to use LVM + encryption) And now this same script is not working. I thought I'd throw it open to arch community to see if I can get this fixed. Here is the code:

#!/usr/bin/python

import sys
import os
import dbus
import gobject
from  dbus.mainloop.glib import DBusGMainLoop

# The uuid of the VPN connection to activate
VPN_CONNECTION_UUID = "FILL IN YOUR OWN"

# The uuid of the connection that needs to be active to start the VPN connection
ACTIVE_CONNECTION_UUID = "FILL IN YOUR OWN"

# some service, path and interface constants
NM_DBUS_SERVICE                   = "org.freedesktop.NetworkManager"
NM_DBUS_PATH                      = "/org/freedesktop/NetworkManager"
NM_DBUS_INTERFACE                 = "org.freedesktop.NetworkManager"
NM_DBUS_IFACE_CONNECTION_ACTIVE   = "org.freedesktop.NetworkManager.Connection.Active"
NM_DBUS_SERVICE_SYSTEM_SETTINGS   = "org.freedesktop.NetworkManagerSystemSettings"
NM_DBUS_SERVICE_USER_SETTINGS     = "org.freedesktop.NetworkManagerUserSettings"
NM_DBUS_IFACE_SETTINGS            = "org.freedesktop.NetworkManagerSettings"
NM_DBUS_PATH_SETTINGS             = "/org/freedesktop/NetworkManagerSettings"
NM_DBUS_IFACE_SETTINGS_CONNECTION = "org.freedesktop.NetworkManagerSettings.Connection"

DBusGMainLoop(set_as_default=True)

nm_dbus_settings_services = (NM_DBUS_SERVICE_SYSTEM_SETTINGS, NM_DBUS_SERVICE_USER_SETTINGS)

def get_connections(bus, service):
  proxy = bus.get_object(service, NM_DBUS_PATH_SETTINGS)
  iface = dbus.Interface(proxy, dbus_interface=NM_DBUS_IFACE_SETTINGS)
  return iface.ListConnections()

def get_connection_by_uuid(bus, uuid):
  for service in nm_dbus_settings_services:
    for c in get_connections(bus, service):
      proxy = bus.get_object(service, c)
      iface = dbus.Interface(proxy, dbus_interface = NM_DBUS_IFACE_SETTINGS_CONNECTION)
      settings = iface.GetSettings()
      if settings['connection']['uuid'] == uuid:
        return (c, service)
  return None

def list_uuids(bus):
  for service in nm_dbus_settings_services:
    for c in get_connections(bus, service):
      proxy = bus.get_object(service, c)
      iface = dbus.Interface(proxy, dbus_interface=NM_DBUS_IFACE_SETTINGS_CONNECTION)
      settings = iface.GetSettings()
      conn = settings['connection']
      print " %s: %s - %s (%s)" % (service, conn['uuid'], conn['id'], conn['type'])

def get_active_connection_path(bus, uuid):
  proxy = bus.get_object(NM_DBUS_SERVICE, NM_DBUS_PATH)
  iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties')
  active_connections = iface.Get(NM_DBUS_INTERFACE, 'ActiveConnections')
  connection_and_service = get_connection_by_uuid(bus, uuid)
  if connection_and_service == None:
    return None
  for a in active_connections:
    proxy = bus.get_object(NM_DBUS_SERVICE, a)
    iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties')
    path = iface.Get(NM_DBUS_IFACE_CONNECTION_ACTIVE, 'Connection')
    service = iface.Get(NM_DBUS_IFACE_CONNECTION_ACTIVE, 'ServiceName')
    if service != connection_and_service[1]:
      continue
    proxy = bus.get_object(connection_and_service[1], path)
    iface = dbus.Interface(proxy, dbus_interface=NM_DBUS_IFACE_SETTINGS_CONNECTION)
    settings = iface.GetSettings()
    if settings['connection']['uuid'] == uuid:
      return a
  return None

def activate_connection(bus, vpn_connection, active_connection):
  def reply_handler(opath):
    print "<<SUCCESS>>"
    sys.exit(0)
  def error_handler(*args):
    print "<<FAILURE>>"
    sys.exit(1)
  proxy = bus.get_object(NM_DBUS_SERVICE, NM_DBUS_PATH)
  iface = dbus.Interface(proxy, dbus_interface=NM_DBUS_INTERFACE)
  iface.ActivateConnection(NM_DBUS_SERVICE_USER_SETTINGS,
                           vpn_connection[0],
                           dbus.ObjectPath("/"), 
                           active_connection,
                           reply_handler=reply_handler,
                           error_handler=error_handler)

bus = dbus.SystemBus()

print "connections:"
list_uuids(bus)

if len(VPN_CONNECTION_UUID) < 1 or len(ACTIVE_CONNECTION_UUID) < 1:
    print "you need to set the uuids"
    sys.exit(0)

vpn_connection = get_connection_by_uuid(bus, VPN_CONNECTION_UUID)
if not vpn_connection:
    print "Configured VPN connection is not known to NM, check VPN_CONNECTION_UUID."
    sys.exit(1)

active_connection = get_connection_by_uuid(bus, ACTIVE_CONNECTION_UUID)
if not active_connection:
  print "Configured active connection is not known to NM, check ACTIVE_CONNECTION_UUID."
  sys.exit(1)

if get_active_connection_path(bus, VPN_CONNECTION_UUID) != None:
  print "VPN connection already activated"
  sys.exit(0)

active_connection_path = get_active_connection_path(bus, ACTIVE_CONNECTION_UUID)
if not active_connection_path:
  print "The required connection isn't active at the moment"
  sys.exit(0)

print "connecting to:\n  '%s'\nwith active connection:\n  '%s'" % (vpn_connection, active_connection)

activate_connection(bus, vpn_connection, active_connection_path)

loop = gobject.MainLoop()
loop.run()

It now exits with the following error:

  File "./auto", line 52
    print " %s: %s - %s (%s)" % (service, conn['uuid'], conn['id'], conn['type'])

As a quick outline, running the script first time in the past, it would error, saying something along the lines of "unknown UUID" and then print the UUID's of the eth0 and VPN, adding these to the script at the top would clearly, make it boogey from that point on.

Can anyone please help me fix this? The various other auto vpn scripts I have come across on the net, dont seem to work for me... Could this be a problem with python3 or networkmanager 0.8? Pretty sure that previously I was using python2 and NM 0.7.

And as a side note, this bug in networkmanager was first reported way back in 2008! 'connect automatically' option not working. Sad really as it's a bit of a show stopper for those who use vpn. Didnt the BSD crowd have a saying..? Put up or patch up. If only I could...

Last edited by Fruity (2010-10-30 10:26:14)

Offline

#2 2010-10-29 23:46:29

hokasch
Member
Registered: 2007-09-23
Posts: 1,461

Re: [SOLVED] NetworkManager VPN auto connect

Sorry no idea about python scripts here... but since there was recent update to python 3, maybe you need to use

#!/usr/bin/python2

Offline

#3 2010-10-29 23:53:41

Fruity
Member
Registered: 2009-12-16
Posts: 198

Re: [SOLVED] NetworkManager VPN auto connect

hokasch, thanks. It works as planned now. Thought it might be something to do with python.. Didnt register to change it to pyhton2.

Offline

#4 2013-02-04 16:16:24

sgleo87
Member
Registered: 2013-02-04
Posts: 3

Re: [SOLVED] NetworkManager VPN auto connect

I found a somewhat simpler script, that not only lets you automatically re-establish your VPN connection, if you get disconnected, but also stops a predefined program (e.g. transmission), until the VPN connection is established again. This prevents your real IP-Address from getting exposed (in that program).

Unfortunately, the original script in the Ubuntu Forums was not working for me, because the script did not recognize, that the VPN connection was already established and tried to reconnect the whole time. So here is my modified version. Hope someone benefits from this!

CHANGES:
- Fixed established VPN connection not being recognized.
- Program can be started independently at any time, since the script now continually checks, if it is running or not.

#!/bin/bash
#This program automatically re-establishes your VPN connection and pauses a predefined program.

#Monitor the VPN connection
date
while true; do
	#Define a string to test VPN connection: 0 = no connection, 1 = connected.
	programID=$(pidof PROGRAM)
	connected=$(nmcli -t -f VPN con status|grep -c yes)	
	case $connected in
	"0")
		date
		echo "VPN disconnected."
		#Connection lost. Stop the VPN dependency, if running.
		if [ "$programID" != "" ]; then
			kill -SIGSTOP $programID
			echo "Program stopped."
		else
			echo "Program not running."
		fi
		echo "Reconnecting VPN."
		#Give the VPN time to recover.
		sleep 15
		#Retry the VPN
		nmcli -p con up uuid CONNECTION-ID-NUMBER	
	;;
	"1")
                date
		echo "VPN connected."
		#Connection is fine. Restart the VPN dependency, if it was running.
		if [ "$programID" != "" ]; then
			kill -SIGCONT $programID
			echo "Program running."
		else
			echo "Program not running."
		fi
	;;
	esac
sleep 5
done

Note: As in the original script, please replace PROGRAM with the application name (e.g. transmission-gtk) and the CONNECTION-ID-NUMBER with the uuid of your vpn connection (e.g. 83335b7a-789a-411e-8140-135126fa4701).


HP EliteBook 8460p: Intel Core i5-2520M 2.50 GHz - 8 GB 1333 MHz DDR3 SDRAM - AMD Radeon HD 6470M 1 GB - Samsung SSD 830 Series 256GB

Offline

Board footer

Powered by FluxBB