Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import netifaces
- import subprocess
- import os
- import glob
- from pprint import pprint
- from time import sleep, time
- import psutil
- from datetime import datetime
- import pycurl
- import random
- try:
- from io import BytesIO
- except ImportError:
- from StringIO import StringIO as BytesIO
- con_nums = 5
- kill_num = 3
- cur_dir = os.path.dirname(os.path.realpath(__file__))
- cur_dt = datetime.now().strftime('%d.%m.%Y %H:%M:%S')
- class cd:
- """Context manager for changing the current working directory"""
- def __init__(self, newPath):
- self.newPath = os.path.expanduser(newPath)
- def __enter__(self):
- self.savedPath = os.getcwd()
- os.chdir(self.newPath)
- def __exit__(self, etype, value, traceback):
- os.chdir(self.savedPath)
- def get_tuns():
- interfaces = netifaces.interfaces()
- tuns = []
- for interface in interfaces:
- if interface[:3] == 'tun':
- tuns.append(interface)
- return tuns
- def tun2num(tun):
- num = tun[3:]
- return int(num)
- def get_pid(name):
- return subprocess.check_output(["pidof",name])
- def killErVPN():
- pids = psutil.pids()
- for pid in pids:
- try:
- pid = psutil.Process(pid)
- if (pid.name() == 'openvpn'):
- tun = pid.cmdline()[5]
- buffer = BytesIO()
- c = pycurl.Curl()
- c.setopt(c.URL, 'http://ipecho.net/plain')
- c.setopt(c.TIMEOUT, 5)
- c.setopt(c.INTERFACE, tun)
- c.setopt(c.WRITEDATA, buffer)
- try:
- c.perform()
- body = buffer.getvalue()
- print(body.decode('utf-8'))
- except:
- print('kill', tun)
- pid.terminate()
- except:
- pass
- # f = open(cur_dir+'/timer')
- # LastTime = float(f.read())
- # f.close()
- # CurTime = time()
- # if CurTime - LastTime > 60:
- # tuns = get_tuns()
- # if len(tuns) > kill_num:
- # tuns4kill = random.sample(tuns, kill_num)
- # for tun in tuns4kill:
- # pids = psutil.pids()
- # for pid in pids:
- # try:
- # pid = psutil.Process(pid)
- # if (pid.name() == 'openvpn'):
- # if (pid.cmdline()[5] == tun):
- # print('kill', tun)
- # pid.terminate()
- # except:
- # pass
- def reconnect():
- killErVPN()
- conn_names = []
- conn_status = []
- pids = psutil.pids()
- for pid in pids:
- try:
- pid = psutil.Process(pid)
- if (pid.name() == 'openvpn'):
- if(len(pid.connections())):
- conn_names.append(pid.cmdline()[3])
- print(pid.cmdline()[3])
- else:
- pid.terminate()
- except:
- pass
- with cd(cur_dir+'/vpns'):
- tuns = list(map(tun2num, get_tuns()))
- print('LEN: ', len(tuns))
- if (len(tuns) < con_nums):
- ovpns = glob.glob('*.ovpn')
- vpn_nums = list(range(len(ovpns)))
- nc_tuns = list(set(vpn_nums) - set(tuns))
- nc_tuns.sort()
- nc_names = list(set(ovpns) - set(conn_names))
- for i in range(con_nums - len(tuns)):
- print(i,')', ' openvpn --route-noexec --config ', nc_names[i], ' --dev ', ('tun'+str(nc_tuns[i])))
- proc = subprocess.Popen(['nohup', 'openvpn','--route-noexec', '--config', nc_names[i], '--dev', ('tun'+str(nc_tuns[i])), '&'], stderr=subprocess.PIPE)
- StartTime = time()
- while True:
- CurTime = time()
- if CurTime - StartTime > 60:
- proc.kill()
- print('VPN ' + nc_names[i] + ' killed!')
- break
- else:
- sleep(1)
- try:
- ip = netifaces.ifaddresses('tun'+str(nc_tuns[i]))[2][0]['addr']
- f = open('/etc/3proxy/ips/'+'tun'+str(nc_tuns[i]), 'w')
- f.write(ip)
- f.close()
- except:
- pass
- else:
- print(nc_names[i], " - ", ip)
- subprocess.call(['ip', 'rule', 'add', 'from', ip, 'lookup', 'viatun'+str(nc_tuns[i])])
- subprocess.call(['ip', 'route', 'add', 'default', 'dev', 'tun'+str(nc_tuns[i]), 'table', 'viatun'+str(nc_tuns[i])])
- break
- print(len(get_tuns()), ' VPNs connected!')
- sleep(3)
- if len(get_tuns()) < con_nums:
- subprocess.call(['python3', 'vpn_v.py'])
- else:
- try:
- get_pid('3proxy')
- subprocess.call(['/etc/init.d/3proxyinit', 'restart'])
- except:
- subprocess.call(['/etc/init.d/3proxyinit', 'start'])
- f = open(cur_dir+'/timer', 'w')
- CurTime = time()
- f.write(str(CurTime))
- f.close()
- reconnect()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement