-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtor-bw.py
131 lines (97 loc) · 2.35 KB
/
tor-bw.py
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
#!/usr/bin/python
#------------------------------------------
#
# A script to write a Tor relay's
# bandwidth data to disk
#
# Author : Luiz Kill
# Date : 21/11/2014
#
# http://lzkill.com
#
#------------------------------------------
import os
import sys
import time
import functools
from stem.control import EventType, Controller, Signal
TOR_CONTROL_PORT = 9051
TOR_ADDRESS = "127.0.0.1"
TOR_CONTROLLER_PASSWD = ""
TOR_RECONNECT_DELAY = 5.0
# The Tor controller object
tor_controller = None
is_tor_alive = False
# Location of the Tor bw files
PATH="/var/lib/rpimonitor/stat/"
file_rx = None
file_tx = None
rx = 0
tx = 0
def main():
global tor_controller
global is_tor_alive
global file_rx
global file_tx
try:
file_rx = open(PATH + "tor_rx", "wb")
file_tx = open(PATH + "tor_tx", "wb")
while True:
if tor_controller == None:
try:
tor_controller = Controller.from_port(address=TOR_ADDRESS, port=TOR_CONTROL_PORT)
except Exception as exc:
print(time.ctime(),exc)
elif tor_controller.is_authenticated() == False:
try:
tor_controller.authenticate(password=TOR_CONTROLLER_PASSWD)
except Exception as exc:
print(time.ctime(),exc)
else:
tor_bind()
is_tor_alive = (tor_controller != None and tor_controller.is_authenticated())
time.sleep(TOR_RECONNECT_DELAY)
except Exception as exc:
print(time.ctime(),exc)
finally:
tor_disconnect()
file_rx.close()
file_tx.close()
def tor_disconnect():
global is_tor_alive
global tor_controller
if tor_controller:
try:
tor_unbind()
tor_controller.close()
except Exception as exc:
print(time.ctime(),exc)
pass
is_tor_alive = False
tor_controller = None
def tor_bind():
global tor_controller
global tor_bw_event_handler
if tor_controller:
tor_bw_event_handler = functools.partial(handle_bandwidth_event)
tor_controller.add_event_listener(tor_bw_event_handler, EventType.BW)
def tor_unbind():
global tor_controller
global tor_bw_event_handler
if tor_controller:
tor_controller.remove_event_listener(tor_bw_event_handler)
def handle_bandwidth_event(event):
global file_rx
global file_tx
global rx
global tx
rx += event.read
tx += event.written
file_rx.seek(0)
file_rx.write(str(rx))
file_rx.truncate()
file_tx.seek(0)
file_tx.write(str(tx))
file_tx.truncate()
if __name__ == '__main__':
main()