This article describes how to monitor network card traffic in python and use graphite graphics. For more information, see the following code:
#! /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 = '2017. 0.0.1'
Carbon_ports = 2003
Delay = 3
Sock = socket ()
Try:
Sock. connect (CARBON_SERVER, CARBON_PORT ))
Except t:
Print "Couldn't connect to % (server) s on port % (port) d, is carbon-agent.py running? "% {'Server': CARBON_SERVER, 'port': CARBON_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"]), now ))
Message = '\ n'. join (lines) +' \ n'
Print "sending message \ n"
Print '-' * 80
Print message
Sock. sendall (message)
Time. sleep (delay)