Netmiko & getpass to access devices
Let’s ask ChatGPT to provide us the code for the following question:
Can you generate a script that uses Netmiko and getpass to login to a list of devices (defined in a text file) using a Tacas account and run a specific command? Output the result into a csv file.
Here’s the answer:
Here is an example Python script that uses Netmiko and getpass to login to a list of devices using a TACACS account and run a specific command. The output is written to a CSV file:
import csv
import getpass
from netmiko import ConnectHandler
# Read in list of devices from text file
with open('devices.txt', 'r') as f:
devices = f.read().splitlines()
# Prompt user for TACACS username and password
username = input("Enter TACACS username: ")
password = getpass.getpass("Enter TACACS password: ")
# Open CSV file for writing
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Device', 'Command Output'])
# Iterate through list of devices
for device in devices:
# Create Netmiko connection handler
net_connect = ConnectHandler(
device_type='cisco_ios',
host=device,
username=username,
password=password,
secret=password
)
# Run command and retrieve output
command = 'show version'
output = net_connect.send_command(command)
# Write device and command output to CSV file
writer.writerow([device, output])
This script reads in a list of devices from a text file called devices.txt, which should contain one device hostname or IP address per line. The user is prompted to enter their TACACS username and password, which are used to authenticate to the devices.
The script then iterates through the list of devices and creates a Netmiko connection handler for each device. It then runs the command show version and retrieves the output. The device hostname and command output are then written to a CSV file called output.csv.
Comments
So empty here ... leave a comment!