python用snmp协议监控网卡流量

发布时间:2019-12-27编辑:脚本学堂
python编写网卡流量监控脚本,通过snmp协议获取系统信息,计算并将数据格式化,输出网卡流量监控结果,用到了os模块与re正则表达式模块。

python监控网卡流量

代码:
 

复制代码 代码示例:
#!/usr/bin/env python
# -*- coding=utf-8 -*-
#using gpl v2.7
#python监控网卡流量
"""
1、实现原理:通过snmp协议获取系统信息,再进行相应的计算和格式化,最后输出结果
2、特别注意:被监控的机器上需要支持snmp。yum install -y net-snmp*安装
"""
import re
import os
#get snmp-mib2 of the devices
def getallitems(host,oid):
        sn1 = os.popen('snmpwalk -v 2c -c public ' + host + ' ' + oid).read().split('n')[:-1]
        return sn1
                                                                                     
#get network device
def getdevices(host):
        device_mib = getallitems(host,'rfc1213-mib::ifdescr')
        device_list = []
        for item in device_mib:
                if re.search('eth',item):
                        device_list.append(item.split(':')[3].strip())
        return device_list
                                                                                     
#get network date
def getdate(host,oid):
        date_mib = getallitems(host,oid)[1:]
        date = []
        for item in date_mib:
                byte = float(item.split(':')[3].strip())
                date.append(str(round(byte/1024,2)) + ' kb')
        return date
                                                                                     
if __name__ == '__main__':
        hosts = ['192.168.10.1','192.168.10.2']
        for host in hosts:
                device_list = getdevices(host)
                                                                                     
                inside = getdate(host,'if-mib::ifinoctets')
                outside = getdate(host,'if-mib::ifoutoctets')
                                                                                     
                print '==========' + host + '=========='
                for i in range(len(inside)):
                        print '%s : rx: %-15s  tx: %s ' % (device_list[i], inside[i], outside[i])
                print