import time
import threading
import signal
from datetime import datetime
last_in_bytes = None
last_out_bytes = None
def (inf):
global last_in_bytes, last_out_bytes
in_traffic, out_traffic = None, None
with open('/proc/net/dev') as f:
lines = f.readlines()
for line in lines[2:]:
line = line.strip()
if line.startswith(inf + ':'):
items = line.strip().split(':')[1].split()
in_bytes, out_bytes = int(items[0]), int(items[8])
if last_in_bytes:
in_traffic, out_traffic = in_bytes - last_in_bytes, out_bytes - last_out_bytes
last_in_bytes, last_out_bytes = in_bytes, out_bytes
return in_traffic, out_traffic
next_thread = None
exit_flag = False
def thread_job(f_handler, inf='eth0', interval=2):
global next_thread, exit_flag
time.sleep(interval)
if not exit_flag:
next_thread = threading.Thread(target=thread_job, args=(f_handler, inf, interval))
next_thread.start()
else:
next_thread = None
time_stamp = int(time.time())
in_traffic, out_traffic = curr_traffic(inf)
print in_traffic, out_traffic
if in_traffic is not None and out_traffic is not None and not f_handler.closed:
f_handler.write('%d, %d, %dn' % (time_stamp, in_traffic, out_traffic))
def exit_func(signum, stack):
global exit_flag
exit_flag = True
print("Exiting ...")
cnt = 0
while not next_thread and cnt < 3:
time.sleep(1)
cnt += 1
if cnt >= 3:
next_thread.exit()
def output_traffics(outfile, inf='eth0', interval=1):
with open(outfile, 'w') as f:
f.write('time, in_rate(B/s), out_rate(B/s)n')
thread_job(f, inf, interval)
while not exit_flag:
time.sleep(1)
if __name__ == '__main__':
signal.signal(signal.SIGINT, exit_func)
signal.signal(signal.SIGINT, exit_func)
args = {
'outfile': time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())) + '.csv',
'inf': 'eth0',
'interval': 1
}
output_traffics(**args)
近期评论