python snmp switch port state

笑着哭i 提交于 2020-03-27 23:02:50

# -*- coding:utf-8 -*-

import re
import os
import time
import platform
import sys
import importlib,sys
importlib.reload(sys)

def snmpWalk(ip,oid):
    result = os.popen('snmpwalk -v 2c -c' + ' ' + 'public' + ' ' + ip + ' ' + oid).read().split('\n')[:-1]
    # result1 = os.popen('snmpwalk -v 2c -c' + ' ' + 'public' + ' ' + '192.168.34.231' + ' ' + '.1.3.6.1.2.1.1.1.0').read().stript()
    # result = ('snmpwalk -v 2c -c' + 'public' + '' + '192.168.34.231' + ' ' + '.1.3.6.1.2.1.1.1.0')
    return result

def getPortDevices(ip,oid):
    device_mib = snmpWalk(ip,oid)
    device_list = []
    for item in device_mib:
        device_list.append(item.split(':')[3].strip())
    return device_list

def getPortStatus(ip,oid):
    device_mib = snmpWalk(ip,oid)
    device_list = []
    for item in device_mib:
        device_list.append(re.search('\w+',item.split(':')[3].strip()).group())
    return device_list

def main():
    with open('ip.text','r',encoding='utf-8') as pf:
        for ip in pf:
            port_full_state = []
            all_switch_informaiton = {}
            ip = ip.strip()
            print(ip)
            device_port = getPortDevices(ip,'ifDescr')
            # print(len(device_port))
            device_port_statue = getPortStatus(ip,'ifOperStatus')
            # print(len(device_port_statue))
            for item in zip(device_port,device_port_statue):
                port_full_state.append(item)
            all_switch_informaiton['ip'] = ip
            all_switch_informaiton['port'] = port_full_state
            with open('output.text', 'a') as f:
                f.write(str(all_switch_informaiton))
                f.write('\n')
                f.close()
        pf.close()
        print(all_switch_informaiton)

if __name__ == '__main__':
    main()
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!