Example of python monitoring network card traffic and drawing using graphite

Source: Internet
Author: User
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)

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.