viewgit/index.php:465 Only variables should be passed by reference [2048]
viewgit/index.php:466 Non-static method GeSHi::get_language_name_from_extension() should not be called statically [2048]
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Questo è un semplice script che attiva automaticamente # la VPN verso poisson per chi si connette ad una rete wireless # dall'interno del dipartimenti di Matematica di Pisa. # # Io lo uso per evitare di dover fare un clic di troppo ;) # # Ringrazio Tambet Ingo-2 dal cui script ho preso ispirazione # per cominciare questo. # # Potete trovare la sua versione di uno script in python per fare # una cosa simile in questo thread: # http://old.nabble.com/dbus-and-OpenVPN-Autostart-td21905375.html # # Questo codice è rilasciato sotto licenza GPL3 che si trova nel # file LICENSE nell'archivio dei sorgenti che potete trovare clonando # il repository git su http://poisson.phc.unipi.it/~robol/gits/AutoVPN.git # # __author__ = "Leonardo Robol <robol@poisson.phc.unipi.it>" # Default values. You can change these to adjust package # configuration # # apt_proxy_file specifies the name of the file that # poisson_vpn will use as configuration file for the # apt proxy. It will created on connection and deleted # on disconnection apt_proxy_file = "/etc/apt/apt.conf.d/99poisson_proxy" # mac_addresses is a list of unicode strings containing the # mac addresses of access point that are in the local # subnet where the VPN is available mac_addresses = [ u"00:0d:54:a9:cf:36", u'00:13:64:2a:10:00' ] # using_notify controls if notifications of # a successful conection should be showed to # logged user. using_notify = True # notify_body is the content of the notification that # will be displayed in alle the gnome active sessions # when the connection is established. notify_body = "La connessione VPN a poisson è stata effettuata ed è ora possibile navigare in Internet." # # START OF THE CODE; DON'T MODIFY THE SCRIPT BEYOND THIS LINE # import dbus, sys, os, subprocess, re, time from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True) def init(): """ Istruzioni da eseguire prima di fare ogni altra cosa. In poche parole otteniamo il bus di sistema che ci servirà abbondantemente in tutto lo script. """ global bus bus = dbus.SystemBus() def is_poisson_vpn(settings): """ Questa funzione riconosce la vpn per connettersi alla rete esterna tramite poisson facendo un check su nome dell'host remote e sulla porta. Nonostante il nome non sia un fqdn, penso che il test sia abbastanza deterministico. """ if settings['connection']['type'] != "vpn": return False if settings['vpn']['data']['remote'] != "poisson.phc-priv": return False # 1194 è la porta di default per la vpn, quindi può anche essere non # specificata nel file di configurazione. Controlliamo se è così, oppure # se è stata specificata ed impostata a 1194. if settings['vpn']['data'].has_key("port") and settings['vpn']['data']['port'] != "1194": return False # Se siamo arrivati a questo punto significa che questa è davvero # la VPN per connettersi alla rete esterna da poisson return True def get_poisson_vpn(): """ Ottiene la vpn per poisson tramite dbus """ # Tentiamo di caricare la configurazione dell'utente. proxy = bus.get_object("org.freedesktop.NetworkManagerUserSettings", "/org/freedesktop/NetworkManagerSettings") interface = dbus.Interface(proxy, "org.freedesktop.NetworkManagerSettings") # Ritorniamo None se non siamo in grado di trovare la VPN oppure # se è già attiva c = None # Controlliamo tutte le connessione salvate nelle connessione dell'utente # sperando di trovare la VPN. Se questa è specificata nelle connessioni di sistema, # beh.. questa è una feature per la prossima versione. for connection in interface.ListConnections(): proxy = bus.get_object("org.freedesktop.NetworkManagerUserSettings", connection) settings = proxy.GetSettings(dbus_interface="org.freedesktop.NetworkManagerSettings.Connection") # Check per determinare se questa è la connessione giusta if is_poisson_vpn (settings): c = connection # Controlliamo se la VPN è già attiva... proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") interface = dbus.Interface(proxy, "org.freedesktop.DBus.Properties") # ...provando a confrontarla con tutte le connessioni attive for connection in interface.Get("org.freedesktop.NetworkManager", "ActiveConnections"): proxy = bus.get_object("org.freedesktop.NetworkManager", connection) interface = dbus.Interface(proxy, "org.freedesktop.DBus.Properties") connection = interface.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection") if connection == c: return None # Ritorniamo la connessione VPN o None se non c'è bisogno di fare nulla return c def get_base_connection(): """ Otteniamo la connessione su cui attivare la VPN (i.e. PHC-wifi o CDCWL1) """ # Otteniamo la lista di tutte le connessioni attive al momento proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") interface = dbus.Interface(proxy, "org.freedesktop.DBus.Properties") active_connections = interface.Get('org.freedesktop.NetworkManager', 'ActiveConnections') # Esaminiamo ogni connessione attiva e verifichiamo se è una connessione wireless # e se lo è se l'AP ha lo stesso MAC di PHC-wifi o di CDCWL1 for connection in active_connections: proxy = bus.get_object("org.freedesktop.NetworkManager", connection) interface = dbus.Interface(proxy, "org.freedesktop.DBus.Properties") path = interface.Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection') proxy = bus.get_object('org.freedesktop.NetworkManagerUserSettings', path) interface = dbus.Interface(proxy, 'org.freedesktop.NetworkManagerSettings.Connection') settings = interface.GetSettings() if settings.has_key("802-11-wireless"): # Rimuoviamo dalla lista gli access point che non sono # all'interno del Dipartimento di Matematica intersection = filter(lambda x : x in mac_addresses, settings['802-11-wireless']['seen-bssids']) # Se ne è rimasto qualcuno ritorniamo la connessione if len(intersection) != 0: return connection # Se siamo arrivati a questo punto significa che la connessione attiva # non è direttamente connessa a poisson.phc-priv e qunidi possiamo # anche lasciar perdere reset_apt_proxy () return None def has_default_route(): """Return True if exists a default route""" p = subprocess.Popen(["ip", "route", "show"], stdout = subprocess.PIPE) output = p.communicate()[0] if "default" in output: return True else: return False def activate_connection(connection): """ Attiva la connessione """ proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager") interface = dbus.Interface (proxy, "org.freedesktop.NetworkManager") # Otteniamo la connessione di base su cui attivare la VPN base_connection = get_base_connection () if base_connection is not None: interface.ActivateConnection('org.freedesktop.NetworkManagerUserSettings', connection, dbus.ObjectPath("/"), base_connection) # Setup apt proxy on poisson:3142 setup_apt_proxy () # If configured to try notification, make a bubble appear # in the user desktop if using_notify: # Wait for the connection to be completed. We should test # that user has internet access starting_time = time.time() while(time.time() < starting_time + 10): if has_default_route(): continue else: time.sleep(0.5) if not has_default_route(): return # To get user Session bus we should get the content # of DBUS_SESSION_BUS_ADDRESS of user # so we can start getting the pid of gnome-session p = subprocess.Popen(["ps", "-C", "gnome-session", "-o", "pid="], stdout = subprocess.PIPE) output = p.communicate()[0] environments = [] for pid in output.split("\n"): try: pid = int(pid.strip()) except: continue with open("/proc/%d/environ" % pid, "r") as handle: env = {} content = handle.read() for pair in content.split("\0"): pieces = pair.split("=") key = pieces[0] value = "=".join(pieces[1:]) env[key] = value environments.append(env) # Copy environment of users so we can send graphical notifications # to them. Quite hack, but... for env in environments: for key, value in env.items(): os.putenv(key, value) # Get SessionBus mybus = dbus.SessionBus() notifyService = mybus.get_object("org.freedesktop.Notifications", "/org/freedesktop/Notifications") interface = dbus.Interface(notifyService, "org.freedesktop.Notifications") interface.Notify('poisson-vpn', 0, 'poisson-vpn', "Connessione effettuata", notify_body, [], {}, 15000) else: reset_apt_proxy () def reset_apt_proxy(): """Delete apt proxy configuration file""" if os.path.exists(apt_proxy_file): os.remove(apt_proxy_file) def setup_apt_proxy(): if not os.path.exists(apt_proxy_file): with open(apt_proxy_file, "w") as handle: handle.write("""Acquire::http { Proxy "http://poisson:3142"; };""") handle.write("\n") if __name__ == "__main__": # Se hai appena staccato una VPN probabilmente non hai bisogno # che ti riattivi quella per poisson (anche perché potresti stare # cercando di liberartente). if sys.argv[2] == "vpn-down": sys.exit (0) # Se è appena stata attivata una VPN non ha senso cercare di # attivarne un'altra (se non altro perché NM non ne supporta più # di una nello stesso momento) if sys.argv[2] == "vpn-up": sys.exit (0) # Se hai appena deconfigurato un'interfaccia probabilmente non # desideri attivare la VPN if sys.argv[2] == "down": reset_apt_proxy() sys.exit (0) # Otteniamo il bus init () # ...e la VPN per poisson poisson_vpn = get_poisson_vpn () # Se non l'abbiamo trovata oppure è # già attiva possiamo anche uscire if (poisson_vpn is None): reset_apt_proxy () sys.exit (0) # Altrimenti la attiviamo, e poi usciamo :) activate_connection (poisson_vpn) sys.exit (0)