天天看點

linux 監控 網卡IO

示例:點選 -> 性能監控

通過/proc/net/dev擷取網卡 IO,第1列和第9列分别代表了in 和out。

[root@wangzi go]#  cat /proc/net/dev
Inter-|   Receive                                                |  Transmit
 face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
  eth0: 10020876640 52702968    0    0    0     0          0         0 11473861781 54530293    0    0    0     0       0          0
    lo: 6454958709 6187408    0    0    0     0          0         0 6454958709 6187408    0    0    0     0       0          0           

複制

python代碼:

#!/usr/bin/env python
# coding=utf-8
# author: brownwang
# mail: [email protected]
# datetime:2019/3/31 1:03 PM
# web: https://www.bthlt.com


def write_net_io():
    net_in=0
    net_out=0
    add_net_in=0
    add_net_out=0
    with open('/proc/net/dev', 'r') as file:
        for line in file.readlines():
            if 'eth0' in line:
                net_in=int(line.split()[1])/1024
                net_out=int(line.split()[9])/1024
    select_sql="""select `in`,`out` from monitor_net_io order by id desc limit 1"""
    result=cursorQuery(select_sql,[])
    if len(result)>0:
        add_net_in=net_in-int(result[0][0])
        add_net_out=net_out-int(result[0][1])
    insert_sql="""insert into `monitor_net_io` (`in`,`out`,`add_in`,`add_out`,`flow_time`) values ({0},{1},{2},{3},'{4}')""".format(net_in,net_out,add_net_in,add_net_out,now_zero)
    cursorUpdate(insert_sql,[])           

複制