Learn Python

By stretch | Thursday, March 27, 2014 at 1:10 a.m. UTC

Around six years ago, I decided to start a website called packetlife.net. Maybe you've heard of it. Most people turn to a purpose-built content management system like Wordpress or Drupal for such an endeavor, but I needed greater flexibility to achieve some of the projects I had in mind. This meant I needed to learn a programming language and write a good amount of the site's logic myself.

I already had some experience dabbling in PHP, but wasn't thrilled with it. I figured if I was going to learn a new language, it should be useful as a general purpose language and not just for building a web site. After a bit of research and deliberation, I chose Python (and the Django web framework).

The purpose of this post is to convince networkers with little to no experience writing code to learn Python. In the past I've encouraged fellow networkers to pick up any programming language, as it's more important to think like a programmer than it is to gain proficiency in a particular language. However, I've realized that many people get stuck on which language they want to learn, lose motivation, and end up not growing proficient in anything. So, I've started telling people to skip that first step and just learn Python.

Why Python?

So why should you learn Python, specifically? Here are some reasons. (To the more contrary readers among you, please recognize that these are reasons for learning Python and not to be taken as slights against any other language.)

It's a general purpose language. Python can be used to script out device configs, crunch data, serve a website (like this one), generate packets, play games - whatever you want it to do.

It's easy to learn. Even if you have zero programming experience, chances are you'll be able to pick up Python pretty quickly. There are many excellent free resources available, which are listed toward the end of this article.

It's quick to write. Python is an interpreted language and light on syntax. It's similar to a scripting language, but made far more powerful through the inclusion of external libraries.

It's convenient. Python's interactive command interpreter makes for quick and fun code experiments. Small chunks of code are easily copied and pasted for evaluation.

It's mature and widely supported. Python has been around for more than two decades. There are many thousands of packages available for it.

It's preferred by many network vendors. Cisco and Juniper both provide Python APIs to some of their network operating systems, and Arista's CLI is actually built on it. Python appears to be the language of choice for many network vendors.

What can I do with Python?

Lots of stuff. You can quickly script out configuration commands to copy and paste:

>>> for i in range(0, 48):
...   print "set interface xe-0/0/%d.0 family inet address 10.0.%d.1/24" % (i, i)
... 
set interface xe-0/0/0.0 family inet address 10.0.0.1/24
set interface xe-0/0/1.0 family inet address 10.0.1.1/24
set interface xe-0/0/2.0 family inet address 10.0.2.1/24
set interface xe-0/0/3.0 family inet address 10.0.3.1/24
...

You can use it to send email:

>>> import smtplib
>>> s = smtplib.SMTP('localhost', 1025)
>>> s.sendmail('me@example.com', 'you@example.com', "Python is awesome!")

And receive email:

$ python -m smtpd -n -c DebuggingServer localhost:1025
---------- MESSAGE FOLLOWS ----------
Python is awesome!
------------ END MESSAGE ------------

Populate NetDot with hundreds of objects in just minutes using bulk HTTP requests:

import requests
i = 0
for rack in range(101, 121) + range(201, 221) + range(301, 321):
    for d in ['tor%sa' % rack, 'tor%sb' % rack, 'mgmt%s' % rack]:
        r = requests.post('http://netdot.local/netdot/management/host_tasks.html',
            data = {
                'add_host_address': '10.1.0.%d' % i,
                'name': "%s.example.com" % d,
            },
        )
        i += 1

Send, receive, and manipulate packets with Scapy:

Welcome to Scapy (2.2.0)
>>> sr1(IP(dst='8.8.8.8')/UDP()/DNS(rd=1,qd=DNSQR(qname='packetlife.net')))
Begin emission:
Finished to send 1 packets.
.*
Received 2 packets, got 1 answers, remaining 0 packets
<IP  version=4L ihl=5L tos=0x20 len=76 id=34777 flags= frag=0L ttl=41 proto=udp chksum=0xcd5e src=8.8.8.8 dst=192.168.0.67 options=[] |<UDP  sport=domain dport=domain len=56 chksum=0x230 |<DNS  id=0 qr=1L opcode=QUERY aa=0L tc=0L rd=1L ra=1L z=0L rcode=ok qdcount=1 ancount=1 nscount=0 arcount=0 qd=<DNSQR  qname='packetlife.net.' qtype=A qclass=IN |> an=<DNSRR  rrname='packetlife.net.' type=A rclass=IN ttl=3153 rdata='173.255.200.61' |> ns=None ar=None |>>>

Dump the routing table from a Nexus 9000 using NX-API (code courtesy of Matt Oswalt):

>>> from nxapi_utils import *
>>> thisNXAPI = NXAPI()
>>> thisNXAPI.set_target_url('http://10.1.1.1/ins')
>>> thisNXAPI.set_username('admin')
>>> thisNXAPI.set_password('cisco')
>>> thisNXAPI.set_msg_type('cli_show')
>>> thisNXAPI.set_cmd('show ip route')
>>> returnData = thisNXAPI.send_req()
>>> print returnData
<?xml version="1.0"?>
<ins_api>
    <type>cli_show</type>
    <version>0.1</version>
    <sid>eoc</sid>
    <outputs>
