Copy Code code as follows:
#!/usr/bin/env python
Import Sys,time
From socket import socket
def read_interface (in_file):
With file (In_file) as F:
return F.readlines () [2:]
def set_interface (inter_msg):
dic={}
For i in Xrange (Len (inter_msg)):
Dic[inter_msg[i].split (":") [0].strip ()]={' in ': Inter_msg[i].split (":") [1].strip (). Split () [0], "out": inter_msg[i] . Split (":") [1].strip (). Split () [8]}
return dic
Carbon_server = ' 127.0.0.1 '
Carbon_port = 2003
Delay = 3
Sock = socket ()
Try
Sock.connect ((Carbon_server,carbon_port))
Except
print "couldn ' t connect to%" (server) s in port% (port) d, is carbon-agent.py running?% {' Server ': Carbon_server, ' Port ': CA Rbon_port}
Sys.exit (1)
While True:
now = Int (Time.time ())
Lines=[]
Int1=read_interface ("/proc/net/dev")
Inter_dic1=set_interface (INT1)
Time.sleep (1)
Int2=read_interface ("/proc/net/dev")
Inter_dic2=set_interface (Int2)
print int (Inter_dic2[inter_dic2.keys () [1]][' in ']), int (Inter_dic1[inter_dic1.keys () [1]]["in"])
For i in Xrange (Len (Inter_dic1.keys ())):
Lines.append ("interface.%s_in%s%d"% (Inter_dic1.keys () [I],int (Inter_dic2[inter_dic2.keys () [i]]["in"])-int (Inter _dic1[inter_dic1.keys () [i]][' in ']), now)
Lines.append ("interface.%s_out%s%d"% (Inter_dic1.keys () [I],int (Inter_dic2[inter_dic2.keys () [i]]["Out"])-int ( Inter_dic1[inter_dic1.keys () [i]]["Out"])
message = ' \ n '. Join (lines) + ' \ n '
print "Sending message\n"
print '-' * 80
Print message
Sock.sendall (Message)
Time.sleep (Delay)