Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: SSH into Cisco device and run show commands

Tags:

python

ssh

cisco

I have read over this post extensively and have researched Exscript, paramiko, Fabric and pxssh and I am still lost Persistent ssh session to Cisco router . I am new to python scripting.

I am attempting to write a script in Python that will SSH into a Cisco device, run "show version", display the results in notepad, then end the script.

I can get this working with show commands that do not require the user to interact with the device. For example:

from Exscript.util.interact import read_login
from Exscript.protocols import SSH2

account = read_login()              
conn = SSH2()                       
conn.connect('192.168.1.11')     
conn.login(account)                 

conn.execute('show ip route')
print conn.response

conn.send('exit\r')               
conn.close()                        

The above script will display the results of "show ip route".

If I try conn.execute('show version') the script times out because the Cisco device is expecting the user to press space bar to continue, press return to show the next line or any key to back out to the command line.

How can I execute the show version command, press space bar twice to display the entire output of the show version command, then print it in python?

Thank you!!!!

like image 646
D3l_Gato Avatar asked Aug 21 '11 20:08

D3l_Gato


People also ask

Can you ssh from a Python script?

In python SSH is implemented by using the python library called fabric. It can be used to issue commands remotely over SSH.

How do I run a script on a Cisco switch?

The most common way to execute scripts in IOS, is to run them in the CLI command prompt accessed via telnet or ssh. Honestly most people prefer to KISS here. and just open an ssh prompt in java, then 'config t' and paste or input you access-list commands Pretty simple and easy to automate in any language.

What is Paramiko SSH?

Paramiko is a Python library that makes a connection with a remote device through SSh. Paramiko is using SSH2 as a replacement for SSL to make a secure connection between two devices. It also supports the SFTP client and server model.


2 Answers

Try executing terminal length 0 before running show version. For example:

from Exscript.util.interact import read_login
from Exscript.protocols import SSH2

account = read_login()              
conn = SSH2()                       
conn.connect('192.168.1.11')     
conn.login(account)  

conn.execute('terminal length 0')           

conn.execute('show version')
print conn.response

conn.send('exit\r')               
conn.close()  

From the Cisco terminal docs: http://www.cisco.com/en/US/docs/ios/12_1/configfun/command/reference/frd1003.html#wp1019281

like image 99
peterjmag Avatar answered Sep 19 '22 04:09

peterjmag


First execute

terminal length 0

to disable paging.

like image 20
MattH Avatar answered Sep 22 '22 04:09

MattH