這篇文章主要介紹了Python實現數通設備端口使用情況監控的方法,涉及Python針對設備監控的操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了Python實現數通設備端口使用情況監控的方法。分享給大家供大家參考。具體如下:
最近因工作需要,上面要求,每天需上報運維的幾百數通設備端口使用情況【】,雖然有現成網管監控工具監控設備狀態,但做報表,有點不方便,特寫了個小腳本。上傳的,為半成品可用程序
注:測試運行于ubuntn,需安裝snmpwalk工具,
目標數通設備,需做好相關snmp配置
- #/usr/bin/python
- #coding:utf-8
- import os,sys
- import re
- from pprint import pprint
- #甯歌鍘傚鏁伴€氳澶嘙IB鍊?
- MIB = {
- 'public':{
- 'ports':{
- 'string':'.1.3.6.1.2.1.2.2.1.2',
- 'status':'.1.3.6.1.2.1.2.2.1.8', #2 down
- }
- },
- 'huawei':{
- },
- 'cisco':{
- }
- }
- #绔彛鐘舵€佽漿鎹?
- def portStatus(_s):
- if int(_s)==2:
- return 'down'
- elif int(_s)==1:
- return 'up'
- else:
- return 'none'
- #鎵ц緋葷粺鍛戒護snmpwalk璋冪敤
- def snmpwalk(host,publicKey,iso):
- return [i.strip() for i in os.popen('/usr/bin/snmpwalk -c %s -v 2c %s %s'%(publicKey,host,iso)).readlines()]
- def getPorts(_ip,_public,option):
- if option == 'ports':
- postsString = (j.split('=')[1].split(':')[1].replace('"','').strip() for j in snmpwalk(_ip,_public,MIB['public']['ports']['string']))
- postsStatus = (int(j.split('=')[1].split(':')[1].strip()) for j in snmpwalk(_ip,_public,MIB['public']['ports']['status']))
- return zip(postsString,postsStatus)
- else:
- print('on this commmnad')
- publicKey = 'hi' #sunmp public key
- HOSTS={
- '10.221.98.2':{'type':'switch','origin':'quidway','public':publicKey},
- '10.221.98.3':{'type':'switch','origin':'quidway','public':publicKey},
- '10.221.97.108':{'type':'firewall','origin':'h3c','public':publicKey},
- '10.231.98.233':{'type':'switch','origin':'cisco','public':publicKey},
- }
- if __name__ == '__main__':
- for i in HOSTS.keys():
- for host,status in getPorts(i,HOSTS[i]['public'],'ports'):
- print("%s/t%s/t%s"%(i,host.ljust(30),portStatus(status).ljust(20)))
- print(''.ljust(50,'#'))
運行結果:
root@ubuntn12:/tmp# python snmpwalk.py
10.221.98.2 InLoopBack0 up
10.221.98.2 NULL0 up
10.221.98.2 GigabitEthernet0/0/0 down
10.221.98.2 Aux0/0/1 down
10.221.98.2 Vlanif100 up
10.221.98.2 Eth-Trunk1 down
10.221.98.2 Eth-Trunk1.32 down
10.221.98.2 Eth-Trunk1.50 down
10.221.98.2 Eth-Trunk1.60 down
10.221.98.2 Eth-Trunk1.70 down
10.221.98.2 Eth-Trunk1.80 down
10.221.98.2 Eth-Trunk1.100 down
10.221.98.2 Eth-Trunk1.110 down
.......
希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答