Python script For nic traffic monitoring and python script traffic monitoring

Source: Internet
Author: User

Python script For nic traffic monitoring and python script traffic monitoring

#/Usr/bin/env/python # coding = utf-8import sys, re, time, osmaxdata = 50000 # Unit: KBmemfilename = '/tmp/newnetcardtransdata.txt' netcard = '/proc/net/dev' def checkfile (filename): if OS. path. isfile (filename): pass else: f = open (filename, 'w') f. write ('0') f. close () def get_net_data (): nc = netcard or '/proc/net/dev' fd = open (nc, "r") netcardstatus = False for line in fd. readlines (): if line. find ("eth0")> 0: netcardstatus = True field = line. split () recv = field [0]. split (":") [1] recv = recv or field [1] send = field [8] if not netcardstatus: fd. close () print 'Please setup your netcard 'sys. exit () fd. close () return (float (recv), float (send) def monfirst (filename): nowtime = time. strftime ('% m-% d % H: % m', time. localtime (time. time () sec = time. localtime (). tm_sec if nowtime = '01-01 00:00 ': if sec <10: f = open (filename, 'w') f. write ('0') f. close () def net_loop (): (recv, send) = get_net_data () checkfile (memfilename) monfirst (memfilename) lasttransdaraopen = open (memfilename, 'R') lasttransdata = lasttransdaraopen. readline () lasttransdaraopen. close () totaltrans = int (lasttransdata) or 0 while True: time. sleep (3) (new_recv, new_send) = get_net_data () recvdata = (new_recv-recv)/1024 senddata = (new_send-send)/1024 totaltrans + = int (recvdata) totaltrans + = int (senddata) memw = open (memfilename, 'w') memw. write (str (totaltrans) memw. close () if totaltrans> = maxdata: OS. system ('init 0') if _ name _ = "_ main _": net_loop ()

Run with the ROOT permission. maxdata exceeds the maximum traffic limit. If the system shuts down automatically, you can change the OS. system ('init 0') The command you want is mainly because the current VPS limits traffic and this small script is used.

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.