很多时候,我们是需要查看服务器的网卡当前跑了多大流量,但对于网卡流量的查询,在linux下似乎没有像top那样的原生命令。虽然top功能很强大,可以实时查看cpu、内存、进程的动态,但是却没有对网卡流量的监控。既然没有,那那就自己写一个吧,哈哈。本文代码综合使用了psutil和curses模块,脚本工具同时支持在linux和windows下使用,支持动态查看网卡流量。当然现在也有些第三方的工具可以使用,比如iftop。
psutil可以获取系统的很多信息,包括CPU,内存,磁盘,网络,并且还可以查看系统进程等信息。psutil是一个跨平台的库,支持linux、windows、freebsd、OSX等多个操作系统平台。
curses库提供一个独立于终端的屏幕显示,支持各种控制代码来执行常见的操作,如移动光标、滚动屏幕和擦除区域。curses库将终端屏幕看成是由字符单元组成的坐标系,每一个单元由行坐标和列坐标来标示。坐标原点是屏幕的左上角,行坐标自上而下递增,列坐标自左而右递增。
利用psutil获取到网卡的上传下载流量,计算出当前网卡的流量速率。然后利用curses将流量数据动态的输出到终端,实现top命令类似的动态刷新效果。
# -*- coding:utf-8 -*-
"""
@Author: Rainbowhhy
@Date: 2020-12-04 10:00:00
"""
import psutil
import time
from datetime import datetime
import curses
import argparse
def getNetworkData():
# 获取网卡流量信息
recv = {}
sent = {}
data = psutil.net_io_counters(pernic=True)
interfaces = data.keys()
for interface in interfaces:
recv.setdefault(interface, data.get(interface).bytes_recv)
sent.setdefault(interface, data.get(interface).bytes_sent)
return interfaces, recv, sent
def getNetworkRate(num):
# 计算网卡流量速率
interfaces, oldRecv, oldSent = getNetworkData()
time.sleep(num)
interfaces, newRecv, newSent = getNetworkData()
networkIn = {}
networkOut = {}
for interface in interfaces:
networkIn.setdefault(interface, float("%.3f" % ((newRecv.get(interface) - oldRecv.get(interface)) / num)))
networkOut.setdefault(interface, float("%.3f" % ((newSent.get(interface) - oldSent.get(interface)) / num)))
return interfaces, networkIn, networkOut
def output(num, unit):
# 将监控输出到终端
stdscr = curses.initscr()
curses.start_color()
# curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
curses.noecho()
curses.cbreak()
stdscr.clear()
try:
# 第一次初始化
interfaces, _, _ = getNetworkData()
currTime = datetime.now()
timeStr = datetime.strftime(currTime, "%Y-%m-%d %H:%M:%S")
stdscr.addstr(0, 0, timeStr)
i = 1
for interface in interfaces:
if interface != "lo" and bool(1 - interface.startswith("veth")) and bool(
1 - interface.startswith("蓝牙")) and bool(1 - interface.startswith("VMware")):
if unit == "K" or unit == "k":
netIn = "%12.2fKB/s" % 0
netOut = "%11.2fKB/s" % 0
elif unit == "M" or unit == "m":
netIn = "%12.2fMB/s" % 0
netOut = "%11.2fMB/s" % 0
elif unit == "G" or unit == "g":
netIn = "%12.3fGB/s" % 0
netOut = "%11.3fGB/s" % 0
else:
netIn = "%12.1fB/s" % 0
netOut = "%11.1fB/s" % 0
stdscr.addstr(i, 0, interface)
stdscr.addstr(i + 1, 0, "Input:%s" % netIn)
stdscr.addstr(i + 2, 0, "Output:%s" % netOut)
stdscr.move(i + 3, 0)
i += 4
stdscr.refresh()
# 第二次开始循环监控网卡流量
while True:
_, networkIn, networkOut = getNetworkRate(num)
currTime = datetime.now()
timeStr = datetime.strftime(currTime, "%Y-%m-%d %H:%M:%S")
stdscr.erase()
stdscr.addstr(0, 0, timeStr)
i = 1
for interface in interfaces:
if interface != "lo" and bool(1 - interface.startswith("veth")) and bool(
1 - interface.startswith("蓝牙")) and bool(1 - interface.startswith("VMware")):
if unit == "K" or unit == "k":
netIn = "%12.2fKB/s" % (networkIn.get(interface) / 1024)
netOut = "%11.2fKB/s" % (networkOut.get(interface) / 1024)
elif unit == "M" or unit == "m":
netIn = "%12.2fMB/s" % (networkIn.get(interface) / 1024 / 1024)
netOut = "%11.2fMB/s" % (networkOut.get(interface) / 1024 / 1024)
elif unit == "G" or unit == "g":
netIn = "%12.3fGB/s" % (networkIn.get(interface) / 1024 / 1024 / 1024)
netOut = "%11.3fGB/s" % (networkOut.get(interface) / 1024 / 1024 / 1024)
else:
netIn = "%12.1fB/s" % networkIn.get(interface)
netOut = "%11.1fB/s" % networkOut.get(interface)
stdscr.addstr(i, 0, interface)
stdscr.addstr(i + 1, 0, "Input:%s" % netIn)
stdscr.addstr(i + 2, 0, "Output:%s" % netOut)
stdscr.move(i + 3, 0)
i += 4
stdscr.refresh()
except KeyboardInterrupt:
# 还原终端
curses.echo()
curses.nocbreak()
curses.endwin()
except Exception as e:
curses.echo()
curses.nocbreak()
curses.endwin()
print("ERROR: %s!" % e)
print("Please increase the terminal size!")
finally:
curses.echo()
curses.nocbreak()
curses.endwin()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="A command for monitoring the traffic of network interface! Ctrl + C: exit")
parser.add_argument("-t", "--time", type=int, help="the interval time for ouput", default=1)
parser.add_argument("-u", "--unit", type=str, choices=["b", "B", "k", "K", "m", "M", "g", "G"],
help="the unit for ouput", default="B")
parser.add_argument("-v", "--version", help="output version information and exit", action="store_true")
args = parser.parse_args()
if args.version:
print("v1.0")
exit(0)
num = args.time
unit = args.unit
output(num, unit)
1.仅支持python3。
2.需安装psutil库,windows需安装curses库,linux默认自带,如果没有也需安装。
3.支持指定刷新时间间隔,-t或者–time。
4.支持指定流量输出单位,-u或者–unit。
5.使用示例:
(1)每5秒刷新一次数据,流量单位为M/s
python3 network.py -t 5 -u M或者python3 network.py -t 5 -u m
(2)默认不指定参数,表示每一秒刷新一次数据,流量单位为B/s
python3 network.py
可以使用工具将脚本打包成二进制文件,之后可以像执行linux命令那样直接执行,无需安装依赖包。
networkstat下载
目前支持Ubuntu14.04以上,CentOS7以上,Debian8以上,Windows10,Windows2008R2以上。