if wireless_device is not None: # Get the currently active VPN connection. # If you're running some kind of weird, three active VPNs scenario, then... # Change this code to work in your use-case. active = NetworkManager.NetworkManager.ActiveConnections for a in active: if "vpn" in a.Type: current_vpn = a # Choose a random one to connect to. We use the far more secure random method, with a larger seed, # to try and prevent the random generation from being a predictable pattern (well, to try to make # it far less predictable with our sample, at least). rand = random.SystemRandom(os.urandom(99999999)) random_int = rand.randint(0, (vpns.__len__() - 1)) random_vpn = vpns.__getitem__(random_int) new_connection = NetworkManager.Connection(random_vpn) # Validate that we have a current VPN connection to disconnect from before we do. if current_vpn is not None: # Disconnect the old & busted. NetworkManager.NetworkManager.DeactivateConnection(current_vpn) # To prevent collision in NetworkManager, we allow background clean-up before reconnecting. time.sleep(10) # Connect the new hotness. print("Connecting to: {}".format(random_vpn)) NetworkManager.NetworkManager.ActivateConnection(new_connection, wireless_device, "/") # No wireless interfaces were found, so let's abort.