[python]Example script on Cisco router

This is an example script based on this https://github.com/davidbombal/pythonvideos/blob/master/paramiko-pythonssh1.py

It works almost like pexpect, however need to have a privilege 15 account to make the SSHClient work, as there is no input to accept enable secret. I was trying to figure out the feasibility of using API to push the configuration, I find the send method of the SSHClient to be very static, a change in hardware or IOS XE version might easily break the operation of the script, IOS is very famous to exclude or change command patterns.

import paramiko
import time

# example format which might be able to push by user putting in the required information
routers = [
    {
        "ipaddress": "192.168.1.201",
        "username": "cisco",
        "password": "cisco"
    }
]
# print(routers[0]["password"])
sshclient = paramiko.SSHClient()

# Accept unknown public rsa key from router.
sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
    sshclient.connect(hostname=routers[0]["ipaddress"],
                      username=routers[0]["username"],
                      password=routers[0]["password"])
    print("Successfully connected to {}".format(routers[0]["ipaddress"]))
    connection = sshclient.invoke_shell()
    # the below are very static and might break if hardware changes or IOS version upgraded.
    # Cisco IOS is very famous of not maintaining their command line patterns.
    # can the below be structured in json?
    connection.send("conf t\n")
    connection.send("int e0/0\n")
    connection.send("description python created description.\n")
    connection.send("exit\n")
    time.sleep(1)
    connection.send("int lo0\n")
    connection.send("1.1.1.1 255.255.255.255\n")
    connection.send("exit\n")
    time.sleep(1)
    connection.send("router ospf 1\n")
    connection.send("router-id 1.1.1.1\n")
    connection.send("network 192.168.1.0 255.255.255.0 area 0\n")
    connection.send("no passive-interface default\n")
    connection.send("end\n")
    time.sleep(1)
    connection.send("write mem\n")
    time.sleep(5)
    end_session = connection.recv(65535)
    print(end_session)
    sshclient.close()

except paramiko.SSHException as se:
    print(se)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s