Python脚本实现网卡流量监控

yipeiwu_com5年前Python基础
#/usr/bin/env/python
#coding=utf-8

import sys,re,time,os
maxdata = 50000 #单位KB
memfilename = '/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都限制流量,才搞了这个小脚本

相关文章

python 在指定范围内随机生成不重复的n个数实例

python 在指定范围内随机生成不重复的n个数实例

利用Python中的randomw.sample()函数实现 resultList=random.sample(range(A,B),N); #表示从[A,B]间随机生成N个数,结...

django2笔记之路由path语法的实现

9月23,Django 发布了2.0a1版本,这是一个 feature freeze 版本,如果没有什么意外的话,2.0正式版不会再增加新的功能了。按照以往的规律,预计正式版将在12月发...

浅析Python中的赋值和深浅拷贝

浅析Python中的赋值和深浅拷贝

python中,A object  = B object  是一种赋值操作,赋的值不是一个对象在内存中的空间,而只是这个对象在内存中的位置 。 此时当B对象里面的内...

python实现问号表达式(?)的方法

python中的and和or和其它语言的区别很大其它语言中的and和or都是返回bool类型的结果,python不是。它返回的是做and和or运算的其中一个值。那个值决定了这个表达式的值...

python pyinstaller打包exe报错的解决方法

python pyinstaller打包exe报错的解决方法

今天用python 使用pyinstaller打包exe出现错误 环境pyqt5 + python3.6 32位 在导入pyqt5包之前加上如下代码 import sys impo...