Skip to content

Instantly share code, notes, and snippets.

@pathcl
Last active September 24, 2020 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pathcl/159ce385ee297ad5bd362ffbdc2f0523 to your computer and use it in GitHub Desktop.
Save pathcl/159ce385ee297ad5bd362ffbdc2f0523 to your computer and use it in GitHub Desktop.
Simple script to connect on network devices and run commands
#!/usr/bin/python3
# Simple script to connect on network devices and run commands
# ./netmiko-test.py -u lsanmartin -c "show version" -m cisco_ios -s labsw.domain.tld
import sys
import argparse
from datetime import datetime
from getpass import getpass
try:
from netmiko import ConnectHandler
except ImportError:
print('Please install netmiko\n')
print('i.e. pip install netmiko\n')
sys.exit(1)
except:
print("Unexpected error:", sys.exc_info()[0])
raise
def main(username, device, cmd, device_type):
# Use argparse
pwd = getpass('Password: ')
# Device parameters
dev = {
'device_type': device_type,
'ip': device,
'username': username,
'secret': pwd,
'password': pwd,
'global_delay_factor': 3,
}
# Establish an SSH connection to the device by passing in the device dictionary
net_connect = ConnectHandler(**dev)
print("\nStart time: {}".format(str(datetime.now())))
print("---------------------------------")
print('Host: {}'.format(device))
# Enable mode
net_connect.enable()
# Execute command
out = net_connect.send_command(cmd)
net_connect.disconnect()
print(out)
print("---------------------------------")
if __name__ == '__main__':
# Build up arguments
parser = argparse.ArgumentParser()
parser.add_argument(
'-u', action='store', dest='username', help='Username', required=True)
parser.add_argument(
'-s', action='store', dest='device', help='Host to connect', required=True)
parser.add_argument(
'-m', action='store', dest='device_type', help='Device type', required=False,
choices=['a10', 'dell_force10', 'cisco_ios'], default='cisco_ios')
parser.add_argument(
'-c', action='store', dest='cmd', help='Command to execute', required=True)
args = parser.parse_args()
# Read parameters and pass them to main
main(args.username, args.device, args.cmd, args.device_type)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment