0% found this document useful (0 votes)
46 views40 pages

Session 1

The document discusses network automation using Python programming. It notes that network operations are often repetitive, time-consuming, and prone to errors. Programming languages like Python can help automate tasks, eliminate errors, and improve scalability. The document recommends learning Python as it is well-suited for network automation tasks like managing devices, running commands, and gathering statistics. It provides an overview of Python including how to install it, different programming modes, data types, variables, constants, strings, and slicing strings.

Uploaded by

Ah M Ed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views40 pages

Session 1

The document discusses network automation using Python programming. It notes that network operations are often repetitive, time-consuming, and prone to errors. Programming languages like Python can help automate tasks, eliminate errors, and improve scalability. The document recommends learning Python as it is well-suited for network automation tasks like managing devices, running commands, and gathering statistics. It provides an overview of Python including how to install it, different programming modes, data types, variables, constants, strings, and slicing strings.

Uploaded by

Ah M Ed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Network Automation using

Python
Ahmed Elaraby

Ahmed Elaraby 1
Network Operational Problems
• Daily repetitive tasks.

• Highly time consuming operations.

• Fat fingers and mistakes.

• Infrastructure scaling.

• Less technical team members.


Ahmed Elaraby 2
Programming to the Rescue

• Network Engineers no longer need to learn all the different syntax from diverse
vendors, codes can do that !

• Predefined code, eliminates the need to follow long configuration steps.

• Scalability of networks, adding new operational nodes to the networks in just few
clicks.

• One window solution for all operational tasks.

Ahmed Elaraby 3
Why learn Programming

• An Essential Skill For Network Engineers to enhance his capabilities.

• Programming to simplify or automate tasks.

• Programming languages are not just for programmers. If you are a


network engineer, knowing a programming language (or two or three)
can come in handy.

Ahmed Elaraby 4
Programming in Networks

• Manages network more efficiently.

• Network Automation.

• Software define networking.

• Big vendors heading towards software based operations i.e. Cisco,


Juniper.

Ahmed Elaraby 5
• Two forms of network programmability :
• On-box
• Off-box

• On-box programming refers to scripting mechanisms such as :


• Tool command language (TCL)
• Embedded Event Manager (EEM)
• Smart Port Macros
• Python [python Execution Engine]

• Off-box programming refers to scripting mechanisms that exist


outside a network device.
• It can be in the form of an external controller or some external server which
often communicate to the network device using robust and modern APIs.
Ahmed Elaraby 6
Orchestration vs Automation

• Automation
• Well specified task run on its own.

• Orchestration
• Automating a lot of things at once.
• Multiple tasks to execute a workflow.
• Is automation, coordination and management.

• Automation is the first step towards orchestration.


Ahmed Elaraby 7
“Automation” A Smart Way Out !
• Network Automation is a methodology in which programmed scripts
automatically configures, provisions, manages and tests network
devices.

• Why Automation? Programmed management tools are designed to


reduce the complexity of manually configuring and managing
distributed infrastructure resources by enabling speed, ensuring
reliability and compliance.

Ahmed Elaraby 8
Languages For Automation
• Strong binding between Network Automation Tools and Programming
languages.

• Puppet , Chef and Ansible are different paths to achieve a common


goal of managing infrastructure efficiently.

• All these configuration management tools are designed to reduce the


complexity of configuring distributed infrastructure resources,
enabling speed, ensuring reliability and compliance.

Ahmed Elaraby 9
Which Programming Language should we learn

Ahmed Elaraby 10
Type of Languages

• Frontend development is the practice of converting data to graphical


interface for user to view and interact with data.

• Backend of an application is responsible for things like calculations,


logic, database interactions, and performance.

• If we talk about networks, it is used to interact with Nodes and


perform actions such as run commands, gather stats, perform
configurational changes and view output.

Ahmed Elaraby 11
Why Python

