Using netmiko to connect to multiple network devices
Here’s an example script that uses the Netmiko library to connect to multiple Cisco network devices and detect VLANs on each device:
from netmiko import ConnectHandler
# Define the credentials and connection details for each device
devices = [
{
'device_type': 'cisco_ios',
'ip': '192.168.1.1',
'username': 'your_username',
'password': 'your_password',
},
{
'device_type': 'cisco_ios',
'ip': '192.168.1.2',
'username': 'your_username',
'password': 'your_password',
},
# Add more devices here if needed
]
# Iterate over each device
for device in devices:
print(f"Connecting to {device['ip']}...")
# Establish SSH connection to the device
try:
connection = ConnectHandler(**device)
print("Connection successful!\n")
except Exception as e:
print(f"Failed to connect to {device['ip']}: {e}\n")
continue
try:
# Send command to retrieve VLAN information
output = connection.send_command('show vlan')
print(f"VLANs on {device['ip']}:\n{output}\n")
except Exception as e:
print(f"Failed to retrieve VLAN information from {device['ip']}: {e}\n")
# Disconnect from the device
connection.disconnect()
Make sure you have the netmiko
library installed before running this script. You can install it using pip install netmiko
.
In the devices
list, provide the necessary details for each Cisco device you want to connect to: the device_type
should be set to 'cisco_ios'
, the ip
should be the IP address of the device, and provide the appropriate username
and password
for authentication.
The script will iterate over each device, establish an SSH connection using Netmiko, send the command show vlan
to retrieve VLAN information, and then disconnect from the device. The VLAN information retrieved from each device will be printed on the console.
You can add more devices to the devices
list as needed. Remember to replace 'your_username'
and 'your_password'
with the actual credentials for each device.
Note: This script assumes that you have SSH access enabled on the Cisco devices and that the provided credentials are correct. Make sure to adjust the script according to your network environment and specific requirements.