欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python实现数通设备端口监控示例

程序员文章站 2023-04-07 23:41:23
最近因工作需要,上面要求,每天需上报运维的几百数通设备端口使用情况【】,虽然有现成网管监控工具监控设备状态,但做报表,有点不方便,特写了个小脚本。注:测试运行于ubuntn...

最近因工作需要,上面要求,每天需上报运维的几百数通设备端口使用情况【】,虽然有现成网管监控工具监控设备状态,但做报表,有点不方便,特写了个小脚本。

注:测试运行于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