• Interpreted
• Object-Oriented
• Extensible–easily import other code
• Embeddable–easily place your code in non-python programs
• Extensive libraries
• Simple
• Easy to Learn
• Free & Open source
• High Level Language –memory management

Ahmed Elaraby 12
Getting started with Python
• Usually a system may have one of the 3 famous Operating System.
• Microsoft Windows
• Apple Mac OS
• Linux Distribution OS

• Python development environment is not included in Windows default


setup.

• In Mac OS X, Python 2 and its built-in Interactive Development


Environment (IDE) comes pre-installed.

• Famous Linux Distributions also have Python enabled on default setup.


Ahmed Elaraby 13
Installing Python

• Linux
• $sudo apt-get install python3

• Windows

Ahmed Elaraby 14
What is PIP
• PIP is a package manager for Python packages, or modules.

• You use PIP to install and update packages and modules as per required by your
python code.

• You can check if PIP is Installed by typing following command


• C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip –version

• If you do not have PIP installed, you can download and install it from,
• https://pypi.org/project/pip/

• pip install packageName


Ahmed Elaraby 15
Python Programming Modes
• Interpreter Mode
• Interactive mode is a command line shell which gives immediate feedback for
each statement.
• The “>>>” indicates that the shell is ready to accept interactive commands.

• Normal Mode (Script Mode)


• is the mode where the scripted (.py) files are run in the Python interpreter.
• Python programs are nothing more than text files, and they may be edited
with a standard text editor program. For example Vim, Nano,
Notepad++,Sublime Text.

Ahmed Elaraby 16
Deeper into Python

Ahmed Elaraby 17
Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.

• Comments starts with a #, and Python will ignore them:


• #This is a comment

• you can add a multiline string (triple quotes) in your code, and place your
comment inside it:
• """
• This is a comment
• written in
• more than just one line
• """
Ahmed Elaraby 18
Variables
• A variable is a named place in the memory where a programmer can
store data and later retrieve the data using the variable “name”.

• Programmers get to choose the names of the variables.

• You can change the contents of a variable in a later statement


• x = 12
• x = 14

Ahmed Elaraby 19
Constants
• Fixed values such as numbers, letters, and strings are called “constants” -
because their value does not change.

• Numeric constants are as you expect.

