forked from NIT-Hamirpur-NITH/ProxyHelper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtorpinger
executable file
·148 lines (133 loc) · 5.22 KB
/
torpinger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#!/usr/bin/python3
# Python 3 required !!
# do 'pip3 install pysocks' for socks module
import argparse
import socket
import subprocess
import sys
import time
try:
import socks
except ImportError:
print('Pysocks not installed, do "pip3 install pysocks"')
print('If pip3 is not installed do "sudo apt-get install python3-pip"')
print('On older versions of Ubuntu it is possible that python3 is not installed\n\ Look up google for that')
sys.exit(1)
try:
from urllib.request import urlopen
except:
print('You are not using python3 but just python')
print('Run the script as "python3 {}"'.format(__file__))
sys.exit(2)
class TorPinger(object):
def __init__(self):
#### All configurable parts are listed below
# TO add
possible_sockets = [9050,9150]
## If multiple tor sockets are found active
## One with higher priority is selected
## Default behaviour is to prioritize tor-browser socket(9150) over
## tor-terminal socket(9050); if you are not sure, leave as it is
priority = [1,2]
## Comment the first url and uncomment 2nd url at production
# self.ping_url = 'http://icanhazip.com'
self.ping_url = 'http://www.msftncsi.com/ncsi.txt'
## time between two pings
## should be 30seconds ??
self.interval = 30
## timeout for one ping
## should be 5 seconds ??
self.timeout = 10
## If program doesn't find any active tor connection within these seconds, it
## will stop its operation and exit
self.timeout_for_socks = 1
## time it will wait to check if there is some update or note, no need to modify
self.timeout_one_check = 1
#### Do not modify below this
## Stores the socket of connection which I want to torping
self.SOCK_REAL = None
self.sockets = dict(zip(possible_sockets,priority))
def set_socket(self,SOCKS5_PROXY_PORT):
""" Set socks proxy for socket
"""
SOCKS5_PROXY_HOST = '127.0.0.1'
socks.setdefaultproxy(proxy_type=socks.PROXY_TYPE_SOCKS5,addr=SOCKS5_PROXY_HOST,port=SOCKS5_PROXY_PORT)
socket.socket = socks.socksocket
def ping_socket(self,url):
## below is only for testing
with open('/var/tmp/torpingtest','a') as f:
f.write(url)
## function to send GET to url
## !Important
## If tor is not yet network is proxy driven it will not give error and
## quit but instead it will be excepted, this is a hack that will allow
## it to run even when when tor is not connected
try:
resp = urlopen(url,timeout=self.timeout)
# print(resp.read().decode()[0:4])
print(resp.read())
resp.close()
except OSError as e:
print('Error:', e)
sys.exit(1)
def which_socks(self):
op = subprocess.check_output('netstat -lnt',shell=True).decode()
SOCKS = []
for SOCK in self.sockets:
success = False
## Comment below later
# print(op.find(str(SOCK)))
## If socket is open
if op.find(str(SOCK)) != -1:
SOCKS.append(SOCK)
print(SOCKS)
return SOCKS
def get_sock(self):
initT = time.time()
while time.time()-initT < self.timeout_for_socks:
SOCKS=self.which_socks()
time.sleep(self.timeout_one_check)
## If we get away from loop due to timeout, then exit
if len(SOCKS) == 0:
print('Sorry dude - couldn\'t find any active Tor connection in the'
' given time, exiting.')
return
## Else we are good to go and have a list of open tor sockets
## Of which we choose the one with highest priority
self.SOCK_REAL = max(SOCKS, key=lambda x: self.sockets[x])
def run_forever(self):
self.get_sock()
if self.SOCK_REAL==None:
sys.exit(3);
## Now we have the socket, so we
## set the socket
self.set_socket(self.SOCK_REAL)
## and ping the socket
while True:
try:
self.ping_socket(self.ping_url)
time.sleep(self.interval)
except KeyboardInterrupt:
print('\n\nCancelled run forever operation')
sys.exit(5)
if __name__=='__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-r','--run_forever',action='store_true',
help='This is will make script run indefinitely.'+\
'It is the default behaviour.');
parser.add_argument('-w','--which_socks',help='Tells which tor socket is open',
action='store_true');
parser.add_argument('-t','--terse',help='Sets output to be terse',\
action='store_true');
arg = parser.parse_args()
tpinger = TorPinger()
if arg.run_forever:
tpinger.run_forever()
elif arg.which_socks:
tpinger.get_sock()
if arg.terse:
print('Port: {}'.format(tpinger.SOCK_REAL))
else:
print('highest priority socks port is ',tpinger.SOCK_REAL)
else:
tpinger.run_forever()