I have cisoc_ios routers and fortinet firewall and HP switches in "devices_list" but when I run this code and when it hits fortinet firewall , it does not give error as it is not cisco_ios and tries to login.. And after login it gives error as it can not go into config mode(obviously) . So I need to improve my below code so that code throws error when fortinet or hp devices comes instead of trying to login and it shud continue until all devices have been tried.
from getpass import getpass
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from netmiko.ssh_exception import AuthenticationException
from paramiko.ssh_exception import SSHException
username = input("Enter username: ")
password = getpass()
with open('commands_file.txt') as f:
commands_list = f.read().splitlines()
with open('devices_list.txt') as f:
devices_list = f.read().splitlines()
for devices in devices_list:
print("Connecting to device: " + devices)
host_name_of_device = devices
ios_device = {
'device_type' : 'cisco_ios' ,
'host' : host_name_of_device ,
'username' : username ,
'password' : password ,
}
try:
net_connect = ConnectHandler(**ios_device)
except (AuthenticationException):
print("Authetication failure: " + host_name_of_device)
continue
except (NetMikoTimeoutException):
print("Time out from device: " + host_name_of_device)
continue
except (EOFError):
print("End of File reached: " + host_name_of_device)
continue
except (SSHException):
print("Not able to SSH: Try with Telnet: " + host_name_of_device)
continue
except Exception as unknown_error:
print("other: " + unknown_error)
continue
output = net_connect.send_config_set(commands_list)
print(output)
netmiko can autodetect the type of the device. You should use this before running the commands.
from netmiko.ssh_autodetect import SSHDetect
...
for devices in devices_list:
print("Connecting to device: " + devices)
host_name_of_device = devices
remote_device = {
'device_type' : 'autodetect' , # Autodetect device type
'host' : host_name_of_device ,
'username' : username ,
'password' : password ,
}
guesser = SSHDetect(**remote_device)
best_match = guesser.autodetect()
if best_match != 'cisco_ios':
print("Device {} is of type {}. Ignoring "
"device".format(host_name_of_device, best_match))
continue
# Device type is cisco_ios
remote_device['device_type'] = best_match # Detected device type
try:
net_connect = ConnectHandler(**remote_device)