目的:通过netmiko实现多线程连接extreme switch,获取model,sn,version等信息。
说明:目录下建立一个devices.txt文件,每行一个设备信息,格式:ipaddress username password(中间用1个空格分隔)
代码如下:
import re, threading
from netmiko import ConnectHandler
switches = []
def conn(devicetype,ip,username,password):
"""Connect to devices."""
exo = {
'device_type': devicetype,
'ip':ip,
'username': username,
'password': password,
}
return exo
def checkDevice(sw):
info=sw.split(' ')
print("Start to connect %s ..." % info[0])
connect = ConnectHandler(**conn('extreme_exos',info[0],info[1],info[2]))
print("%s Connected!" % info[0])
switch = {}
switch.setdefault("ip",info[0])
print("Start to check %s Model..." % info[0])
output = connect.send_command("show switch")
findsw = re.compile('System Type.+\n')
modelinfo = findsw.search(output).group(0).replace(' ','')
switch.setdefault("Model",modelinfo.split(':')[1].replace('\n',''))
print("Start to check %s SerialNumber & Version..." % info[0])
output = connect.send_command("show version")
findsn = re.compile('Switch.+\n')
swver = findsn.search(output)
findima = re.compile('ExtremeXOS.+\n')
swima = findima.search(output)
findword = re.compile('\d{4}\w-\d{5}')
switch.setdefault("SN",findword.search(swver.group(0)).group(0))
verinfo = str(swima.group(0)).split(' ')
switch.setdefault("Ver",verinfo[3])
switches.append(switch)
openfile = open('devices.txt','r')
sws = openfile.read()
swlist = sws.split("\n")
threads = []
for sw in swlist:
t = threading.Thread(target=checkDevice,args=(sw,))
threads.append(t)
for t in threads:
t.setDaemon=True
t.start()
for t in threads:
t.join() #子线程全部加入,主线程等所有子线程运行完毕
print("Done!")
for sw in switches:
print('-'*20)
print('IP: %s' % sw["ip"])
print('Model: %s' % sw["Model"])
print('SN: %s' % sw["SN"])
print('Ver: %s' % sw["Ver"])
测试结果:
Start to connect 10.0.0.6 ...
Start to connect 10.0.0.1 ...
Start to connect 10.0.0.4 ...
10.0.0.4 Connected!
Start to check 10.0.0.4 Model...
10.0.0.1 Connected!
Start to check 10.0.0.1 Model...
10.0.0.6 Connected!
Start to check 10.0.0.6 Model...
Start to check 10.0.0.4 SerialNumber & Version...
Start to check 10.0.0.1 SerialNumber & Version...
Start to check 10.0.0.6 SerialNumber & Version...
Done!
--------------------
IP: 10.0.0.4
Model: X450e-24p
SN: 1000G-12345
Ver: v1533b5-patch1-10
--------------------
IP: 10.0.0.1
Model: X450a-48t
SN: 1001G-12345
Ver: v1535b2-patch1-13
--------------------
IP: 10.0.0.6
Model: X460-48p
SN: 1002N-12345
Ver: 16.2.5.4-patch1-3