Search code examples
pythoncisco

Python - Retrieve the output of Cisco CLI command and use it as input


Below is my working code which is used to execute Cli commands on Cisco Routers and Switches. I have a task at my hand which requires me to read specific values from the output of the Cli commands executed earlier and use is as input for another command to be executed on the Cisco device.

Output of the below code:

TEST#sh run | i hostname

hostname TEST

TEST#

My task is to fetch only "TEST" from the output and use it as input for another command in the same code as follows,

chan.send("conf t\n")

chan.send("tacacs server key TEST\n")

chan.send("exit\n")

Please guide me on this. Thanks in advance.

import paramiko
import sys
import os
import subprocess
import cmd
import time
import datetime
import getpass
from netaddr import *

buff = ''
resp = ''
now = datetime.datetime.now()
usr = raw_input('Enter Username:')
pwd = getpass.getpass('Enter Password:')

with open('Fetch.txt') as f:
    for line in f:
        line = line.strip()
        with open(os.devnull, "wb") as limbo:
                ip = line
                result = subprocess.Popen(["ping", "-n", "2", "-w", "200", ip],
                    stdout=limbo, stderr=limbo).wait()
                if result:
                        print ip, "Link Down - Site unreachable"
                        f = open('Down Sites.txt', 'a+')
                        f.write( line + '\n' )
                        f.close()
                else:
                        try:
                            dssh = paramiko.SSHClient()
                        dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                            dssh.connect(line, username=usr, password=pwd)
                            chan = dssh.invoke_shell()
                            chan.send("sh run | i hostname\n")
                            time.sleep(6)
                            data = chan.recv(99999)
                            filename_prefix = line
                            filename = "%s-%.2i-%.2i-%i_%.2i-%.2i-%.2i.txt" % (filename_prefix,now.day,now.month,now.year,now.hour,now.minute,now.second)
                            f=open(filename,"w")
                            f.write(data)
                            f.close()
                            print "Command Executed"
                        except Exception as e:
                            err = str(e)
                            f = open('Exceptions.txt', 'a+')
                            f.write(ip + ": " + err + '\n')
                            f.close()
                            print ip, "ERROR:", e
dssh.close()

Solution

  • I was able to get it working, just researched and got this solution,

    import paramiko
    import sys
    import os
    import subprocess
    import cmd
    import time
    import datetime
    import getpass
    import re
    from netaddr import *
    
    buff = ''
    resp = ''
    now = datetime.datetime.now()
    usr = raw_input('Enter Username:')
    pwd = getpass.getpass('Enter Password:')
    
    with open('Fetch.txt') as f:
        for line in f:
            line = line.strip()
            with open(os.devnull, "wb") as limbo:
                ip = line
                result = subprocess.Popen(["ping", "-n", "2", "-w", "200", ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print ip, "Link Down - Site unreachable"
                        f = open('Down Sites.txt', 'a+')
                        f.write( line + '\n' )
                        f.close()
                else:
                        try:
                            dssh = paramiko.SSHClient()
                            dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                            dssh.connect(line, username=usr, password=pwd,timeout=60)
                            stdin, stdout, stderr = dssh.exec_command('sh run | i hostname')
                            mystring = stdout.read()
                            v = mystring[9:]
                            dssh.connect(line, username = usr, password = pwd)
                            chan = dssh.invoke_shell()
                            chan.send("conf t\n tacacs-server key %s\n"%v)
                            time.sleep(2)
                            resp = chan.recv(9999)
                            f=open('Output.txt',"a+")
                            f.write(resp+ '\n')
                            f.close()
                            print "Command Executed"
                        except Exception as e:
                            err = str(e)
                            f = open('Exceptions.txt', 'a+')
                            f.write(ip + ": " + err + '\n')
                            f.close()
                            print ip, "ERROR:", e
    dssh.close()
    

    Thank u all.