introduction to python
TRANSCRIPT
Introduction to Python for Network Engineer (Basic)
Before We Start
Do you know these following languages?
´ C/C++
´ Java
´ Shell
´ Batch
´ TCL
´ Python
Python Overview
´ A script programming language
´ A high-level programming language
´ object-oriented
´ No compilation
´ No datatype declaration
What can Python do?
Many many things which Python could do
but the only one thing we will talk about is
“ Network Automation”
Running Python: Interactively
Python is pre-installed on Linux platform
[porhai@python ~]$ python
Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> print "Hello world"
Hello world
>>>
Running Python: .py file
[porhai@python ~]$ vi khnog.py
print "hello world"
~
~
[porhai@python ~]$ python khnog.py
hello world
[porhai@python ~]$
Python VS Shell
[porhai@python ~]$ echo Hello World
Hello World
[porhai@python ~]$
>>> print "Hello world"
Hello world
>>>
Shell
Python
Python VS Shell
[porhai@python ~]$ vi khnog.sh
echo Hello World
~
[porhai@python ~]$ sh khnog.sh
Hello World
[porhai@python ~]$
Shell Python
[porhai@python ~]$ vi khnog.py
print "hello world"
~
[porhai@python ~]$ python khnog.py
hello world
[porhai@python ~]$
Python Input/Output
>>> x = raw_input("x = ")
x = 123
>>>
>>> print x
123
Python Datatypes
´ Integer (int)
´ Float (float)
´ String (str)
´ List (list)
´ Dictionary (dict)
>>> x=1 >>> type(x) <type 'int'>
>>> x="hello" >>> type(x) <type 'str'> >>>
>>> x=[1,2,3] >>> type(x) <type 'list'>
>>> x={'name':'porhai', 'age':22} >>> type(x) <type 'dict'>
>>> x=1.1 >>> type(x) <type 'float'>
Python Modules
´ Telnetlib
´ Paramiko
´ Smtplib
´ PySNMP
Python Program Example
´ Login to Switch
´ Enter Username and Password
´ Get configuration of interface
´ Output result
Python Code
[porhai@python ~]$ vi khnog.py
import telnetlib
def open_telnet_conn(ip):
#Change exception message
try:
#Define telnet parameters
username = 'porhai'
password = 'porhai'
TELNET_PORT = 23
#Logging into device
connection = telnetlib.Telnet(ip, TELNET_PORT, TELNET_TIMEOUT)
Python Code connection.write(username + "\n")
connection.write(password + "\n")
time.sleep(1)
connection.write("show run int g0/1 \n")
time.sleep(1)
Output = connection.read_very_eager()
print Output
#Closing the connection
connection.close()
except IOError:
print "Input parameter error! Please check username, password and file name."
open_telnet_conn("10.1.1.1")
Python Program Executed
[porhai@python ~]$ python khnog.py
User Access Verification
Username: porhai
Password:
S1#show run int g0/1
Building configuration...
Current configuration : 66 bytes
!
interface GigabitEthernet0/1
no switchport
no ip address
end
Reference
´ Python Language Comparison
https://www.python.org/doc/essays/comparisons/Shell
´ Python Lesson
http://learnpythonthehardway.org/
´ Python for Network Engineers
https://pynet.twb-tech.com/
Thanks you!!!