Python脚本实现网卡流量监控

yipeiwu_com6年前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都限制流量,才搞了这个小脚本

相关文章

Django如何实现网站注册用户邮箱验证功能

Django如何实现网站注册用户邮箱验证功能

我们在很多网站上都可以看到用户注册使用电子邮件激活或启用的方式。也就是说,用户在注册后填写正确的电子邮件地址,接着网站会发送一封启用电子邮件到用户设置的电子邮件的邮箱中,并在邮件中提供一...

python使用pandas处理大数据节省内存技巧(推荐)

python使用pandas处理大数据节省内存技巧(推荐)

一般来说,用pandas处理小于100兆的数据,性能不是问题。当用pandas来处理100兆至几个G的数据时,将会比较耗时,同时会导致程序因内存不足而运行失败。 当然,像Spark这类的...

python3安装speech语音模块的方法

python3安装speech语音模块的方法

在windows平台上使用pyhton编写语音识别程序需要用到speech模块,speech模块支持的主要功能有:文本合成语音,将键盘输入的文本信息转换为语音信号方式输出;语音识别,将输...

Python实现的简单读写csv文件操作示例

Python实现的简单读写csv文件操作示例

本文实例讲述了Python实现的简单读写csv文件操作。分享给大家供大家参考,具体如下: python中有一个读写csv文件的包,直接import csv即可 新建test.csv 1....

如何通过python实现人脸识别验证

这篇文章主要介绍了如何通过python实现人脸识别验证,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 直接上代码,此案例是根据http...