Introduction
to
Python Network Programming
for
Network Architects and Engineers
Vince Kelly
CCIE emeritus
CISSP
Introduction to Python Network Programming for Network Architects and Engineers
UCS and ACI Network Programmability
Part I Python - Blocking and Tackling
- Python Data types; int, float, string
- Python Data Structures
o Lists; List Slicing, List Methods, etc.
- Conditionals; IN, IF, ELIF, While, etc.
- Functions
- Python Modules and Built-in methods
- Python File Operations
Part II Generic Network Programming - Blocking and Tackling
- Python Specific Things for Networking
- Python Socket API UDP/TCP
- Web services/”screen scraping” HTTP/HTTPS
- CRUD operations and Python REST API
- Python XML API
Part III Python Programming for Cisco ACI and UCS Environments
- ACI and UCS Object model review
- Leveraging Python REST API to manage/manipulate ACI and UCS
- Understanding ACI and UCS data structures; “packages”, “classes”, “objects”
- Python code generator for ACI
- “Is there an easier way to do this?”
o ACI toolkit and ACI SDK
Introduction to Python Network Programming for Network Architects and Engineers
[Link] to take input from the command line or from the keyboard
[Link] socket library to retrieve the IP address of a device
[Link] those names & addresses to disk
[Link] UDP based client/server
Introduction to Python Network Programming for Network Architects and Engineers
- Reconvene at 4:30 if you want to
- Python27 based
- No OOP
- No Functional Programming
- Doesn’t follow PEP8 standards, *especially* regarding comments
- MINIMAL use of python frameworks or microframeworks – eg: Flask, Django, etc.
- MINIMAL error correction (that’s your job later)
- No intermediate or advanced Python language ‘techniques’
- lamda’s, closure/decorators, list comprehension, etc., etc.
- No advanced system or networking techniques, e.g:
- Queuing, threading, asynchronous event processing, error correction, etc., etc.
- No effort of any kind to write clean, efficient, bullet-proof, compact, ‘beautiful code’
- The emphasis is ‘easy to understand’ over ‘production ready’ code
Introduction to Python Network Programming for Network Architects and Engineers
Code Templates
Template Name Description
1 [Link] Examples of printing, escape sequence and using ANSI text color colorama module
2 [Link] Examples of printing, retrieving command line arguments, console input
3 [Link] Example of functions & using basic Python socket library to retrieve local machine IP information
4 [Link] Examples of combining cmd line arguments and passing arguments to functions
5 [Link] Example of saving/appending network info to a simple text log file
[Link]
Introduction to Python Network Programming for Network Architects and Engineers
“Flaky” Python Background Videos
Video Length Name
1 14 min Background Compiled vs. Interpreted languages. Python interpreter process.
2 13 min Python Implementation High level Python implementation differences, Cpython, Jython, IronPython, etc.
3 20 min Python 2.7 vs. Python 3.5 High level discussion on differences between Python2.7 vs. Python3.5 and rationale for installing them
4 22 min Python Installation Installing Python 2.7.12 Example of cutting & pasting to Windows7 clipboard using ‘[Link]’ module
5 17 min Python Post Install 1 Downloading Python modules from PyPi and incorporating them in programs
6 12 min Python Post Install 2 Isolating Python modules and code in the development environment using virturalenv
7 9 min Python Post Install 3 Installing Python 3.5.3, running Python 2.7 and 3.5 together
8 10 min Python Post Install 4 Isolating Python 3.5 development environment. Downloading Pylint, (Python error & syntax checker)
[Link]
Introduction to Python Network Programming for Network Architects and Engineers
PRINTING, & ESCAPE SEQUENCES
([Link] and [Link])
Introduction to Python Network Programming for Network Architects and Engineers
CONCATENATION
print "Quote's can have LOT's of Quote's!" Just need to be consistent
print "Hello World using 'old Python' !" # Python2.7 and below
print ("Hello World using ‘new Python' !“) # Python3.x
### Concatenation ####
variable1 = "This is a 'sequence’ " # data type will be string
variable2 = "with a value of" # data type will be string
variable3 = 5678 # data type will be INTEGER
print variable1 + " " + variable2 # concatenates/displays it all together
print variable1 + variable2 , variable3 # you can't concatenate different data types!
print variable1 + variable2 + str(variable3) # same thing just forcing it all to be a string
Introduction to Python Network Programming for Network Architects and Engineers
SUBSTITUTION
….directly INSIDE this string?
variable1 = "This is a 'sequence’ with a value of " # data type will be string
variable3 = 5678 # data type will be INTEGER
What if I want to insert this number….
# How Python 2.x does it:
#
print "The Python 2.7 way: '\n‘ %s %d"% (variable1, variable3)
#
The The
Create
first second variable
2 variable
‘placeholders’ found
found inside
will will
getthe gethere
placed
string placed
(so here
for variable1(so youamake
you better
with better
‘string’make
suredata sure
datathe
thetype data
types aretypes are correct
correct
and variable3 with an ‘integer’ data type
# How Python 3.x does it:
#
print ("The Python3.5 way: '\n' {0} {1:d}".format(variable1, variable3))
#
The same thing happens but formatted differently
Introduction to Python Network Programming for Network Architects and Engineers
ESCAPE SEQUENCES
Tells Python how to do special things
[Link]
Introduction to Python Network Programming for Network Architects and Engineers
### Escape Sequences ##
print "printing new line:" # print statement Python 2.7 and below
print "hello world\n there“ # newline character anywhere inside a string
print '\n‘ # or by itself
print ("printing back spaces:") # print function Python 2.7 or 3.x and above
print ("hello world\b\b\b\b\bthere !") # backspace character – try it and see what happens
print '\n'
print "printing tabs" # print tab
print "hello world\tthere !"
print '\n'
Introduction to Python Network Programming for Network Architects and Engineers
IMPORTING MODULES
Introduction to Python Network Programming for Network Architects and Engineers
Start python Save whatever comes
Find & execute
Interpreter after the program name
([Link]) this program
(Program_xyz.py) as command line
argumentS
([Link], [Link])
argv = [ ‘Program_xyz.py’, ‘[Link]’, ‘[Link]’ ]
print argv[0] print argv[1] print argv[2]
‘Program_xyz.py’ ‘[Link]’ ‘[Link]’
Introduction to Python Network Programming for Network Architects and Engineers
Python Interpreter
How do you import Python modules?
argv = [ ‘Program_xyz.py’, ‘[Link]’, ‘[Link]’ ]
Sys is part of python’s [Link]
‘standard library’ System stuff
import sys
Source Code
Python
Program_xyz.py
Interpreter
Operating System
Introduction to Python Network Programming for Network Architects and Engineers
[Link]
screen
argv = [ ‘Program_xyz.py’, ‘[Link]’, ‘[Link]’ ]
‘Program_xyz.py’
‘[Link]’
‘[Link]’
import sys
print [Link][0]
print [Link][1]
print [Link][2]
Program_xyz.py
Python Interpreter
Introduction to Python Network Programming for Network Architects and Engineers
TRY IT YOURSELF!
ANSI Color Codes
(bottom of [Link])
Introduction to Python Network Programming for Network Architects and Engineers
ANSI Color Codes:
\033[ text-style m; text-color m; text-background m
Text Style Text Color Background
0 – Reset to default 30 – Black 40 - Black
1 - Bold 31 – Red 41 - Red
2 - Faint 32 – Green 42 - Green
3 - Italic 33 – Yellow 43 - Yellow
4 – Underline 34 – Blue 44 - Blue
5 – Blink: slow 35 – Magenta 45 - Magenta
6 – Blink: fast 36 – Cyan 46 - Cyan
7- Negative 37 - White 47 - White
8 – Conceal
9 – Strike Through
Don’t forget to reset everything back!
\033[0m
Introduction to Python Network Programming for Network Architects and Engineers
Python Interpreter
[Link]
How do you download Python modules? [Link]
(ANSI color)
[Link]
(ANSI color) PIP !
import colorama
Source Code
Python
Program_xyz.py
Interpreter
Operating System
“Good Programmers write code, GREAT Programmers steal code”
Introduction to Python Network Programming for Network Architects and Engineers
[Link]
def class colorama(self):
def init():
do some stuff with colors
return
import colorama
[Link]()
Program_xyz.py
Python Interpreter
Introduction to Python Network Programming for Network Architects and Engineers
Text style Text color
1 means 31 is RED
BOLD
import colorama escape end escape
sequence sequence
[Link]()
print ("printing color red in bold:")
print"\n“ \033[1;31m
separate
boldRed = "\033[1;31m" #
attributes
end = "\033[0;0m" # restore default color
with a ;
print "this is: " + boldRed + "the color " + end
print "\n"
\033[0;0m
Text Text
style color
Introduction to Python Network Programming for Network Architects and Engineers
FUNCTIONS & NETWORK MODULES
([Link] & [Link])
Introduction to Python Network Programming for Network Architects and Engineers
Python Interpreter
How do you import Python networking modules?
Socket is part of python’s [Link]
‘standard library’ System stuff
import socket
Source Code
Python
Program_xyz.py
Interpreter
Operating System
NIC
Introduction to Python Network Programming for Network Architects and Engineers
Firefox
import socket UCSM APIC
Program_xyz.py Browser
“Higher Layer” Libraries
HTTP, etc.
Socket Library
Web FTP Telnet POP3 SNMP SYSLOG
TCP/IP PROTOCOL STACK
5678 80 161 514
20,21 23 110
TCP UDP
IP
Device Drivers
LAYER 2 PROTOCOL STACK
Framer/
Protocol
decode
B
U
Tx S Rx
Buffers Buffers
LAYER 1 NIC
Introduction to Python Network Programming for Network Architects and Engineers
Functions: Small blocks of code that don’t get executed until they are called
## Template 3
# Examples of using functions and basic Python socket library
# this just prints out the local machine NIC information
#
Functions starts with import socket
the def statement and
ends with the return def get_machine_info():
Nothing inside a function
host_name = [Link]()
is visible to the ‘outside’
ip_address = [Link](host_name)
print "host name is: \t\t\t %s " % host_name
print "This machines IP address is: \t %s" % ip_address
return
Notice we can combine statements.
In this case we issue the call to
# call the function named 'get_machine_info'
‘get_machine_info() function and then
print what’s returned.
print "\n", get_machine_info()
Introduction to Python Network Programming for Network Architects and Engineers
Functions: Small blocks of code that don’t get executed until they are called
#Template 4
# combines command line, functions
import socket, sys
Functions gets passed a
host name and returns def get_machine_info(host_name):
an IP address # host_name = [Link]() Nothing inside a function
# host_name = "[Link]" is visible to the ‘outside’
ip_address = [Link](host_name)
print "host name is: \t\t\t %s " % host_name
print "This machines IP address is: \t %s" % ip_address
return host_name, ip_address
if (len([Link]) > 1): # check to see if a name is on the cmd line
Check the command line for
host_name = [Link][1] # it is, so use that name
Parameters if nothing is there
else:
just use our local machine
print "machine name not specified on the command line"
information
print "so I'm using the local machine name instead\n" # if name not specified on command line
host_name = [Link]() # then just set default name to local host
name, address = get_machine_info(host_name)
print “%s %s”% (name, address)
Introduction to Python Network Programming for Network Architects and Engineers
FILES
([Link])
Introduction to Python Network Programming for Network Architects and Engineers
(Text) File Modes
Mode Description
“r” Read fro a txt file. Error if file not found
“w” Write to a file. If it already exists, it will be overwritten, if not it will be created
“a” Append to a file if it already exists, if not it will be created
“r+” Read and Write to a file. Created if it doesn’t exist, data is appended if it does
“w+” Write to and Read from a file. If it exists, its overwritten, if not its created
“a+” Append and Read from a file. Append if the file exists, create file if it dosen’t
Writing single string and list of strings to a file
fp = open(“filename”, “w”)
strng = “this is 1 string” a CR\LF will NOT be automatically added
[Link](strng)
lines = [“Line 1\n”, Line 2 \n, Line 3 \n”]
[Link](lines)
[Link]()
Introduction to Python Network Programming for Network Architects and Engineers
File Read Operations
Reading characters from a file: Reading one line at a time:
fp = open(“[Link]”,”r”) fp = open(“[Link]”,”r”)
print [Link](1) read 1 character print [Link]()
print [Link](5) read the next 5 characters [Link]()
[Link]() close file, reset offset back to 0
Reading an entire file into a list:
Reading the entire file: fp = open(“[Link]”,”r”)
fp = open(“[Link]”,”r”) lines = [Link]()
fileBuff = [Link]() chars not given so read it all print lines
[Link]() print len(lines) Each line becomes
for line in lines: A string element in
print line a list
Reading characters from a line:
fp = open(“[Link]”,”r”)
print [Link](1) read 1 character from the next LINE Looping through a file line by line:
print [Link](5) read next 5 character of the current line fp = open(“[Link]”,”r”)
[Link]() for line in fp:
print line
dir(fp) returns all of the methods that can be used by fp (e.g., ‘seek’)
help([Link]) print doc on the seek command
Introduction to Python Network Programming for Network Architects and Engineers
#Template 5
# piggyback on templete4 and write info retrieved to disk
# 'appending' to a simple text logfile
#
import socket, sys
def get_machine_info(host_name):
# host_name = [Link]()
# host_name = "[Link]"
ip_address = [Link](host_name)
print "host name is: \t\t\t %s " % host_name
print "This machines IP address is: \t %s" % ip_address
return host_name, ip_address
if (len([Link]) > 1): # check to see if a name is on the cmd line
host_name = [Link][1] # it is, so use that name
else:
print "machine name not specified on the command line"
print "so I'm using the local machine name instead\n" # if name not specified on command line
host_name = [Link]() # then just set default name to local host
name, address = get_machine_info(host_name)
print "\nwriting name and IP Address to disk"
print name, address
###########################
# Wirte output to disk log file
output = name + " " + address + "\n"
fp = open("ip_addresses.txt","a")
[Link](output)
[Link]
Introduction to Python Network Programming for Network Architects and Engineers
THANK YOU