python snmp switch port state
# -*- 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()
相关推荐
highwaymanhw 2020-09-06
insularisland 2020-08-15
87447100 2020-02-20
HelloC先生 2008-03-28
bjkamui 2011-04-24
Jiajinjin 2011-04-24
Linuxest 2010-07-30
84266131 2009-12-10
周海汉的开发 2010-02-26
xufuangchao 2014-10-09
fqx 2012-12-04
seacover 2012-10-23
wenshifang 2011-03-05
viplinux 2011-03-05
LinuxCard 2014-08-22