python - 如何使用包含每个交换机的字典的文件通过 SSH 连接到多个交换机?
问题描述
这是“myswitches”文件,其中包含不同交换机的 IP 地址列表:
192.168.122.15
192.168.122.16
192.168.122.17
我已经成功地使用“myswitches”文件远程登录到多个交换机:
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 t\n")
telnet.write(b"int loop 10\n")
telnet.write(b"ip address 1.1.1.1 255.255.255.255\n")
telnet.write(b"end\n")
telnet.write(b"exit\n")
print(telnet.read_all().decode('ascii'))
现在我想使用 Netmiko 使用“myswitches”文件通过 SSH 连接到交换机:
这里又是“myswitches”文件,这次我使用的是字典而不是列表:
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。
推荐阅读
- html - CSS - 另一个悬停时的悬停触发器
- json - 使用不同的模式合并数据帧 - Scala Spark
- ios - 收听和取消其他应用的通知
- aframe - 有没有办法在 A-Frame 中创建一个空心圆圈?
- php - 在 Laravel Controller 中调用 JS 函数
- javascript - 使用 JAVASCRIPT 创建的计数器不起作用
- php - PHP从多维数组/ JSON中提取数据
- flutter - 下拉选定对象显示为字符串
- angular - node_modules 文件夹中的 Angular 9 错误构建库
- javascript - TypeError:空传播运算符不可迭代