# Import program dependencies
from netmiko import ConnectHandler
import time
# Read from a list of hostnames to connect to
hosts = open(‘hosts-sw‘, ‘r‘)
hosts = hosts.read()
hosts = hosts.strip().splitlines()
# Loop to process hosts in hosts.txt file
for host in hosts:
# Define device type and connection attributes
cisco = {
‘device_type‘: ‘cisco_ios‘,
‘ip‘: host,
‘username‘: ‘a2-m0073501‘,
‘password‘: ‘ruoyan@123456789‘,
}
try:
net_connect = ConnectHandler(**cisco) # 连接到交换机
net_connect.enable() # 进入特权模式
except Exception as e:
print(e)
# 交换机需要执行的命令
else:
commands = [
‘sh running-config‘, ]
# 处理获取的命令结果,并保存为 txt 文件
timestr = time.strftime(‘%Y-%m-%d‘, time.localtime(time.time()))
for cmd in commands:
filename = u‘%s_%s_%s.txt‘ % (host, cmd.replace(‘ ‘, ‘_‘), timestr)
save = open(filename, ‘w‘)
result = net_connect.send_command(cmd)
save.write(result)
net_connect.disconnect()
原文:https://www.cnblogs.com/zhaoyong631/p/14512239.html