Python指令碼實現網卡流量監控

來源:互聯網
上載者:User
#/usr/bin/env/python#coding=utf-8import sys,re,time,osmaxdata = 50000 #單位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()

用ROOT許可權運行,maxdata為最大流量限制 超過這個限制,系統自動關機 當然,你可以改os.system('init 0')為你想要的命令 主要是現在VPS都限制流量,才搞了這個小指令碼

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.