歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python監控網卡流量

Python監控網卡流量

日期:2017/3/1 9:39:30   编辑:Linux編程

Python監控網卡流量

#!/usr/bin/env python
# -*- coding=utf-8 -*-
#Using GPL v2.7
#Author: [email protected]
#Python監控網卡流量
"""
1、實現原理:通過SNMP協議獲取系統信息,再進行相應的計算和格式化,最後輸出結果
2、特別注意:被監控的機器上需要支持snmp。yum install -y net-snmp*安裝
"""
#!/usr/bin/python
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

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved