Python monitors network card traffic and uses the graphite drawing sample _python

Source: Internet
Author: User
Tags sleep

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.