All the tables provided in the cheat sheets are also presented in tables below which are easy to copy and paste.
The Python Network Programming Cheat Sheet covers:
- Required common installation modules: PIP and IDLE
- Top python network programming libraries
- Network forensics: Required python libraries and scripts
- Python Keywords
- Data Types, Math operators
- Network Analysis with Python
- The dnspython library
- Socket Module (Berkley API interface)
- Socket Types, Creating Sockets
- Socket Examples
- Script Examples
- Parsing Modules
View or Download the Cheat Sheet JPG image
Right-click on the image below to save the JPG file (1987 width x 2362 height in pixels), or click here to open it in a new browser tab. Once the image opens in a new window, you may need to click on the image to zoom in and view the full-sized jpeg.
View or Download the cheat sheet PDF file
Download the cheat sheet PDF file here. When it opens in a new browser tab, simply right click on the PDF and navigate to the download menu.
What’s included in this cheat sheet
The following categories and items have been included in the cheat sheet:
Required common installation modules: PIP and IDLE
PIP (Python Package Installer) | $ sudo apt-get install python-pip |
IDLE (Integrated Development and Learning Environment) | $ sudo apt-get install idle |
Top python network programming libraries
Django | High-level Python Web framework for rapid development and pragmatic |
pycos (formerly asyncoro) | Python framework for asynchronous, concurrent, network, distributed programming and distributed computing |
Diesel | A clean API for writing network clients and servers. TCP and UDP supported. Bundles clients for HTTP, DNS, Redis, Riak and MongoDB. |
Pulsar | Easy way to build scalable network programs |
Twisted | Event-based framework for internet applications: HTTP clients and servers, SSHv2 and Telnet, IRC, XMPP, IMAPv4, POP3, SMTP, IMAPv4, POP3, SMTP, etc. |
NAPALM | Network Automation and Programmability Abstraction Layer with Multivendor support - For dealing with dvice vendors |
gevent | A coroutine -based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libev or libuv event loop |
Celery | Asynchronous task queue/job queue based on distributed message passing |
Network forensics: Required python libraries and scripts
EDDIE Tool | System and network monitoring, security, and performance analysis agent for python |
pypcap | Small packet capture tool based on python and pcap |
Paramiko | Implementation of the SSHv2 protocol, providing both client and server functionality |
pip | Package installer for python |
The Python Package Index (PyPI) | Repository of software for the Python |
Python Keywords
>>> import keyword |
|
Python 2.7.15+ ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] |
|
Python 3.8.0 ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] |
Data Types
Text | str - x = "Hello World" |
Numeric | int, float, complex |
Sequence | list, tuple, range |
Mapping | dict |
Set | set, frozenset |
Boolean | bool |
Binary | bytes, bytearray, memoryview |
Math operators
** | Exponent 4 ** 2 = 16 |
% | Modulus/Remainder 43 % 5 = 3 |
// | Integer division 11 // 5 = 2 |
/ | Division 11 / 5 = 2.2 |
* | Multiplication 3 * 3 = 9 |
- | Subtraction 8 - 3 = 5 |
+ | Addition 2 + 2 = 4 |
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater Than |
<= | Less than or Equal to |
>= | Greater than or Equal to |
Comments
# | Can be used at the start of a line, or from within a line to the end of the line |
Network Analysis with Python
Use NMAP with port scanner | $ pip install python-nmap |
Commands to run NMAP scan | import nmap |
NMAP commands used with python | nmScan.scaninfo() # {'tcp': {'services': ‘25-80’, 'method': 'connect'}} |
The dnspython library
Installation | $ pip install dnspython |
Basic DNS query | import dns.resolver |
Get MX target and name preference | import dns.resolver |
Socket Module (Berkley API interface)
Primary Functions an Methods | socket() • ind() • listen() • accept() • connect() • connect_ex() • send() • recv() • close() |
Socket Types
SOCK_STREAM | For TCP protocols • Reliable transmission • Packet sequence • Connection-oriented • Bidirectional |
SOCK_DGRAM | For UDP protocols • Unreliable transmission • No sequence of packets • Connectionless(UDP) • Not Bidirectional |
Creating Sockets
import socket # Imports the socket method socket.socket() # Function that creates socket |
|
sock = socket. socket (socket family, socket type, protocol=value) |
|
Socket Family | AF_UNIX or AF_INET |
Socket Type | SOCK_STREAM or SOCK_DGRAM for TCP & UDP respectively • e.g. TCP - UDP2 = socket. socket (socket.AF_INET, socket.SOCK_DGRAM) • e.g. UDP - TCP2 = socket. socket (socket.AF_INET, socket.SOCK_STREAM) |
Client socket method | connect() |
Server socket method | bind() • listen(backlog) • accept() |
TCP socket methods | s.recv() # Receive TCP packets |
UDP socket methods | s.recvfrom() # Receives UDP packets |
More Socket Methods |
|
close() | Close the socket connection |
gethostname() | Returns a string which includes the hostname of the current PC |
gethostbyname() | Returns a string which includes the hostname and IP address of the current PC |
listen() | Setup and start TCP listener |
bind() | Attach (host-name, port number) to the socket |
accept() | TCP client connection wait |
connect() | Initiate TCP server connection |
TCP Socket Methods |
|
mysocket.accept() | Returns a tuple with the remote address that has connected |
mysocket.bind( address ) | Attach the specified local address to the socket |
mysocket.connect( address ) | Data sent through the socket assigns to the given remote address |
mysocket.getpeername() | Returns the remote address where the socket is connected |
mysocket.getsockname() | Returns the address of the socket’s own local endpoint |
mysocket.sendto(data, address) | Force a data packet to a specific remote address |
Socket Blocking |
|
setblocking(1) | Setup block |
setblocking(0) | Remove / un-setup block |
Get port number using domain name | import socket |
Check support for IPV6 | import socket |
getaddrinfo() - Bind Server to a Port | from socket import getaddrinfo |
Socket Examples
Client-side socket example |
|
import socket |
|
Client-side Socket example with Comments |
|
# import the socket library |
Script Examples
Create list of devices |
|
>>>devices = ['SW1', 'SW2', 'SW3'] |
|
Create VLAN dictionary list |
|
vlans = [{'id': '100', 'name': 'staff'}, {'id': '200', 'name': 'VOICE'}, |
|
Write functions to collect commands and push to the network |
|
>>>def get_commands(vlan, name): |
|
Create VLANs in multiple switches using python script |
|
>>>for vlan in vlans: |
|
Citation: https://www.oreilly.com/library/view/network-programmability-and/9781491931240/ch04.html |
|
Disable router interface using python command |
|
>>> from push import push_commands |
Parsing Modules
argparse() | The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv |
Creating a parser | >>> parser = argparse.ArgumentParser(description='Process some integers.') |
Adding arguments | >>> parser.add_argument('integers', metavar='N', type=int, nargs='+', |
Parsing arguments | >>> parser.parse_args(['--sum', '7', '-1', '42']) |
Python network programming FAQs
How Python can be used in networking?
Python is a flexible programming language and it can be used to automate many business tasks. On networks, you would use Python scripts to perform maintenance tasks, collect and transform data, or to update settings. A useful application for Python on networks is to ensure coordination between different components in a system. For example, all of the elements in a software-defined network can be aligned through the use of Python scripts.
Is Python good for socket programming?
You can bind and release a socket with Python very easily. There are a number of network traffic management services that you can construct with Python, such as resequencing packets or checking for abandoned connections.
Why is Python good for network automation?
The short answer to why Python is good for network programming is that Cisco System uses it for the on-board programs on its devices, so if they put in lots of research into the relative benefits of programming languages for networking, you could just take their word for it and save yourself a lot of time. Pointing to the qualities that recommend Python for network programming is that it is extensible by libraries in the way that C is but it is much easier to read than C and it doesn’t need to be compiled.