使用python实现流量监控,实现watch 执行下边的python脚本,参数为监控的网卡名
在这里插入图片描述
#!/usr/bin/python
import os
import time
import sys
shell = “cat /proc/net/dev | sed -e ‘s/?/g’ | grep " + sys.argv[1] + " | awk ‘{print $2,$10}’”
fp = os.popen(shell)
data1 = fp.read()
fp.close()
time.sleep(1)
fp = os.popen(shell)
data2 = fp.read()
fp.close()
if not data1:
print(“interface is invalid”)
else:
rx = (float)(data2.split()[0])*8 - (float)(data1.split()[0])*8
tx = (float)(data2.split()[1])*8 - (float)(data1.split()[1])*8
if rx < 1024:
rxtd = str(rx) + “bits”
elif rx < 1048576:
rxtd = str(rx) + “Kbits”
else :
rxtd = str(rx) + “Mbits”

if tx < 1024:
txtd = str(tx) + “bits”
elif tx < 1048576:
txtd = str(tx) + “Kbits”
else :
txtd = str(tx) + “Mbits”
print"interface\t\trx\t\ttx\n%s\t\t%s\t\t%s" % (sys.argv[1],rxtd,txtd)

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