Python
for network engineers
(https://pynet.twb-tech.com)
Articles (/blog/)
Join Email-List
(lemail-
signup html)
Python, Paramiko SSH, and Network Devices (2014-01-23)
By Kirk Byers
You have been learning Python, but as a network engineer what can you do with it?
In this article, | will show you how to use Paramiko SSH (a Python SSH library) to connect to.
and gather information from a router. In a later article (potentially multiple articles), | will expand
upon this—showing you how to gather information from multiple devices, and how to make
configuration changes.
Now in this article I will be using Python to connect to an interface that is inherently expecting a
human being (i.e. using an ‘Expect-like' method). For various reasons, this Expect-like method
is problematic—tor example, there can be timing issues; there can be unexpected interaction
problems; and there can be variations in device output (between OS versions, between device
models, between device types, etc.)
While this Expect-like method is problematic, in many cases, it is a reasonable option for
automation of existing equipment (given currently available alternatives). This will change
across time as newer APIs (and other management/control mechanisms) become available and
as devices in the field get refreshed and upgraded. In my opinion, the difficulties of using
Expect-like mechanisms are also overstated (don't get me wrong there are a lot of difficulties,
but APIs are not all a bed of roses either).
As with many things, a Python SSH 'Expectlike' method can be made to work in a reasonable
way provided that you know its limitations; you test it appropriately; and you take appropriate
precautions when using it.
One final warning—and this is a warning about network automation in general
Programmatically controlling a set of network devices is a powerful capability and because it is
powerful the stakes are significantly increased. You potentially might be changing fifty devices
instead of one; you could be changing devices in multiple geographies. The consequences of
mistakes are greatly increased. Consequently, start small. Start with show commands instead of
configuration changes. When making changes practice good operational procedures—knowwhat you are doing; test it out appropriately in a test environment; deploy the change to a single
device; expand it to a small set of devices; consider the consequences if things go wrong and
how you will correct them; determine whether this change is something that makes sense to do
programmatically
So on that warm and fuzzy note, let's dive-in
So how can you SSH into routers using Python? The first step is to get the Paramiko SSH
library installed. In my environment (AWS using AWS Linux AMI '2013.09.2' 64-bit), the
installation process is easy—Paramiko is already installed.
If you are using Mac OS and you want to install Paramiko locally, then you will need a c-
compiler. Consequently you will need to download Xcode (or you will need to install the
Command Line Tools). This link provides some details http://osxdaily.com/2012/07/10/how-to-
install-paramiko-and-pycrypto-in-mac-os-x-the-easy-way/ (http://osxdaily.com/2012/07/10/how-
to-install-paramiko-and-pycrypto-in-mac-os-x-the-easy-way/). Note, the Xcode download is very
large.
If you are using Windows, then you will need to get Python installed first. Once Python is
installed, there are links that you can find online for installing Paramiko. You might want to just
run a Linux virtual machine, however.
For other Linux distributions/builds—if Paramiko is not available via YUM or APT, you can
probably use pip or easy_install to get Paramiko installed
Now that Paramiko is installed, let's test that it works:
[root@ ec2-user# python
Python 2.6.8 (unknown, Oct 29 2013, 19:58:13)
[GCC 4.6.3 20120306 (Red Hat 4.6.3-2)] on linux2
Type *help*, copyright, "credits" or icense" for more information
>>> import paramiko
Note, on my AWS box, | received two warnings from the PyCrypto package when importing
Paramiko (Paramiko uses the PyCrypto package). The first waming pertained to RandomPool;
my research indicated that Paramiko had probably worked around this issue. The second
warning pertained to a ‘timing attack vulnerability’ and needing libgmpS or greater, | had
considerable trouble finding additional useful information on this warning. | have currently
commented out these two warnings in my test environment; you will have to decide what to do
about these warnings in your environment,
Okay the Paramiko library is importing, but how do you connect to a router?[ro0t@ ec2-user}# python
Python 2.6.9 (unknown, Oct 29 2013, 19:58:13)
[GCC 4.6.3 20120306 (Red Hat 4.6.3-2)] on linux2
‘Type *help", "copyright
edits" or “license” for more information,
>>> import paramiko
>>> ip=14.4.16"
>>> usemame = 'testuser’
>>> password = password’
>>> remote_conn_pre=paramiko.SSHClient()
>>> remote_conn_pre
>>> remote_conn_pre.set_missing_host_key_policy(
paramiko AutoAddPolicy())
>>> remote_conn_pre.connect(ip, username=usemame, password=password)
Note, in the examples in this article, | generally modified the IP addresses and always modified
the password (i.e. changed the displayed output to hide what I really used). Everything else is
real-life; | am connecting to a real router (Cisco 881) and displaying real sessions.
‘So what just happened here? First, | imported the Paramiko library; then | initialized a few
variables. After the variables were initialized, then I created a Paramiko SSHClient object,
Paramiko describes the SSHClient class as, "A high-level representation of a session with an
SSH server". After the SSHClient object is created, | then set the SSH host key policy to
automatically add the SSH host key—note, this is a security issue and makes you potentially
vulnerable to man-in-the-middle attacks so make sure that this is appropriate for your
environment. This was fine in my test environment.
At this point, | am ready to connect using the SSH ‘connect’ method passing in the ip,
username, and password variables. If everything went well | should have an established SSH
session. Let's check ‘netstat’:
[ro0t@ ec2-user}# netstat -an | grep 22
tp 0 9 += 0.0.0.0:22 0.0.00" uSTEN
tp 0 «0 10.t0.10.22:55588 1.4.1.1822 ESTABLISHED
There is the session. Now let's start an ‘interactive shell' with the router using the Paramiko
invoke_shell() method.
>>> remote_conn = remote_conn_pre.invoke_shell()
Now if everything worked right, we should be able to communicate with the router. Let's try to
read from the SSH channel and see what is there:>>> output = remote_conn.recv(1000)
>>> print output
two-sf-881>
Here | read up to 1000 bytes from the channel (the maximum of 1000 bytes or whatever is
currently available in the buffer). | then print the output. There is my router prompt, 'twb-sf-881>".
Now what if we try to send a command through the channel:
>>> remote_conn.send("show ip int briefin")
18
>>> output = remate_conn.recv(5000)
>>> print output
show ip int brief
Interface IP-address oK? Method Status Protocol
FastEthemet0 unassigned Yes unset up wp
Fast€thernett unassigned yes unset up wp
FastEtheret2 Unassigned Yes unset down down
FastEthernet3 unassigned Yes unset up wp
Fast€thernetd 114.16 yes NVRAM up wp
Nvio 114.18 yes unset up w
Tunnelt 169.254.2532 Yes NVRAM up down
Tunnel2 169.254.2536 yes NVRAM up down
Viant Unassigned Yes NVRAM down down
Vianto 10281 Yes NVRAM up w
vian20 192,168.04 Yes NVRAM down down
More
Here, | sent the ‘show ip int brief command down the channel. Notice, | added a newline
character to the end of the command (i.e. | emulated hitting ‘enter’ on the line that was
presented to the router), The '18' displayed after the send command is just the number of bytes
[sent down the channel. | then read the buffer to see the output. This time I increased the buffer
size to 5000 bytes to make sure | received all of the output data. | then print the output.
So, we are able to connect to the router, read from the session, and send a command to the
router. Now we are doing all of this via the interactive shell. Let's convert this over to a basic
Python program so we can better reuse our work
[root@ CODE} cat test-ssh py
import paramiko
import time
def disable_paging(remote_conn):
“Disable paging on a Cisco router”
remote_conn.send("terminal length O\n")
time sleep(1)
# Clear the buffer on the screenoutput = remote_conn recv(1000)
retum output
if_name__=='_main_'
# VARIABLES THAT NEED CHANGED
ip 14.41.16"
usemame = ‘testuser’
password = ‘password’
# Create instance of SSHClient object
remote_conn_pre = paramiko.SSHClient()
# Automatically add untrusted hosts (make sure okay for security policy in your environment)
remote_conn_pre.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
# initiate SSH connection
remote_conn_pre.connect(p, usemnam:
print "SSH connection established to %s" % ip
isername, password=password)
# Use invoke_shell to establish an ‘interactive session’
remote_conn = remote_conn_pre.invoke_shell()
print "Interactive SSH session established”
# Strip the intial router prompt
‘output = remote_conn.recv(1000)
# Seo what we have
print output
# Tum off paging
disable_paging(remote_conn)
# Now let:
remote_conn.send("in
remote_conn.send("show ip int briefin’)
to send the router a command
# Wait for the command to complete
time sleep(2)
output
print output
smote_conn.recv(5000)
{root@ CODE}#Now this is similar to what we did in the interactive session except | added some print
statements to indicate what is occurring when the program runs. Additionally, | created a
function to disable_paging (i.e. the --More-- prompt). | also added a small delay to the program
(after sending the ‘show ip int briefin' command and before reading the buffer). This is required
because if you send the command and then immediately read the buffer the router likely would
not have responded yet or may have only partially responded. You can test removing the sleep
on your own—when | tested it got an exception because the data buffer was empty. One other
minor tweak that | made was to send a newline character before sending the ‘show ip int brief
command. This is just for formatting of the output (so the router prompt shows up in the output
in a way we expect).
Okay, let's see what happens when I run the script:
[root@ CODE}# python test-ssh.py
‘SSH connection established to 1.1.1.16
Interactive SSH session established
two-st-881>
twb-sf-881>show ip int brief
Interface IP-address oK? Method Status Protocol
FastEtheret0 Unassigned Yes unset up w
FastEthernett unassigned Yes unset up a
Fast€theret2 unassigned yes unset down down
FastEtheret3 tunassigned Yes unset up w
FastEthernets 14.48 Yes NVRAM up ry
Nvio 114.46 yes unset up wp
Tunnelt 169.254.253.2 yes NVRAM up down
Tunnel2 169.254.2536 Yes NVRAM up down
Viant Unassigned yes NVRAM down down
Viento 10.281 yes NVRAM up wp
vian20 192,168.01 Yes NVRAM down down
viant00 10.244 Yes NVRAM up wp
two-st-881>
(root@ CODE}
Notice, the '--More--' paging is gone.
Hopefully, this demonstrates that it is not too hard to integrate Python to a router using an SSH
“Expect-like" method. Additionally, hopefully, you can start to see the potential in doing this or
similar things to gather information and to make changes to a set of network devices
If you have questions or comments feel free to ping me on Twitter or if you want to receive
additional content, join my email-list (/email-signup. htm!)
Kirk Byers
CCIE #6243
Twitter: @kirkbyers
Copyright © 2014 Twin Bridges Technology