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模拟鼠标拖动操作的方法

python模拟鼠标拖动操作的方法

本文实例讲述了python模拟鼠标拖动操作的方法。分享给大家供大家参考。具体如下: pdf中的书签只有页码,准备把现有书签拖到一个目录中,然后添加自己页签。重复的拖动工作实在无趣,还是让...

解决pip install的时候报错timed out的问题

安装包的时候报错,执行:pip install pyinstaller 问题: File "c:\python\python35\lib\site-packages\pip\_ven...

使用Pyinstaller的最新踩坑实战记录

前言 将py编译成可执行文件需要使用PyInstaller,之前给大家介绍了关于利用PyInstaller将python程序.py转为.exe的方法,在开始本文之前推荐大家可以先看下这篇...

python+tifffile之tiff文件读写方式

背景 使用python操作一批同样分辨率的图片,合并为tiff格式的文件。 由于opencv主要用于读取单帧的tiff文件,对多帧的文件支持并不好。 通过搜索发现了两个比较有用的包:Ti...

python访问系统环境变量的方法

本文实例讲述了python访问系统环境变量的方法。分享给大家供大家参考。具体如下: #-------------------------------- # Name: en...