• String constants use single-quotes (')or double-quotes (").


• >>> print 123
• 123
• >>> print 98.6
• 98.6
• >>> print 'Hello world'
• Hello world

Ahmed Elaraby 20
Data Types
• In Python variables and constants have a “data type”.

• In Python variables are “dynamically” typed. In some other languages you have to
explicitly declare the type before you use the variable.

• In C/C++:
• Int a;
• float b;
• a=5
• b = 0.43

• In Python:
• a=5
• a = “Hello”
• a = [ 5, 2, 1]
Ahmed Elaraby 21
Some Data Types in Python

• Integer (Examples: 0, 12, 5, -5)

• Float (Examples: 4.5, 3.99, 0.1 )

• String (Examples: “Hi”, “Hello”, “Hi there!”)

• Boolean (Examples: True, False)

• List (Example: [ “hi”, “there”, “you” ] )

• Tuple (Example: ( 4, 2, 7, 3) )

Ahmed Elaraby 22
String Data Type
• A string is a sequence of characters.

• A string literal uses quotes ‘Hello’ or “Hello”.


• >>> str1 = "Hello“ >>> str2 = 'there‘

• For strings, + means “concatenate”.


• >>> bob = str1 + str2

• When a string contains numbers, it is still a string.

Ahmed Elaraby 23
Looking Inside Strings

• We can get at any single character in a string using an index specified in square brackets.

• The index value must be an integer and starts at zero.

• The index value can be an expression that is computed.

• >>> fruit = 'banana‘


• >>> letter = fruit[1]
• >>> print letter
• a
• >>> n = 3
• >>> w = fruit[n -1]
• >>> print w
• n

Ahmed Elaraby 24
Slicing Strings
• We can also look at any continuous section of a string using a colon operator.
• The second number is one beyond the end of the slice -“up to but not including”.
• If the second number is beyond the end of the string, it stops at the end.

• >>> s = 'Monty Python‘


• >>> print s[0:4]
• Mont
• >>> print s[6:7]
• P
• >>> print s[6:20]
• Python

• If we leave off the first number or the last number of the slice, it is assumed to be the beginning or end of
the string respectively.

• >>> s = 'Monty Python‘


• >>> print s[:2]
• Mo
• >>> print s[8:]
• thon
Ahmed Elaraby 25
String Concatenation

• When the + operator is applied to strings, it means "concatenation"

• >>> a = 'Hello‘
• >>> b = a + 'There‘
• >>> print b
• HelloThere

• >>> c = a + ' ' + 'There‘


• >>> print c
• Hello There

Ahmed Elaraby 26
Handling User Input

• We prefer to read data in using strings and then parse and convert the data as we need.

• This gives us more control over error situations and/or bad user input.

• Raw input numbers must be converted from strings.

• >>> name = raw_input('Enter:')


• Enter:Chuck
• >>> print name
• Chuck
• >>> apple = raw_input('Enter:')
• Enter:100
• >>> x = apple –10
• >>> x = int(apple) –10
• >>> print x
• 90 Ahmed Elaraby 27
Casting

• Int()

• Float()

• Str()

Ahmed Elaraby 28
Python Collections (Arrays)
• There are four collection data types in the Python programming language :

• List is a collection which is ordered and changeable. Allows duplicate members.

• Tuple is a collection which is ordered and unchangeable Allows duplicate members.

• Set is a collection which is unordered and unindexed No duplicate members.

• Dictionary is a collection which is unordered, changeable and indexed No duplicate


members.

• When choosing a collection type, it is useful to understand the properties of that type
Choosing the right type for a particular data set could mean retention of meaning, and, it
could mean an increase in efficiency or security
Ahmed Elaraby 29
Lists
• A list is a collection which is ordered and changeable In Python lists are written with square
brackets.
• Lists are created using square brackets:
• thislist = ["apple", "banana", "cherry", "apple", "cherry"]
• print( thislist )
• ['apple', 'banana', 'cherry', 'apple', 'cherry']

• You access the list items by referring to the index number.


• print( thislist[1]) >>> banana
• print( thislist[-1]) >>> cherry

• You can specify a range of indexes by specifying where to start and where to end the range.
• print( thislist[1:4]) >>> ['banana', 'cherry', 'apple‘]

• When specifying a range, the return value will be a new list with the specified items.
Ahmed Elaraby 30
• List Length : To determine how many items a list has, use the len() function.
• Print( len(thislist)) >>> 5

• List items can be of any data type:


• list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

• A list can contain different data types:


• list1 = ["abc", 34, True, 40, "male"]

• From Python's perspective, lists are defined as objects with the data type 'list':
• print( type( mylist)) >>> <class 'list'>

• It is also possible to use the list() constructor when creating a new list.
• thislist = list(("apple", "banana", "cherry"))
• print( thislist)
• ['apple', 'banana', 'cherry']
Ahmed Elaraby 31
• To determine if a specified item is present in a list use the in keyword:
• thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
>>> Yes, 'apple' is in the fruits list

• To change the value of a specific item, refer to the index number:


• thislist[1] = "blackcurrant“
• >>> ['apple', 'blackcurrant', 'cherry']
• thislist[:2] = ["blackcurrant", "watermelon"]
• >>> [" blackcurrant ", " watermelon ", "cherry"]
• thislist[1:2] = ["blackcurrant", "watermelon"]
>>> ['apple', 'blackcurrant', 'watermelon', 'cherry']
• thislist[1:3] = ["watermelon"]
>>> ['apple', 'watermelon']
Ahmed Elaraby 32
• To insert a new list item, without replacing any of the existing values, we can
use the insert() method :
• thislist = ["apple", "banana", "cherry"]
• thislist.insert(2, "watermelon")
• print(thislist)
>>> ['apple', 'banana', 'watermelon', 'cherry']

• To add an item to the end of the list, use the append() method:
• thislist.append("orange")
>>> ['apple', 'banana', 'cherry', 'orange']

• To append elements from another list to the current list, use the extend()
method :
• tropical = ["mango", "pineapple", "papaya"]
• thislist.extend(tropical)
>>> ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']

Ahmed Elaraby 33
• The remove() method removes the specified item :
• thislist = ["apple", "banana", "cherry"]
• thislist.remove("banana")
• print(thislist)
>>> ['apple', 'cherry']

• The pop() method removes the specified index :


• thislist.pop(1)
>>> ['apple', 'cherry']

• If you do not specify the index, the pop() method removes the last item.
• The del keyword also removes the specified index:
• del thislist[0] >>> ['banana', 'cherry']

• The del keyword can also delete the list completely.


• del thislist

• The clear() method empties the list.


• The list still remains, but it has no content.
• thislist.clear() >>> [] Ahmed Elaraby 34
• You can loop through the list items by using a for loop:
• thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
>>> apple
banana
cherry

• You can also loop through the list items by referring to their index number.
• for i in range(len(thislist)):
print(thislist[i])

• You can loop through the list items by using a while loop.
• i=0
• while i < len(thislist):
print(thislist[i])
i=i+1

• List Comprehension offers the shortest syntax for looping through lists:
• [print(x) for x in thislist]
Ahmed Elaraby 35
List Comprehension
• List comprehension offers a shorter syntax when you want to create a new list
based on the values of an existing list.
• fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
• newlist = [x for x in fruits if "a" in x]
• print(newlist)
>>> ['apple', 'banana', 'mango']

• Syntax : newlist = [expression for item in iterable if condition == True]

• newlist = [x for x in range(10)]


>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
• newlist = [x for x in range(10) if x < 5]
>>> [0, 1, 2, 3, 4]
• newlist = [x if x != "banana" else "orange" for x in fruits]
>>> ['apple', 'orange', 'cherry', 'kiwi', 'mango']
• newlist = [x.upper() for x in fruits]
>>> ['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']
Ahmed Elaraby 36
• List objects have a sort() method that will sort the list alphanumerically,
ascending, by default:
• thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
• thislist.sort()
• print(thislist)
>>> ['banana', 'kiwi', 'mango', 'orange', 'pineapple']

• To sort descending, use the keyword argument reverse = True:


• thislist.sort(reverse = True)
>>> ['pineapple', 'orange', 'mango', 'kiwi', 'banana']

• The reverse() method reverses the current sorting order of the elements.
• thislist.reverse()
>>> ['cherry', 'Kiwi', 'Orange', 'banana']
Ahmed Elaraby 37
• There are ways to make a copy, one way is to use the built-in List
method copy().
• thislist = ["apple", "banana", "cherry"]
• mylist = thislist.copy()
• print(mylist)
>>> ['apple', 'banana', 'cherry']

• Another way to make a copy is to use the built-in method list().


• mylist = list(thislist)
>>> ['apple', 'banana', 'cherry']

Ahmed Elaraby 38
• There are several ways to join, or concatenate, two or more lists in Python.
• One of the easiest ways are by using the + operator.
• list1 = ["a", "b", "c"]
• list2 = [1, 2, 3]
• list3 = list1 + list2
• print(list3)
>>> ['a', 'b', 'c', 1, 2, 3]

• Another way to join two lists is by appending all the items from list2 into list1,
one by one:
• for x in list2:
list1.append(x)

• Or you can use the extend() method, which purpose is to add elements from
one list to another list:
• list1.extend(list2)
Ahmed Elaraby 39
List Methods
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

Ahmed Elaraby 40

You might also like