Python腳本實現(xiàn)網(wǎng)卡流量監(jiān)控
更新時間:2015年02月14日 11:12:11 投稿:junjie
這篇文章主要介紹了Python腳本實現(xiàn)網(wǎng)卡流量監(jiān)控,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下
#/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權(quán)限運行,maxdata為最大流量限制 超過這個限制,系統(tǒng)自動關(guān)機 當(dāng)然,你可以改os.system('init 0')為你想要的命令 主要是現(xiàn)在VPS都限制流量,才搞了這個小腳本
相關(guān)文章
Python深度學(xué)習(xí)albumentations數(shù)據(jù)增強庫
下面開始albumenations的正式介紹,在這里我強烈建議英語基礎(chǔ)還好的讀者去官方網(wǎng)站跟著教程一步步學(xué)習(xí),而這里的內(nèi)容主要是我自己的一個總結(jié)以及方便英語能力較弱的讀者學(xué)習(xí)2021-09-09
Python實現(xiàn)Window路徑格式轉(zhuǎn)換為Linux路徑格式的代碼
這篇文章主要介紹了Python實現(xiàn)Window路徑格式轉(zhuǎn)換為Linux路徑格式的方法,文中通過代碼示例講解的非常詳細,對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-07-07
Object arrays cannot be loaded when
這篇文章主要介紹了Object arrays cannot be loaded when allow_pickle=False,本文給大家分享問題解決思路,需要的朋友可以參考下2022-11-11

