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)
281 views
Python For Network Engineers
Python Reference for Network Engineers
Uploaded by
Albert Suwandhi
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
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)
281 views
Python For Network Engineers
Python Reference for Network Engineers
Uploaded by
Albert Suwandhi
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
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
Incubator Airflow
PDF
No ratings yet
Incubator Airflow
267 pages
Saurav Dudulwar Resume
PDF
No ratings yet
Saurav Dudulwar Resume
1 page
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
Writing Simple Automation Scripts With Python
PDF
No ratings yet
Writing Simple Automation Scripts With Python
3 pages
Aws Cli PDF
PDF
No ratings yet
Aws Cli PDF
94 pages
Data Science Assignment 1
PDF
No ratings yet
Data Science Assignment 1
20 pages
Ipv6 Cheat Sheet
PDF
No ratings yet
Ipv6 Cheat Sheet
2 pages
Nifi Expression Language Cheat Sheet
PDF
100% (1)
Nifi Expression Language Cheat Sheet
2 pages
Allied Telesis Ip Addressing & Subnetting Guide
PDF
No ratings yet
Allied Telesis Ip Addressing & Subnetting Guide
1 page
DevOps KKK PDF
PDF
No ratings yet
DevOps KKK PDF
168 pages
Devops Slides
PDF
No ratings yet
Devops Slides
223 pages
LABGuide - AWS Solution Architect Professional - AutoScalling
PDF
No ratings yet
LABGuide - AWS Solution Architect Professional - AutoScalling
11 pages
Learning Apache Spark With Python
PDF
No ratings yet
Learning Apache Spark With Python
10 pages
Deploying Jupyter Notebooks For Students and Researchers
PDF
No ratings yet
Deploying Jupyter Notebooks For Students and Researchers
35 pages
Notes AWS Solutions Architects
PDF
No ratings yet
Notes AWS Solutions Architects
55 pages
Getting Connected: Choosing An SSH Client
PDF
No ratings yet
Getting Connected: Choosing An SSH Client
14 pages
Flask Restful
PDF
No ratings yet
Flask Restful
37 pages
CP R80.40 Installation and Upgrade Guide
PDF
No ratings yet
CP R80.40 Installation and Upgrade Guide
799 pages
Programming1 Lecture Presentations
PDF
No ratings yet
Programming1 Lecture Presentations
124 pages
2 HDFS Commands
PDF
No ratings yet
2 HDFS Commands
7 pages
Install Sqoop
PDF
No ratings yet
Install Sqoop
7 pages
DevOps Training Curriculum
PDF
No ratings yet
DevOps Training Curriculum
6 pages
Hitachi Unified Storage - Operations Gui PDF
PDF
No ratings yet
Hitachi Unified Storage - Operations Gui PDF
580 pages
Python How To Regex
PDF
No ratings yet
Python How To Regex
19 pages
Meridian Crash Course
PDF
No ratings yet
Meridian Crash Course
6 pages
Beaglebone Black
PDF
No ratings yet
Beaglebone Black
63 pages
Frrouting Developers Guide
PDF
No ratings yet
Frrouting Developers Guide
315 pages
Oracle 1Z0-883: Mysql 5.6 Database Administrator
PDF
No ratings yet
Oracle 1Z0-883: Mysql 5.6 Database Administrator
59 pages
Pytest Documentation: Release 2.7.1
PDF
No ratings yet
Pytest Documentation: Release 2.7.1
219 pages
Aws Three Practical Use Cases With Databricks Ebook v5 101221
PDF
No ratings yet
Aws Three Practical Use Cases With Databricks Ebook v5 101221
34 pages
PTC Big Data Analysis With ApacheS 27.11-28.11.2019 Handout
PDF
No ratings yet
PTC Big Data Analysis With ApacheS 27.11-28.11.2019 Handout
48 pages
Cacti PDF
PDF
100% (1)
Cacti PDF
44 pages
Course in Erlang
PDF
100% (8)
Course in Erlang
48 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
Software Developer Resume
PDF
No ratings yet
Software Developer Resume
1 page
RegularExpression Notes
PDF
No ratings yet
RegularExpression Notes
17 pages
TCP IP Applications
PDF
No ratings yet
TCP IP Applications
10 pages
Akash Resume
PDF
No ratings yet
Akash Resume
7 pages
NovelVista - Course Content - DBT - PDF
PDF
No ratings yet
NovelVista - Course Content - DBT - PDF
3 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
Course Contents of Hadoop and Big Data
PDF
No ratings yet
Course Contents of Hadoop and Big Data
11 pages
COM-421-Lecture-Notes-7 - Open Stack
PDF
No ratings yet
COM-421-Lecture-Notes-7 - Open Stack
24 pages
Mourya K Data Engineer
PDF
No ratings yet
Mourya K Data Engineer
7 pages
Donald Ngandeu 1
PDF
No ratings yet
Donald Ngandeu 1
6 pages
Cisco APIC Python API Documentation
PDF
100% (1)
Cisco APIC Python API Documentation
93 pages
OpenEDG Python Institute Fulda
PDF
No ratings yet
OpenEDG Python Institute Fulda
48 pages
Docker Handwritten Notes PDF Free
PDF
No ratings yet
Docker Handwritten Notes PDF Free
61 pages
Python Web Framework
PDF
No ratings yet
Python Web Framework
17 pages
Python Lab
PDF
No ratings yet
Python Lab
87 pages
5 2023 24 10 04 49 17
PDF
No ratings yet
5 2023 24 10 04 49 17
229 pages
Code Obfuscation
PDF
No ratings yet
Code Obfuscation
15 pages
Cisco Live 2021 Learning Maps All
PDF
No ratings yet
Cisco Live 2021 Learning Maps All
43 pages
Unix File System
PDF
No ratings yet
Unix File System
95 pages
Python Notes - 1
PDF
No ratings yet
Python Notes - 1
364 pages
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
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