Nothing Special   »   [go: up one dir, main page]

To Python Network Programming For Network Architects and Engineers

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

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

1.How to take input from the command line or from the keyboard
2.Leveraging socket library to retrieve the IP address of a device
3.Save those names & addresses to disk
4.Simple 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 template1.py Examples of printing, escape sequence and using ANSI text color colorama module

2 template2.py Examples of printing, retrieving command line arguments, console input

3 template3.py Example of functions & using basic Python socket library to retrieve local machine IP information

4 template4.py Examples of combining cmd line arguments and passing arguments to functions

5 template5.py Example of saving/appending network info to a simple text log file

https://cisco.box.com/v/ciscoLivePythonCode
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 ‘pyperclip.py’ 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)

https://cisco.box.com/v/ciscoLivePythonVideos
Introduction to Python Network Programming for Network Architects and Engineers

PRINTING, & ESCAPE SEQUENCES


(template1.py and template2.py)
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

https://docs.python.org/2/reference/lexical_analysis.html
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
(python.exe) this program
(Program_xyz.py) as command line
argumentS
(www.cisco.com, 192.168.10.1)

argv = [ ‘Program_xyz.py’, ‘www.cisco.com’, ‘192.168.10.1’ ]

print argv[0] print argv[1] print argv[2]

‘Program_xyz.py’ ‘www.cisco.com’ ‘192.168.10.1’


Introduction to Python Network Programming for Network Architects and Engineers

Python Interpreter
How do you import Python modules?

argv = [ ‘Program_xyz.py’, ‘www.cisco.com’, ‘192.168.10.1’ ]

Sys is part of python’s sys.py


‘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

sys.py
screen
argv = [ ‘Program_xyz.py’, ‘www.cisco.com’, ‘192.168.10.1’ ]
‘Program_xyz.py’
‘www.cisco.com’
‘192.168.10.1’

import sys

print sys.argv[0]
print sys.argv[1]
print sys.argv[2]

Program_xyz.py

Python Interpreter
Introduction to Python Network Programming for Network Architects and Engineers

TRY IT YOURSELF!
ANSI Color Codes
(bottom of template1.py)
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
PyPi.python.org
How do you download Python modules? colorama.py
(ANSI color)

colorama.py
(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

colorama.py
def class colorama(self):
def init():
do some stuff with colors
return

import colorama

colorama.init()

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

colorama.init()
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


(template3.py & template4.py)
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 socket.py


‘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 = socket.gethostname()
is visible to the ‘outside’
ip_address = socket.gethostbyname(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 = socket.gethostname() Nothing inside a function
# host_name = "www.google.com" is visible to the ‘outside’
ip_address = socket.gethostbyname(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(sys.argv) > 1): # check to see if a name is on the cmd line


Check the command line for
host_name = sys.argv[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 = socket.gethostname() # 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
(template5.py)
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
fp.write(strng)
lines = [“Line 1\n”, Line 2 \n, Line 3 \n”]
fp.writelines(lines)
fp.close()
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(“filename.txt”,”r”) fp = open(“filename.txt”,”r”)
print fp.read(1)  read 1 character print fp.readline()
print fp.read(5)  read the next 5 characters fp.close()
fp.close()  close file, reset offset back to 0
Reading an entire file into a list:
Reading the entire file: fp = open(“filename.txt”,”r”)
fp = open(“filename.txt”,”r”) lines = fp.readlines()
fileBuff = fp.read()  chars not given so read it all print lines
fp.close() 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(“filename.txt”,”r”)
print fp.readline(1)  read 1 character from the next LINE Looping through a file line by line:
print fp.readline(5)  read next 5 character of the current line fp = open(“filename.txt”,”r”)
fp.close() for line in fp:
print line

dir(fp) returns all of the methods that can be used by fp (e.g., ‘seek’)
help(fp.seek) 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 = socket.gethostname()
# host_name = "www.google.com"
ip_address = socket.gethostbyname(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(sys.argv) > 1): # check to see if a name is on the cmd line


host_name = sys.argv[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 = socket.gethostname() # 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")
fp.write(output)
fp.close
Introduction to Python Network Programming for Network Architects and Engineers

THANK YOU

You might also like