...

Write a quick-and-dirty syslog daemon:

>>> from socket import *
>>> syslogd = socket(AF_INET, SOCK_DGRAM)
>>> syslogd.bind(('localhost', 514))
>>> while True:
...     message, source = syslogd.recvfrom(2048)
...     print "[%s] %s" % (source[0], message)
... 
[10.10.8.1] %SYSTEM-0-ENVIRONMENTAL: Supervisor 0 has caught fire. Dispersing halon...

...and lots more! Whenever you encounter an operational challenge, the odds are good are that Python can help solve it.

Where can I learn Python?

LearnPython.org is the go-to resource for many newbies. The tutorials include a live Python shell directly within your web browser, so you can get started without even needing to install anything.

Learn Python the Hard Way is a great starting place for people with zero previous experience writing code. Worthwhile if you stick with it through the more monotonous parts.

Codecademy provides a very immersive, experimentation-driven approach with lots of practical examples.

These are just a few of numerous resources available. Download Python today and see what you can do!

About the Author

Jeremy Stretch is a network engineer living in the Raleigh-Durham, North Carolina area. He is known for his blog and cheat sheets here at Packet Life. You can reach him by email or follow him on Twitter.

Posted in Education

Comments


Kirk Byers (guest)
March 27, 2014 at 4:29 a.m. UTC

One other interesting thing about Python it is installed by default on almost all versions of Linux. And since many networking platforms are built on Linux, the networking platform will also have Python on box (for example, Arista, NX-OS).

Some other very useful libraries for network engineers (Paramiko SSH - that you can use to SSH into routers/switches; telnetlib - same thing but for telnet; ncclient - for netconf integration; snmp libraries).

I have a blog post on Paramiko SSH integration to network devices.

Jerald Swan had some recommendations for network engineers learning Python.

Jeremy Schulmann has also been doing some interesting things with Python for Juniper devices.


biOos (guest)
March 28, 2014 at 12:03 a.m. UTC

Very nice post. I study python some times and your use is simple infinity.


Vineet (guest)
March 28, 2014 at 5:42 p.m. UTC

A few weeks ago I started dabbling into Python on a friend's insistence. Was feeling a bit down and out and viola! Jeremy posts this! Thanks a lot. :)


Mike (guest)
March 31, 2014 at 7:52 p.m. UTC
pompeychimes
April 1, 2014 at 6:55 a.m. UTC

Great timing. I needed this direction.


Chris (guest)
April 4, 2014 at 1:11 a.m. UTC

What code base do you recommend, 2 or 3?


Jeff (guest)
April 4, 2014 at 9:26 a.m. UTC

What a coincidence, I just started learning Python and reading the "Learning Python". After reading your article I'm more eager to learn the Python now!

Thank you Jeremy.


Scott McDermott (guest)
April 19, 2014 at 1:55 p.m. UTC

Another fun Python learning tool is Python Koans. It's a python program with integrated bugs and unfinished sections which teaches you through fixing them. It's a neat idea.


Josey (guest)
April 23, 2014 at 3:58 p.m. UTC

Nice article, I've been tipping away at python since the new year, took awhile to get it.

Could you write a function to ssh into your switch and paste in the interface config above?


vijay2make
May 31, 2014 at 12:32 a.m. UTC

Great! Motivation to learn Python.Thanks Jeremy!


Roesnet (guest)
June 5, 2014 at 12:33 a.m. UTC

I recently heard support for version 2.7 will go to 2020.


2marshall8
June 6, 2014 at 11:57 p.m. UTC

Great stuff. I'm going to start learning this weekend. I've been debating what language to start on for a while. This article is perfect coming from an expert. I got my first job as a network engineer 4 months ago and really want to get up to speed on Cisco automation, and network automation.

Thanks Jeremy


Rishabh Jain (guest)
June 10, 2014 at 6:40 p.m. UTC

Thanks for the directions.. was thinking to learn something new and this will surely help.. looking fwd to do something amazing linking python and networking.


murphyslaww
July 7, 2014 at 9:54 p.m. UTC

There is also a great class in Coursera.org. I've tried to make time to take this three times, but CCNP study has always trumped it. CCNP is complete, so my excuses are out the window.

Next class starts in September. It's set up like a normal college course and is taught by CS professors from Rice University in Houston, one of our better private colleges. They have a web-based IDE set up for you to use.

https://www.coursera.org/course/interactivepython

Leave a Comment


Optional; will not be displayed publicly or given out.
No commercial links. Only personal (e.g. blog, Twitter, or LinkedIn) and/or on-topic links, please.
What is the decimal equivalent of 0x5F0E?