Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
244 views
Python For Network Engineers
Python Reference for Network Engineers
Uploaded by
Albert Suwandhi
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Python for Network Engineers For Later
Download
Save
Save Python for Network Engineers For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
244 views
Python For Network Engineers
Python Reference for Network Engineers
Uploaded by
Albert Suwandhi
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Python for Network Engineers For Later
Carousel Previous
Carousel Next
Save
Save Python for Network Engineers For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 6
Search
Fullscreen
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
You might also like
Anurag Arwalkar CV
PDF
No ratings yet
Anurag Arwalkar CV
1 page
InfoBlox SNMP Enterprise MIB
PDF
No ratings yet
InfoBlox SNMP Enterprise MIB
20 pages
Saurav Dudulwar Resume
PDF
No ratings yet
Saurav Dudulwar Resume
1 page
Python For Network Engineers - Huawei Presentation - Updated
PDF
No ratings yet
Python For Network Engineers - Huawei Presentation - Updated
44 pages
Install Python Paramiko
PDF
No ratings yet
Install Python Paramiko
3 pages
Creating Multiple SSH Connections at A Time Using Paramiko
PDF
No ratings yet
Creating Multiple SSH Connections at A Time Using Paramiko
3 pages
Python Web Framework
PDF
No ratings yet
Python Web Framework
17 pages
Aws Cli PDF
PDF
No ratings yet
Aws Cli PDF
94 pages
Python Class Links From Naresh IT
PDF
No ratings yet
Python Class Links From Naresh IT
3 pages
Mcse Notes
PDF
No ratings yet
Mcse Notes
88 pages
Jenkins Job Builder PDF
PDF
No ratings yet
Jenkins Job Builder PDF
315 pages
Data Science Assignment 1
PDF
No ratings yet
Data Science Assignment 1
20 pages
Pytest Documentation: Release 2.7.1
PDF
No ratings yet
Pytest Documentation: Release 2.7.1
219 pages
Xrdocs Io Programmability Tutorials Pyats Series Collecting Many Show Commands
PDF
No ratings yet
Xrdocs Io Programmability Tutorials Pyats Series Collecting Many Show Commands
8 pages
200 901 Devasc (Ccna)
PDF
No ratings yet
200 901 Devasc (Ccna)
3 pages
JN0 220
PDF
100% (1)
JN0 220
12 pages
B Cisco Nexus 7000 Series NX-OS Fundamentals Configuration Guide Release 6.x
PDF
No ratings yet
B Cisco Nexus 7000 Series NX-OS Fundamentals Configuration Guide Release 6.x
144 pages
Allied Telesis Ip Addressing & Subnetting Guide
PDF
No ratings yet
Allied Telesis Ip Addressing & Subnetting Guide
1 page
Industry Certification Costing
PDF
No ratings yet
Industry Certification Costing
1 page
OnkarPramodKurle (3 0)
PDF
No ratings yet
OnkarPramodKurle (3 0)
7 pages
Notes AWS Solutions Architects
PDF
No ratings yet
Notes AWS Solutions Architects
55 pages
2014 BRKSPG-2722 SDN Asr9k
PDF
No ratings yet
2014 BRKSPG-2722 SDN Asr9k
130 pages
EIGRP Tutorial
PDF
100% (1)
EIGRP Tutorial
23 pages
Introduction To MapReduce
PDF
No ratings yet
Introduction To MapReduce
43 pages
A Beginners Guide To Cron Jobs
PDF
No ratings yet
A Beginners Guide To Cron Jobs
4 pages
Network and Subnet Helper
PDF
No ratings yet
Network and Subnet Helper
1 page
Frrouting Developers Guide
PDF
No ratings yet
Frrouting Developers Guide
315 pages
Blue
PDF
100% (1)
Blue
6 pages
List of Docker Commands
PDF
No ratings yet
List of Docker Commands
6 pages
5 2023 24 10 04 49 17
PDF
No ratings yet
5 2023 24 10 04 49 17
229 pages
ECMP 3.3.4.2.36-1 OTA Installation Process For BSNL AP
PDF
No ratings yet
ECMP 3.3.4.2.36-1 OTA Installation Process For BSNL AP
2 pages
Set 1 - Fundamental Questions Date: - 13/05/2020 Version: - 1.0 Total: - 50 Questions
PDF
No ratings yet
Set 1 - Fundamental Questions Date: - 13/05/2020 Version: - 1.0 Total: - 50 Questions
51 pages
OpenEDG Python Institute Fulda
PDF
No ratings yet
OpenEDG Python Institute Fulda
48 pages
User and Group Management
PDF
No ratings yet
User and Group Management
11 pages
Segment Routing in MPLS Networks
PDF
No ratings yet
Segment Routing in MPLS Networks
2 pages
Ipv6 Cheat Sheet
PDF
No ratings yet
Ipv6 Cheat Sheet
2 pages
AcademyCloudFoundations Module 02
PDF
No ratings yet
AcademyCloudFoundations Module 02
58 pages
Donald Ngandeu 1
PDF
No ratings yet
Donald Ngandeu 1
6 pages
CP R80.40 Installation and Upgrade Guide
PDF
No ratings yet
CP R80.40 Installation and Upgrade Guide
799 pages
13 Linux Network Configuration and Troubleshooting Commands
PDF
No ratings yet
13 Linux Network Configuration and Troubleshooting Commands
9 pages
Unix File System
PDF
No ratings yet
Unix File System
95 pages
Flask Restful
PDF
No ratings yet
Flask Restful
37 pages
Selenium Python Readthedocs - Selenium Python Bindings
PDF
100% (1)
Selenium Python Readthedocs - Selenium Python Bindings
116 pages
07 - Ingesting New Datasets Into Google BigQuery
PDF
No ratings yet
07 - Ingesting New Datasets Into Google BigQuery
8 pages
Cisco Certifications and Training by PyNet
PDF
No ratings yet
Cisco Certifications and Training by PyNet
2 pages
Docker Certified Associate Study Guide
PDF
No ratings yet
Docker Certified Associate Study Guide
13 pages
Cumulus Networks Data Center Cheat Sheet
PDF
No ratings yet
Cumulus Networks Data Center Cheat Sheet
10 pages
AWS Solution Architect Associate Dump4
PDF
No ratings yet
AWS Solution Architect Associate Dump4
13 pages
OSI (Open System Interconnect)
PDF
No ratings yet
OSI (Open System Interconnect)
33 pages
Cisco Asa 5525 X
PDF
No ratings yet
Cisco Asa 5525 X
16 pages
Deploying Jupyter Notebooks For Students and Researchers
PDF
No ratings yet
Deploying Jupyter Notebooks For Students and Researchers
35 pages
Meridian Crash Course
PDF
No ratings yet
Meridian Crash Course
6 pages
Software Developer Resume
PDF
No ratings yet
Software Developer Resume
1 page
Vim Cheat Sheet For Programmers Screen
PDF
No ratings yet
Vim Cheat Sheet For Programmers Screen
1 page
Introduction To Netmiko
PDF
No ratings yet
Introduction To Netmiko
23 pages
Black Hat Python The Paramiko Module
PDF
No ratings yet
Black Hat Python The Paramiko Module
11 pages
Paramiko Docs
PDF
No ratings yet
Paramiko Docs
76 pages
Paramiko Docs
PDF
No ratings yet
Paramiko Docs
76 pages
Paramiko Docs
PDF
No ratings yet
Paramiko Docs
92 pages
Path To Cloud
PDF
No ratings yet
Path To Cloud
92 pages
Mastering-Stm32 017
PDF
100% (9)
Mastering-Stm32 017
746 pages
LoRa Gateway To Network Server Interface Definition
PDF
No ratings yet
LoRa Gateway To Network Server Interface Definition
19 pages
Cisco UCS 101: Installation and Basic Config: Speak
PDF
No ratings yet
Cisco UCS 101: Installation and Basic Config: Speak
31 pages
CVD DataCenterDesignGuide AUG13 PDF
PDF
No ratings yet
CVD DataCenterDesignGuide AUG13 PDF
156 pages