31 March, 2019

#2 - Python - Netmiko scripts to automate Network Tasks

To have more attractive code we have changed some functions, now we have 3 files in game.
Also we have excluded some exeptions like timeout and authentication failure to prevent script stops when its hepens.
We also have function to prompt for Username and Password and verify the password to confirm.

python@python:~$ ls -lh
-* command2.py          (Main Script we are working on)
-* devices.json             (We use this file to read Device list from there)
-* credential_tools.py  (Exported some tools such credential management to do not load a main script)


### command2.py
python@python:~$ cat command2.py

#!/usr/bin/python
import netmiko
import json
#Import our tools to manage credentials
import credential_tools

#Configure Exceptions for timeout and authentication failure
netmiko_exceptions = (netmiko.ssh_exception.NetMikoTimeoutException,
                      netmiko.ssh_exception.NetMikoAuthenticationException)

username, password = credential_tools.get_credentials()

#Open the file witch contains device list in json format
with open('devices.json') as dev_file:
    devices = json.load(dev_file)

for device in devices:
    device["username"] = username
    device["password"] = password
    try:
        print("-"*80)
        print("Connecting to Device ", device["ip"])
        connection = netmiko.ConnectHandler(**device)
        print(connection.send_command("show running-config | in hostname"))
        print(connection.send_command("show clock"))
        print(connection.send_command("show ip interface brief"))
        connection.disconnect()
    except netmiko_exceptions as e:
         print("Failed to ", device["ip"], e)


### devices.json 
python@python:~$ cat devices.json
[
 {
  "ip": "10.0.10.105",
  "device_type": "cisco_ios"
 },
 {
  "ip": "10.0.10.106",
  "device_type": "cisco_ios"
 },
 {
  "ip": "10.0.10.107",
  "device_type": "cisco_ios"
 },
 {
  "ip": "10.0.10.108",
  "device_type": "cisco_ios"
 }
]

### credential_tools.py 
python@python:~$ cat credential_tools.py

from getpass import getpass

def get_input(prompt=""):
    try:
        line = raw_input(prompt)
    except NameError:
        line = input(prompt)
    return line

def get_credentials():
    """Prompts for, and returns, a username and password."""
    username = get_input("Enter Username: ")
    password = None
    while not password:
       password = getpass()
       password_verify = getpass("Retype Your Password: ")
       if password != password_verify:
          print("Password do not match. Try again! ")
          password = None
    return username, password

### Run the Script...
Result :
python@python:~$ ./command2.py
Enter Username: admin
Password: ******
Retype Your Password: ******
--------------------------------------------------------------------------------
('Connecting to Device ', u'10.0.10.105')
hostname XZXNR0801
*14:31:31.939 UTC Sun Mar 31 2019
Interface                  IP-Address      OK? Method Status                Protocol
FastEthernet0/0            unassigned      YES unset  administratively down down
GigabitEthernet1/0         10.0.10.105     YES manual up                    up
--------------------------------------------------------------------------------
('Connecting to Device ', u'10.0.10.106')
hostname XZXNR0802
*14:32:07.111 UTC Sun Mar 31 2019
Interface                  IP-Address      OK? Method Status                Protocol
FastEthernet0/0            unassigned      YES manual administratively down down
GigabitEthernet1/0         10.0.10.106     YES manual up                    up
--------------------------------------------------------------------------------
('Connecting to Device ', u'10.0.10.107')
('Failed to ', u'10.0.10.107', NetMikoAuthenticationException(u'Authentication failure: unable to connect cisco_ios 10.0.10.107:22\nAuthentication failed.',))
--------------------------------------------------------------------------------
('Connecting to Device ', u'10.0.10.108')
('Failed to ', u'10.0.10.108', NetMikoTimeoutException(u'Connection to device timed-out: cisco_ios 10.0.10.108:22',))