Advertisement
Guest User

Untitled

a guest
Mar 12th, 2017
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.14 KB | None | 0 0
  1. import netifaces
  2. import subprocess
  3. import os
  4. import glob
  5. from pprint import pprint
  6. from time import sleep, time
  7. import psutil
  8. from datetime import datetime
  9. import pycurl
  10. import random
  11.  
  12. try:
  13.     from io import BytesIO
  14. except ImportError:
  15.     from StringIO import StringIO as BytesIO
  16.  
  17. con_nums = 5
  18. kill_num = 3
  19.  
  20. cur_dir = os.path.dirname(os.path.realpath(__file__))
  21. cur_dt = datetime.now().strftime('%d.%m.%Y %H:%M:%S')
  22.  
  23. class cd:
  24.     """Context manager for changing the current working directory"""
  25.     def __init__(self, newPath):
  26.         self.newPath = os.path.expanduser(newPath)
  27.  
  28.     def __enter__(self):
  29.         self.savedPath = os.getcwd()
  30.         os.chdir(self.newPath)
  31.  
  32.     def __exit__(self, etype, value, traceback):
  33.         os.chdir(self.savedPath)
  34.  
  35. def get_tuns():
  36.     interfaces = netifaces.interfaces()
  37.     tuns = []
  38.     for interface in interfaces:
  39.         if interface[:3] == 'tun':
  40.             tuns.append(interface)
  41.     return tuns
  42.  
  43. def tun2num(tun):
  44.     num = tun[3:]
  45.     return int(num)
  46.  
  47. def get_pid(name):
  48.     return subprocess.check_output(["pidof",name])
  49.  
  50.  
  51. def killErVPN():
  52.     pids = psutil.pids()
  53.  
  54.     for pid in pids:
  55.         try:
  56.             pid = psutil.Process(pid)
  57.             if (pid.name() == 'openvpn'):
  58.  
  59.                 tun = pid.cmdline()[5]
  60.  
  61.                 buffer = BytesIO()
  62.                 c = pycurl.Curl()
  63.                 c.setopt(c.URL, 'http://ipecho.net/plain')
  64.                 c.setopt(c.TIMEOUT, 5)
  65.                 c.setopt(c.INTERFACE, tun)
  66.                 c.setopt(c.WRITEDATA, buffer)
  67.  
  68.                 try:
  69.                     c.perform()
  70.                     body = buffer.getvalue()
  71.                     print(body.decode('utf-8'))
  72.                 except:
  73.                     print('kill', tun)
  74.                     pid.terminate()
  75.         except:
  76.             pass
  77.  
  78.     # f = open(cur_dir+'/timer')
  79.     # LastTime = float(f.read())
  80.     # f.close()
  81.     # CurTime = time()
  82.     # if CurTime - LastTime > 60:
  83.  
  84.     #   tuns = get_tuns()
  85.  
  86.     #   if len(tuns) > kill_num:
  87.  
  88.     #       tuns4kill = random.sample(tuns, kill_num)
  89.  
  90.     #       for tun in tuns4kill:
  91.     #           pids = psutil.pids()
  92.     #           for pid in pids:
  93.     #               try:
  94.     #                   pid = psutil.Process(pid)
  95.     #                   if (pid.name() == 'openvpn'):
  96.     #                       if (pid.cmdline()[5] == tun):
  97.     #                           print('kill', tun)
  98.     #                           pid.terminate()
  99.     #               except:
  100.     #                   pass
  101.  
  102.  
  103. def reconnect():
  104.     killErVPN()
  105.    
  106.    
  107.     conn_names = []
  108.     conn_status = []
  109.     pids = psutil.pids()
  110.     for pid in pids:
  111.         try:
  112.             pid = psutil.Process(pid)
  113.             if (pid.name() == 'openvpn'):
  114.                
  115.                 if(len(pid.connections())):
  116.                    
  117.                     conn_names.append(pid.cmdline()[3])
  118.                     print(pid.cmdline()[3])
  119.  
  120.                 else:
  121.                     pid.terminate()
  122.         except:
  123.             pass
  124.  
  125.     with cd(cur_dir+'/vpns'):
  126.         tuns = list(map(tun2num, get_tuns()))
  127.         print('LEN: ', len(tuns))
  128.         if (len(tuns) < con_nums):
  129.             ovpns = glob.glob('*.ovpn')
  130.             vpn_nums = list(range(len(ovpns)))
  131.             nc_tuns = list(set(vpn_nums) - set(tuns))
  132.             nc_tuns.sort()
  133.             nc_names = list(set(ovpns) - set(conn_names))
  134.            
  135.  
  136.             for i in range(con_nums - len(tuns)):
  137.                 print(i,')', ' openvpn --route-noexec --config ', nc_names[i], ' --dev ', ('tun'+str(nc_tuns[i])))
  138.                 proc = subprocess.Popen(['nohup', 'openvpn','--route-noexec', '--config', nc_names[i], '--dev', ('tun'+str(nc_tuns[i])), '&'], stderr=subprocess.PIPE)
  139.                 StartTime = time()
  140.                 while True:
  141.                     CurTime = time()
  142.                     if CurTime - StartTime > 60:
  143.                         proc.kill()
  144.                         print('VPN ' +  nc_names[i] + ' killed!')
  145.                         break
  146.                     else:
  147.                         sleep(1)
  148.                         try:
  149.                             ip = netifaces.ifaddresses('tun'+str(nc_tuns[i]))[2][0]['addr']
  150.                             f = open('/etc/3proxy/ips/'+'tun'+str(nc_tuns[i]), 'w')
  151.                             f.write(ip)
  152.                             f.close()
  153.                         except:
  154.                             pass
  155.                         else:
  156.                             print(nc_names[i], " - ", ip)
  157.                             subprocess.call(['ip', 'rule', 'add', 'from', ip, 'lookup', 'viatun'+str(nc_tuns[i])])
  158.                             subprocess.call(['ip', 'route', 'add', 'default', 'dev', 'tun'+str(nc_tuns[i]), 'table', 'viatun'+str(nc_tuns[i])])
  159.                             break
  160.  
  161.         print(len(get_tuns()), ' VPNs connected!')
  162.         sleep(3)
  163.        
  164.        
  165.  
  166.     if len(get_tuns()) < con_nums:
  167.         subprocess.call(['python3', 'vpn_v.py'])
  168.     else:
  169.         try:
  170.             get_pid('3proxy')
  171.             subprocess.call(['/etc/init.d/3proxyinit', 'restart'])
  172.         except:
  173.             subprocess.call(['/etc/init.d/3proxyinit', 'start'])
  174.        
  175.     f = open(cur_dir+'/timer', 'w')
  176.     CurTime = time()
  177.     f.write(str(CurTime))
  178.     f.close()
  179.  
  180.  
  181. reconnect()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement