1 from __future__
import print_function
10 def try_connecting_to_socksport():
11 socks_socket
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
12 if socks_socket
.connect_ex(('127.0.0.1', socks_port
)):
13 tor_process
.terminate()
15 sys
.exit('Cannot connect to SOCKSPort')
20 l
= tor_process
.stdout
.readline()
21 if s
in l
.decode('utf8'):
24 def pick_random_port():
29 port
= random
.randint(10000, 60000)
30 s
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
31 if s
.connect_ex(('127.0.0.1', port
)) == 0:
38 if sys
.hexversion
< 0x02070000:
39 sys
.exit("ERROR: unsupported Python version (should be >= 2.7)")
41 if sys
.hexversion
> 0x03000000 and sys
.hexversion
< 0x03010000:
42 sys
.exit("ERROR: unsupported Python3 version (should be >= 3.1)")
44 control_port
= pick_random_port()
45 socks_port
= pick_random_port()
47 assert control_port
!= 0
48 assert socks_port
!= 0
50 if not os
.path
.exists(sys
.argv
[1]):
51 sys
.exit('ERROR: cannot find tor at %s' % sys
.argv
[1])
53 tor_path
= sys
.argv
[1]
55 tor_process
= subprocess
.Popen([tor_path
,
56 '-ControlPort', '127.0.0.1:{}'.format(control_port
),
57 '-SOCKSPort', '127.0.0.1:{}'.format(socks_port
),
58 '-FetchServerDescriptors', '0'],
59 stdout
=subprocess
.PIPE
,
60 stderr
=subprocess
.PIPE
)
62 if tor_process
== None:
63 sys
.exit('ERROR: running tor failed')
66 sys
.exit('Usage: %s <path-to-tor>' % sys
.argv
[0])
68 wait_for_log('Opened Control listener on')
70 try_connecting_to_socksport()
72 control_socket
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
73 if control_socket
.connect_ex(('127.0.0.1', control_port
)):
74 tor_process
.terminate()
76 sys
.exit('Cannot connect to ControlPort')
78 control_socket
.sendall('AUTHENTICATE \r\n'.encode('utf8'))
79 control_socket
.sendall('SETCONF SOCKSPort=0.0.0.0:{}\r\n'.format(socks_port
).encode('utf8'))
80 wait_for_log('Opened Socks listener')
82 try_connecting_to_socksport()
84 control_socket
.sendall('SETCONF SOCKSPort=127.0.0.1:{}\r\n'.format(socks_port
).encode('utf8'))
85 wait_for_log('Opened Socks listener')
87 try_connecting_to_socksport()
89 control_socket
.sendall('SIGNAL HALT\r\n'.encode('utf8'))
93 tor_process
.terminate()