Created
September 22, 2013 14:31
-
-
Save melpomene/6660458 to your computer and use it in GitHub Desktop.
VPN verification and reconnection script for Ubuntu with network-manager.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, requests, time | |
from datetime import datetime | |
import socket | |
URL = "https://showmemyip.example.com" # EDIT THIS. NEEDS TO BE A URL THAT RETURNS YOUR PUBLIC IP. | |
CORRECT_REVERSE_URL = "ipredator.se" # EDIT THIS TO BE THE REVERSE-URL OF YOUR VPN PROVIDER | |
VPN_CONNECTION_NAME = "Ipredator" # EDIT THIS TO THE NAME OF THE VPN CONNECTION IN NETWORK-MANAGER. | |
""" | |
Run this script in cron to verify that you are connected to your desired VPN service | |
which is automatically reconnected if the connection is lost | |
Dependencies: Network-manager (tested on ubuntu) | |
""" | |
def test_con(): | |
try: | |
r = requests.get(URL) | |
if r.status_code == 200: | |
reverse_dns = socket.gethostbyaddr(r.content)[0] | |
if reverse_dns.endswith(CORRECT_REVERSE_URL): | |
return True | |
else: | |
log("Connection was turned off (not running %s)" % CORRECT_REVERSE_URL) | |
return False | |
else: | |
log("Connection not responding") | |
return False | |
except requests.exceptions.ConnectionError: | |
log("Connection not responding") | |
return False | |
def connect(): | |
os.system("nmcli con up id %s" % VPN_CONNECTION_NAME) | |
def disconnect(): | |
os.system("nmcli con down id %s" % VPN_CONNECTION_NAME) | |
def reconnect(): | |
disconnect() | |
time.sleep(5) | |
connect() | |
def log(cause): | |
f = open('vpn-issues.txt', 'a') | |
f.write(str(datetime.now()) + ": Restarting: " +cause+" \n") | |
def restart_if_down(): | |
up = test_con() | |
if not up: | |
reconnect() | |
if __name__ == "__main__": | |
restart_if_down() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment