我有3台路由器,一次我只需要ssh到3台路由器中的任何一台,然后运行一些命令。现在,我的代码将ssh到所有3个路由器。我只需要ssh到1个活动的路由器。
方案首先检查第一台路由器是否处于活动状态,以及是否对第一台路由器执行alive..proceed命令,然后运行command..end..but...如果第一台路由器已关闭且对网络不可见,请检查第二台路由器,如果对第二台路由器执行alive..proceed操作,则对第三台路由器运行command..end...if down...check,如果所有路由器都已关闭,则会发出通知。
我正在使用netmiko ssh到设备。
这是ssh到所有设备的代码:-
with open('routers.json') as dev_file:
devices = json.load(dev_file)
for device in routers['router']:
try:
print('Connecting to device:', device['ip'])
connection = netmiko.ConnectHandler(**device)
if device['device_type'] == "cisco_ios" :
output = net_connect.send_command("show arp")
print(output)这是routers.json文件:
{
"router": [
{
"device_type": "cisco_ios",
"ip": "192.168.100.10",
"password": "cisco123",
"username": "user1"
},
{
"device_type": "cisco_ios",
"ip": "192.168.100.20",
"password": "cisco123",
"username": "user1"
},
{
"device_type": "cisco_ios",
"ip": "192.168.100.30",
"password": "cisco123",
"username": "user1"
}
]
}只需要ssh到只有1的3个路由器,如果活动和可靠。请进一步协助。谢谢
**如果发现路由器运行,则添加break语句。如果没有,则继续检查其他路由器。
发布于 2019-05-06 11:21:38
要添加检查该IP是否可ping通的功能,我们可以使用os.system在该IP上运行ping命令,如果能ping通该IP,就可以连接它
def check_ping(ip_address):
response = -1
#Check if we can ping the IP, if we can, response will be 0,
try:
response = os.system("ping -c 1 {}".format(ip_address))
except Exception as exc:
pass
if response == 0:
host_is_up = True
else:
host_is_up = False
return host_is_up使用该函数,我们可以将代码重写为
import os
#Open devices file
with open('routers.json') as dev_file:
devices = json.load(dev_file)
#Function to check if ip address is pingable
def check_ping(ip_address):
response = -1
#Check if we can ping the IP, if we can, response will be 0,
try:
response = os.system("ping -c 1 {}".format(ip_address))
except Exception as exc:
pass
if response == 0:
host_is_up = True
else:
host_is_up = False
return host_is_up
for device in routers['router']:
try:
#If device_type matches cisco_ios, do stuff
if device['device_type'] == "cisco_ios":
print('Connecting to device:', device['ip'])
if check_ping(device['ip']):
connection = netmiko.ConnectHandler(**device)
output = net_connect.send_command("show arp")
print(output)
#Added the missing except
except:
pass输出将如下所示
Connecting to device: 192.168.100.10
.....https://stackoverflow.com/questions/55998329
复制相似问题