IceGuye Blog

Upgrade the Auto Reconnection Tool for Sshuttle for Python 3

Just copy the code and run.

#!/usr/bin/env python3

import subprocess
import os
import sys
import time
import traceback
import urllib
import psutil
import shelve
import requests
import random
import re

# Enter some websites. Make sure you can see the website in your
# country without any secured connection.

servers = ['http://ip.cn/',
           'http://ip.42.pl/raw',
           'http://jsonip.com',
           'http://httpbin.org/ip',
           'https://api.ipify.org/?format=json']

def get_ip():
    try:
        page = requests.get(random.choice(servers), timeout=5).text
        ip = re.search('(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', page)
    except:
        ip = None

    if ip is not None and ip.group is not None:
        return ip.group(0)
    else:
        return "nothing"

def main():
    try:
        gateway = sys.argv[1]
        subnets = sys.argv[2:]

    except Exception:
        print (traceback.format_exc())
        usage()

    orn_ip = get_ip()

    command = 'sshuttle -r %s %s' % (gateway, ' '.join(subnets))
    print ('-' * 10, command)
    proc = subprocess.Popen(['/bin/bash', '-c', command])
    crn_ip = get_ip()

    wc = 0 
    while True:
        time0 = time.time()
        net_rcv0 = psutil.net_io_counters()[1]
        time.sleep(1)
        time1 = time.time()
        net_rcv1 = psutil.net_io_counters()[1]
        net_spd = ((net_rcv1 - net_rcv0) * 0.001) / (time1 - time0)
        print ("---- Download speed: %d Kb/s" %(net_spd))
        print ("---- Your ip is: " + crn_ip)
        if wc % 5 == 0:
            if crn_ip == orn_ip:
                crn_ip = get_ip()
            if net_spd < 1 and proc is not None:
                crn_ip = get_ip()
                if crn_ip == "nothing":
                    print ("---- Killed the sshuttle for restart.")
                    proc.kill()
                    proc = None

            if proc is not None:
                if proc.returncode is not None:
                    print ("---- Killed the sshuttle for restart.")
                    proc.kill()
                    proc = None
            else:
                crn_ip = get_ip()
                if crn_ip == "nothing":
                    print ("---- Waiting for Internet.")
                elif crn_ip == orn_ip:
                    print ("---- Restarting the sshuttle.")
                    proc = subprocess.Popen(['/bin/bash', '-c', command])
        wc = wc + 1
        if wc >= 65532:
            wc = 0

def usage():
    print ("""
./sshuttle-ar.py    ...
""")


if __name__ == "__main__":
    main()

Have fun; be free!




Back to Blog's index