如何使用包含每个交换机的字典的文件通过 SSH 连接到多个交换机?



这是"myswitch"文件,包含不同交换机的IP地址列表:

192.168.122.15
192.168.122.16
192.168.122.17

我已经设法使用"myswitch"文件成功地远程登录到多个交换机:

import getpass
import telnetlib
host = "localhost"
user = input("Enter your username: ")
password = getpass.getpass()
f = open('myswitches', 'r')
for IP in f:
IP=IP.strip()
print("configuring switch " + (IP))
host = IP
telnet = telnetlib.Telnet(host)
telnet.read_until(b"Username: ")
telnet.write(user.encode('ascii') + b"n")
if password:
telnet.read_until(b"Password: ")
telnet.write(password.encode('ascii') + b"n")
telnet.write(b"config tn")
telnet.write(b"int loop 10n")
telnet.write(b"ip address 1.1.1.1 255.255.255.255n")
telnet.write(b"endn")
telnet.write(b"exitn")
print(telnet.read_all().decode('ascii'))

现在我想使用 Netmiko 通过"myswitch"文件通过 SSH 连接到交换机:

这里又是"myswitch"文件,这次我使用了字典而不是列表:

iosv_l2_S1 = {
'device_type': 'cisco_ios',
'ip': '192.168.122.15',
'username': 'admin',
'password': 'cisco',
}
iosv_l2_S2 = {
'device_type': 'cisco_ios',
'ip': '192.168.122.16',
'username': 'admin',
'password': 'cisco',
}
iosv_l2_S3 = {
'device_type': 'cisco_ios',
'ip': '192.168.122.17',
'username': 'admin',
'password': 'cisco',
}

这是我目前正在处理的Netmiko python脚本:

from netmiko import ConnectHandler
f = open('myswitches', 'r')
myswitches = [iosv_l2_S1, iosv_l2_S2, iosv_l2_S3]
for switches in f:
net_connect = ConnectHandler(**switches)
for n in range (2,11):
print ("Creating VLAN " + str(n))
config_commands = ['vlan ' + str(n), 'name Python_VLAN_' + str(n)]
output = net_connect.send_config_set(config_commands)
print (output)

如何改进我的 netmiko python 脚本,我也希望它配置loopback0 1.1.1.1 255.255.255.255.

是的,正如评论中回应的那样 - 将my_switches转换为my_switches.py然后导入它。

from my_switches import iosv_l2_S1, iosv_l2_S2, iosv_l2_S3
config_list = []
for n in range (2, 11):
print ("Creating VLAN " + str(n))
new_vlan = f"vlan {n}"
config_list.append(new_vlan)
vlan_name = f"name Python_VLAN_{n}"
config_list.append(vlan_name)

for switch in [iosv_l2_S1, iosv_l2_S2, iosv_l2_S3]
net_connect = ConnectHandler(**switch)
output = net_connect.send_config_set(config_list)
print(output)
net_connect.disconnect()

所以应该是像上面这样的东西。最好一次发送所有配置命令,而不是一次单独发送一个(以避免 Netmiko 每次都进入/退出配置模式,这很慢(。

同样如上所述 - 如果你真的想将它们作为非Python文件读取,你可以使用JSON或YAML。

最新更新