0% found this document useful (0 votes)
4 views35 pages

Python Programming Final

This document provides an introduction to Python programming, covering its history, capabilities, and advantages. It includes fundamental concepts such as variables, data types (numbers, strings, arrays), operators, and control structures (if-else statements and loops). Additionally, it explains the use of lists, tuples, and dictionaries in Python, along with examples and syntax for each topic.

Uploaded by

sohilahishamm70
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)
4 views35 pages

Python Programming Final

This document provides an introduction to Python programming, covering its history, capabilities, and advantages. It includes fundamental concepts such as variables, data types (numbers, strings, arrays), operators, and control structures (if-else statements and loops). Additionally, it explains the use of lists, tuples, and dictionaries in Python, along with examples and syntax for each topic.

Uploaded by

sohilahishamm70
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

Python Programming

Prepared by:
Eslam Ahmed Nour EL Deen
Python Programming
Introduction to programming
A program, is simply a sequence of commands to be executed by the processor. High-level programming language is the
scripting language that’s readable by human, but Computers can only understand ‘0’s and ‘1’s , so we need to an entity that
convert our code into the language that can be understood by computer , this entity is called Interpreter , or Compiler.

1. Introduction to Python
What’s python?
Python is a simple programming language that’s developed in 1991 by Guido van Rossum.
What python can do?
Python,as any other programming language,can create desktop applications,web applications, automate any
repeatitive operations and convert any logic into an executable process , also it can interact with different file
formats.
What’s the power of python?
 Very easy to learn and practice
 Can run on multiple platforms (i.e windows , Linux , Mac , … )
 Supports much of ready functions that help programmers save time & effort
 It runs on interpreter systems so it’s executed very fast
 It supports both procedural and Object-Oriented Programming (OOP)
 Python code is very readable to any non-programmer

[Link] Basics
2.1 Variables
A variable in programming is simply a store in memory to hold some data which may be integers , string , boolean value , or
other object.

Example
a = 10 //here we defined a variable named [a] , and assign it a value [4] , so [a] is now an integer
a = “10” //here we defined a variable named [a] , and assign it a value [“4”] , so [a] is now a string
s = “cisco” // here we defined a variable named [s] , and assign it a value [“cisco”] , so [s] is now a string
b = TRUE // here we defined a variable named [b] , and assign it a value [TRUE] , so [b] is now a boolean

Notes
 Variable hold the last value assigned to it in the program
X = 10
X = 25
X = 15
//now the current value of X is 15
 Variable name can’t contain special characters except under_score (_)
 Variable name can only start with a letter or under_score , it can never start with a number
_name  valid
Switchvalid
[Link]not valid
 Variables are case-sensitive
So , router not equal Router
2.2 Numbers
Numbers in python are data types that has numeric characterestics , we have multiple types of a Numbers data type , as {int
{Float}.
 Int : it is an Integer that holds a whole number , either positive or negative , without decimal
 Float : it is a number that contains decimals , either positive or negative

Example
X = 10 // integer
Y = 2008938493788683623 //integer
Z = -575652635625 //integer
a = 20.5 //float
b = -443324864.63552 //float

Note:
 Python doesn’t require to define the data type when defining the variable

2.3 Strings
 A string is determined by a single or double quotations , (‘ ‘) or (“ “)
 Strings are considered as an array of characters
 To access any character in a string , use the square brackets [] , with specifying the index
 The index of the first character is [0]
 To include the quotation as a part of the string , use the escape character (\)

Example
String Functions & Manipulation…

Select substring
It returns a string starting from the first index and end with (last index-1)
White space is countered as a character
If first index not defined , so it means to start from index 0
If last index not defined , so it means to return to the last character
If both indices not defined , it means to return the whole string

len()
To get the length of a string use this function
len(string)

Replace()
Replace any text in the string by another
It doesn’t change the original variable
Split()
It divides the string into substrings based on the specified parameter
 It doesn’t change the original variable
It returns a list of strings

lower()
Convert all string characters to small letters
 It doesn’t change the original variable

Upper()
Convert all string characters to capital letters
It doesn’t change the original value
Find(str)
It’s used when we need to search for a simple string in large text
If string not found , it will return (-1)
If string found , it will return its index in the text

2.4 Operators
 Operators are special symbols in python used to do operations on different variables
 The variables on which the operators work are called “operands”
 There are many types of operators in python , like:
 Arithmetic
 Logical
 Assignment
 Comparison

Arithmetic Operators
Are used to perform arithmetic operations on numeric values (addition , subtraction , multiplication , division , …)

Operator Definition
+ Addition
- Subtraction
* Multiplication
/ Division (The return type is float)
% Mod (the result is the remainder of the division process)
Logical Operators
It’s used to combine two or more conditions which has one of two values (TRUE | FALSE)

Operator Definition
and If , at least , one condition is FALSE , the result is false
Or If , at least , one condition is TRUE , the result is true
not It reverses the value

Assignment Operators
It’s that type of operators that enables you to assign a value to certain variable
Operator Equal to …
= var = value
+= var = var + value
-= var = var - value
*= var = var * value
/= var = var / value
%= var = var % value
Comparison Operators
It’s used to compare two variables , or a variable with constant value
It returns TRUE if the condition is right , and ; if the condition is wrong

Operator Definition
== Check if two values are equal
!= Check if two values not equal
> Check if left operand is greater than right operand
< Check if left operand is less than right operand
>= Check if left operand is greater than or equal right operand
<= Check if left operand is less than or equal right operand
2.5 Arrays
Array is a data store that can carry multiple values grouped in one entity
In python , there are four types of Array (List , Tuple , Set , Dictionary)

2.5.1 Lists
List format : [item1 , item2 , item3 , ….. , item(len-1)]
Lists are a group of items that’s ordered , indexed , and can be modified (can add items , remove items , edit items)
List is defined by these brackets []
List items can be of any data type , strings , integers , or even another list (nested lists)
List can carry mix of data types
A list index is numeric , and 1st index in a list is [0]

List Definition

Access List Items

List length
It returns list length (no. of items inside a list)
Add Items
There are two ways to add items to list

[Link]() method
It will add the item after the last item in the list

[Link]() method
It’s used when you need to insert an item in certain index
All the next items to the specified index are shifted

Modify items

Delete Items from list


There are three ways to delete an item from a list

[Link]() method
It removes an item with specifying the value

[Link]() method
It removes the last item in the list
It returns the value of the removed item
[Link] keyword
It removes the item by its index

Nested Lists
An item inside may be another list
To access an item inside the 2nd level list , you have to specify two level of indices

Delete List
Delete the whole list object

Clear List
Delete all list items , but the list object still exists

2.5.2 Tuples
Tuple format : (item1 , item2 , item3 , ….. , item(len-1))
Tuples are a group of items that’s ordered , indexed , but can’t be modified (can’t add items , remove items , edit items)
A tuple is defined by these brackets ()
Tuple items can be of any data type , strings , integers , or even another tuple (nested tuples)
A tuple can carry mix of data types
A tuple index is numeric , and 1st index in a tuple is [0]
Tuple Definition

Access Tuple Items

Tuple Length
It returns the length of a tuple (no. of items inside a tuple)

Add Items , Remove Items , Edit Items


No way to edit the tuple after it is being defined , can never add , remove , or modify items
The only action available is to delete the whole tuple object
Delete Tuple

Nested Tuples
An item inside a tuple may be another tuple , or even a list or dictionary
If a list is an item inside a tuple , you can modify it (add ,remove , edit items inside this list) , but you still
can’t delete this list as an item inside the tuple
2.5.3 Dictionaries
Dictionary format : { key1:val1 , key2:val2 , …. , key(n-1):val(n-1) }
Dictionaries are a group of items that’s unordered , indexed , can be modified (can add items , remove items , edit items)
A dictionary is defined by these brackets {}
Dictionary key may be either string or integer
Dictionary value may be string , int , or even a list or tuple or another dictionary
A dictionary can carry mix of data types
Items inside a dictionary are written in format of key:value , and the dictionary index is the key

Dictionary Definition
Can define it by using just empty brackets {}
Using dict() method

Note here that the we haven’t to write the keys between quotations

To access an item inside a dictionary , we he two methods:


Refer to its key
Use get() method

Modify an item inside the dictionary


Specify the key and change its value

Add new item to the dictionary


Just refer to a new key and assign it a value
Get a list by all dictionary keys using keys() method
It returns a list containing all dictionary keys
Its type is “dict_keys” and its items can’t be accessed by normal indexing
Simply , convert is to list by list() method and treat it as normal list

Remove items from the dictionary


We have two methods:

[Link]() method
Specify the key and the function will delete the item (key:value)
It returns the value
It type is according to the removed value

[Link]() method
It removes the last item in the dictionary
It returns a tuple containing the removed key & value
Delete Dictionary
using del keyword

Remove all dictionary items


Usinf clear() method

Copying dictionary --- the copy() method vs (=) symbol


To copy a dictionary to another one , DON’t use the (=) symbol , as this will just equalize the memory address , not the
dictionary [Link] , any modification in the original dictionary will automatically impact the copy one.
If you need to just copy the contents to another dictionary , use the copy() method

We will equalize “employee” by “employee2” :

Now,we will make change to “employee” , and observe what’s the impact on “employee2”:

To just copy the contents to another dictionary , use the copy() method:
2.6 If…else statement
Syntax
If condition1:
code
elif condition2:
code
elif condition3:
code
.
.
.
else:
code

If…else statement is used to match a condition or combination of conditions and then decide to take an action based on
the condition status
If the condition is TRUE , the code block inside the if clause will be executed
If the condition is FALSE , it will bypass the code inside if clause and continue executing the program
We can use the elif keyword to match on more than one condition with different actions
If there’s no match on any condition , you can end with the else keyword to define an action In case there’s no match

Examples:

EX#1

Explanation
-In the above example , we checked a condition  is a not equal b ?
-The condition result is TRUE
-So,execute the code inside the if clause
-The code is to print the sum of a & b ,, which is 30 as shown

Notes:
-The IF statement must be ended by(:)
-All the code block inside the if caluse must be indented by a white space , all the statements with the same white space
indentation level are considered in the same scope
-There’s no rule for how many space the indentation should be , it may be one space , two spaces , 10 spaces , but all the
code inside the same scope must have the same spaces.
Ex#2

Explanation
-In the above example , we checked a condition  is a equal 30 ?
-The condition is wrong as a =10 , so it willn’t execute the inside code and it will bypass it
-It will stuck by another condition check  is a equal 5 ?
- The condition is wrong as a =10 , so it willn’t execute the inside code and it will bypass it
-Finally , it will stuck by the else statement which will be executed as all the above conditions are false

Notes:
-When check equality of two operands , don’t use one equal symbol (=) as this will perform an assignment process , but
instead , use double equal symbol (==)

Ex#3

Explanation
-In the above example , we checked two conditions with logical and operator  is age greater than 20 AND age less than 60 ?
-Both conditions must be TRUE to execute the inside code , if one of them is false the whole result will be false and the inside
code will n’t be executed
-As the result here is TRUE , so the code will executed

Notes:
-Print() function will print any string parameter between the two brackets
-If there’s a variable between the brackets , it will be resoluted to its value and then printed
-We may need to print a constant string beside a value of a variable , to do that use the (+) symbol between the string and
the variable , and don’t put the variable between quotations as this will type the variable name
The above action is called Concatenation
-If the variable is string , so there’s no problem to concatenate the constant string to the variable and they will be displayed
normally
-But , if the variable holds a numeric value , it can’t be concatenated to a string , also you can’t concatenate two variables
one of them is a string and the other is numeric
-So,the solution is to convert the numeric value into string t be able to print it beside a string value
-To convert an integer to a string , use the str() method
Notice the below example…
x is integer , can do numeric operations on it

Now,we will convert it to string and assign it to new variable  y

2.7 Loops
We have two kind of loops in python:
-While Loop
-For Loop

2.7.1 While Loop

Syntax

While condition:
Code

While loop is working on a condition which may be TRUE or False


As long as this condition is TRUE , the inside code will be executed
Use While loop when you need to run some actions based on a condition , not based on a definite number of trials
The inside code must contain some statements that will terminate the loop , else , it will run to infinity
In While loop , we follow the same indentation concept as explained in the last section
Examples

Ex#1
Print numbers from 1 to 4

Explanation
In the above code , the while loop checks  is i less than 5 ?
As i has initial value =1 , so the condition is TRUE , so execute the inside code
The inside code will print the value of i , and then increment i by 1
The loop is repeated again , but now i has value of 2 , so the condition is still TRUE and the inside code is executed
when the value of i reach 5 , the condition result will be FALSE and the inside code not executed

Note:
If this statement not found (i += 1) , the loop will be executed infinite number of times as the condition is always TRUE

Ex#2 – loop through a list


Loop on a list and if you find ‘huwei’ change it to ‘srx’

Explanation
Given a list containing three items , we need to loop on each item and check its value , if it is ‘huawei’ so change it to ‘srx’
As list is numerically indexed , so we have to create a variable that will hold the list index , so we created a variable named i
Now,we’ll write a while loop,but we have to set a condition that will terminate the loop
The condition here is to check if the index is less that the list length , as this will indicate reaching the list end
Inside the while loop , there’s if statement that checks if the current value is equal to ‘huawei’
For each iteration , we refer to the current value by l[i],where i is the index and it’s incremented in each iteration

Note:
We must increment i so that each iteration we move to the next element in the list
We must initiate i with initial value , if loop is written without specifying an initial value to i , it will raise an error
Ex#3 - break keyword
Some times you’ll need to exit the loop when certain condition achieved , break will do that
Our target in the example to loop on the list and compare each item with the given input from user , if found then break and
exit from the whole loop , if not found then print the current item value

Explanation
To make the code more dynamic and interactive , we take an input from the user
The input() function will prompt a message to the user and store the user input in a variable (dev in our example)
Now,we write our while loop as last example , and check the items by if statement
If current value is equal to the value given by user , then the command break will be executed
If break executed , the while loop is terminated even if the condition still TRUE
To check it’s working properly , we write this statement print(l[i]) after the if statement inside the while loop , so , it should
print each item till the given value is found , it will stop printing as the loop is terminated
In the above example , we give an input ‘srx100’ , which is the fourth value in the list , so all the previous values are printed as
the loop is working (‘cisco’ , ‘juniper’ , ‘huawei’) , but once ‘srx100’ is found and break is executed , the next values not printed ,
which actually indicates that the while loop is no longer active

Ex#4 - continue
The break terminates the whole loop and go to the next commands after the while loop to be executed , continue will
terminate the current iteration only and continue the while loop normally

Explanation
When the value of i = 2 , all the next commands after the if statement willn’t be executed , so only (1,3,4,5) are printed
2.7.2 For Loop

For loops are most commonly used when we need to loop over a list , tuple , dictionary , or to run a certain code definite
number of times with varying parameters , not based on certain condition.

Ex#1 - looping over list using (in) keyword


Loop over the list and print its items

Explanation
The in keyword is commonly used with for loops to loop over list , tuple and dictionary
The above code will loop over the list .So , in each iteration , n will carry a value of list item , in sequence

Note:
It follows the same indentation rules as explained before
Looping over tuple is exactly the same as list , but looping through dictionary may have another ways , as shown below

Ex#2 - looping over a dictionary using in key word

Explanation
The items method of dictionary returns a list of pairs (key & value)
So , in each iteration , the k , v will carry the current key & value in the dictionary
Print(k , v) will print both values with one space apart

Notes:
If we loop on employee only (not [Link]() ) , it will by default on the dictionary keys
If we need to loop on the values only , we can loop over [Link]()
Ex#3 – Looping over a sequence

Explanation
The range() function is used to determine a sequence on which the For loop will run
it takes two parameters , the first one is the starting counter , and the second is the ending one but it’s n’t included
If starting parameter not specified , its default is (0)
By default , the counter step is (1) , we can change it using a third parameter to the range() function , see the below example
In each iteration , x will carry a value in the specified range
2.8 Files in Python
In this section , we’ll know how to handle files in python , how to create file , read from file , write to file

The open() function


It’s the master function for file handling
It takes two parameters , the first one is file name , the second one is a code that indicates how to deal with this file

Function Its meaning


Open(“filename” , “r”) Read the specified file
Open(“filename” , “a”) Add some text to this file , with keeping the existing data as it is , if file not found create it
Open(“filename” , “w”) Erase the existing data , and write the new data to the file , if file not found create it
Open(“filename” , “x) Crete file

Notes:
If the action not specified , the default is “r” , i.e read
The file name including its extension
The file name also should contain the path to this file , with reference to the folder containing the code file
If there’s no path specified , then the file existing in the same folder of the file containing this code

Examples

Ex#1 - read file using read() function

Explanation
Open a file using the open() function , and it must be assigned to an object , here we called it ‘f’
File name is “[Link]”
Since it’s written without path , so it should exist in the same directory of the code file
The action to do is read (determined by the ‘r’ mode)
The read() function will get all text in the file and print it
We must close the file after finishing operations on it using the close() method

Notes:
If file not exist , an error will be raised
The read() functions displays the text as one line , and note that new line is replaced by (\n)
By default , read function get the whole text in the file , if we need to get certain number of characters we can use the below
version :

read(number of characters)
Ex#2 - write to an existing file

Explanation
A file named ‘[Link]’ is opened and loaded in an object “f”
The action here is write , determined by the ‘w’ mode
As we mention before , the write mode will erase all text in the file and write the new specified text
The write() method is used to write to a file , and it returns the number of written characters to the file

Note:
If file not exist , it will create it and write to it

Ex#3 -readline() & readlines()

Explanation
readlines() method returns a list , where each item in the list is a line in the file , in sequence
readline() returns only one line to be fetched

Notes:
readline() will return the first line , and then the ‘ f’ object is pointing to the second line , if using readline() again it will return
the second line , and so on
After executing the readlines() method , now ‘f’ is empty as it fetches the whole file , to populate it again you must repeat this
command again :

f = open('[Link]' , 'r')

see the below example


2.9 Functions
What is a function ?
-Function is a code block that can be executed just by calling it

Why we use functions ?


-Function has great benefit , if you have a repeated action that’s done frequently with certain changes in values or parameters ,
you can build a function only one time and call it when you need , and you can pass for it the needed parameters

How many parameters can be passed to a function ?


-You can pass as many parameters as you need , and it isn’t a must they they all are of the same type

How to call the function ?


-By typing its name

How function returns its value ?


-We can make function just do some action , without returning any value such as (create file , write something to file , print some
text , …).In other functions , we may need to make the function return a value that’s need in the rest of the code , and we use the
return keyword to return the needed value

Syntax:

def function_name(param1 , param2 , param3 , … , paramn):


code

let’s see the below examples to illustrate the different cases for using functions

Ex#1 - our first function

Explanation
Function name is Hello()
It takes no parameters , so each time we called it , the output will be the same
By calling the function , it executes the inside code and print the specified text

Note:
It follows the indentation rule
Ex#2 - Passing parameters to function

Explanation
In the above example , the function is working on one parameter called name
So,when we call the function , we have to pass a value to the function , this value will be loaded in the parameter name
Once function is called , its inside code is executed with the passed value
The above function has no return value

Ex#3 - Passing a list to the function & return value

Explanation
The above function takes a list as a parameter
Then it loops on list items and add them and store their summation in a variable named x
The final line is to return the value of x
Call the function and receive its returned value in a variable called result

Note:
If you pass to the function anything rather than a numeric list it will raise an error.

Variables Scope
-By default , when we define variable in the code , it can’t be accessed from inside the [Link] if there are two variables
having the same name , one inside the function and one in the external code , actually they didn’t refer to the same memory
location.
-In the above example , we have a variable named c and assigned a value 10 , and in the function we also defined a variable
named c and it’s equal to the summation of the two passed parameters .So, c not equal c , in other words , c which is defined in
the body of the code is n’t the same as c that’s defined inside the function , both refer to different memory locations and have
different [Link] , after calling the function , c is still keeping its original value which is 10

-But , we can change this behavior , such that the variable inside a function can refer to the variable outside the function with the
same name , and any change happens to this variable inside the function will affect the outside variable , this can be achieved by
using the global keyword , let’s see the below example

-This example is exactly the same as the previous one , with just one difference , which is using the keyword global with the
variable c inside the function .By using this keyword , we inform the program that the variable named c inside the function refer
to the variable c outside the [Link],after calling the function , the value of c changed to 5 , which is the new value of c inside
the function after executing its inside code.

2.10 Classes & Objects


A class is simply the abstract & generic type of certain objects , for example , a “human” is a class , while “Ahmed” &
“Mohammed” are objects from the class “human” . A “car” is a class , while “toyota” & “Honda” are objects
A class is defined by two things: Attributes & Methods
Attributes are variables that carry this object properties , while Methods describe how this object [Link] are actually
functions , but in classes we named it Methods.
For example , a human class has some properties like (name , age , weight , skin color , …) , all these are attributes. Human
methods are (walk , eat , speak , …) these are functions , actions can be done by this class.
Object is an instance of a class , you can create objects as much as you can from any class , each object has its own attribute
values and methods

Let’s see the below example

Ex#1 - our first class


Explanation
-We defined a class named “car” with two attributes : color & model , and it has one method : mycar
-The self keyword refers to this current object
-As we see , the class itself doesn’t represent any specific instance , it is just a container

Now,we’ll create an object from the above class and interact with its attributes & methods

-car1 is an instance from the class car


-To access an attribute or a method inside a class , we use the (.) notation
-So , ,to access the attribute color to read/modify it , we use this format  [Link]
-To call a method inside the class , we’ll follow the same way  [Link]()
-Now , car1 is a real object and represents a specific instance with specific values for its attributes

Notes:
-In method definition , the first arguement must be the self object , then you can add any other arguments
-While calling the method , we pass only the extra arguments , as the self is passed by default

Class Constructors
-We can assign initial values for the object properties on its creation , this can be achieved using special function called ‘Class
Constructor” , and it has the following syntax:

def __init__(self, argue[1], argue[2], … , argue[n])

-The first argument for the constructor is always the self object
-The constructor is automatically called on object creation , even if you didn’t define it in the class body it will be called but do no
action

Ex#2 - Class Constructor

Explanation
We created a class called Router and defined its constructor which takes three arguments : self , type , version
The constructor will just populate the class properties : routerType & routerVersion
Class Method getSpecs will just print one phrase and will use the class properties , there’re no external arguements provided
On object creation , we passed two values for the constructor , which will replace (type & version) mentioned in constructor
definition
2.11 Modules
-A collection or a library of functions / classes gathered in one file , called module
-A module can be included in any other code file to use its functions & classes instead of repeating them in each code
-To include a module in our code , use the keyword import
-There are a well-known python modules as (time , netmiko , telnetlib , …) , and we can build our modules and include them in
our code , both are included by the same way

Ex#1 - our first Module

Explanation
-We save the below code in a file and named it [Link] , note that the module is a normal python file with extension .py

def employee(name , age , address):


print('Name: ' + name + '\n' + 'Age: ' + str(age) + '\n' + 'address: ' + address)

-Save this file in the same directory of your code file


-To use the entire function , include the module using the import keyword (without extension)
-You can now access the entire elements of the module using the (.) notation

Ex#2 - import specific elements from module

Explanation
-We can import specific parts from a module , not all the module , this can be done by using the following syntax:

From module_name import elem[1] , elem[2] , elem[3] , …. elem[n]

-Whenever , you can call the included part directly without specifying the modulename before it

2.12 PiP
-PiP is a python package that enables you to download & install new python modules
-Run the PiP from your cmd , and you must run it from its directory , as following :

-To list the installed packages:


[Link] Programming
-Python is equipped by many libraries that can interact with different network devices with different methods like (Telnet , SSH ,
Console,..)
-You’ll just need to know what are the functions supported by each library , what each function do , how it returns the output
-After that , all the work will be by the basics in the last section , you may need to parse some output to extract a certain value ,
you may need to save a certain output in file , you may need to apply some configuration lines , you may need to access excel
sheet and loop on it and compose a configuration blocks and push it to a router , and so on.

3.1 Telnet library (telnetlib)


telnetlib is the library used to connect network devices using telnet session
It contains a class called Telnet() and all our work will be with this class , the below example will illustrate how to use this class

Ex#1 - using telnetlib to connect and write to telnet session

Explanation
import telnetlib  we must import the library in our code file to be able to use its entire classes and functions

conn = [Link]('[Link]')  We created an object called “conn” from the class Telnet() , and we passed to it the IP
address which we need to telnet it , and note that it must be included between two [Link], conn is the session holder ,
so if we need to read from the session or write to the session we’ll use the conn object.
-If the host is unreachable , it will raise error
-Till this point , it’s just as if you opened any terminal on your pc and type (telnet [Link]) , a telnet session is opened but
there’s no any extra info sent to this session , now it should ask you for username & password , so you have to provide it by the
needed info , remember that it’s a normal telnet session , imagine yourself instead of the program.

[Link](b'admin' + b'\n')  Use the write() method to send any text to the telnet session , this is exactly as if you write
anything to the opened session on your [Link] write() method takes its parameter in the format of bytes not string , so we
have to convert our string to bytes by using the b character before your [Link] , the above command should send a string
‘admin’ and then it will transfer to the next line (just as if you hit enter on the keyboard to get the next prompt) by using the new
line ‘\n’
[Link](b'Admin@huawei' + b'\n')  Nothing different than the above , just here we sent the expected password
‘Admin@huawei’ , and don’t forget the b character , and don’t forget the new line ‘\n’

[Link](b'system-view' + b'\n')  enter the configuration mode

[Link](b'int gi0/0/3' + b'\n')  access the interface configuration

[Link](b'ip address [Link] 24' + b'\n')  send a configuration command to add ip address

-By the above steps , we opened a telnet session to the specified host , send username , send password , enter the configuration
mode , access the interface , send configuration [Link] the same logic , you can do anything , shut/no shut interface , add
vlans , apply any kind of configuration. But , what if we need to get read the output of certain command to take a decision , or to
parse it and search it for certain value and extract it if found , this can be achieved using the read_until() function , let’s see the
below example.
Ex#2 - read output from the session

Explanation
-The read_until() method returns the output shown on your console till the specified string by you as a parameter to the
read_until() method.
-The returned output is in bytes format , so you have to convert it to string using the str() function
-The \r\n characters represent the new line

Ex#3 - send ping command and get the output

3.2 SSH (Netmiko)


Netmiko is library used to connect to network devices by SSH
In netmiko , we have to define the host that we need to connect to it as following:

aterm = { "host": "[Link]",


"username": '[Link]',
"password": '!$Pshift123',
"device_type": "linux",
"port": "9090"
}

“host”  the ip address of the host we need to connect to it , it can be written as a domain name
“username”  the username used to access this host
“password”  the password used to access this host
“device_type”  the device_type informs Netmiko how to deal with this host , there are a well-known list for the device_type ,
includes {‘cisco_ios’ , ‘linux’ , ‘juniper’ , ‘cisco_xr’ , ‘cisco_asa’} .
“port”  if we don’t use the ssh defult port , so we have to define the new port

 Now , aterm is defined by the above parameters , but still no connection established , to establish ssh connection to the host
called aterm , use the following command:

net_connect = ConnectHandler(**aterm)
 Now , net_connect is our netmiko object that holds the established session , and we can use it to interact with the remote
device using the following most common methods:

 net_connect.send_command(command) will send a command to the device over the ssh connection , only one
command can be sent between the [Link] function will send the command and wait till the default prompt
appears again , this default prompt is defined according to the device_type .If no prompt returned , it will raise an
exception and program will stop.
 net_connect.send_command_expect(command , expect_string = ‘ ‘ )  it is the same as the above one
, but we can here assign the expected string

-The above methods return the output of the executed command on the device as a string , let’s see the below
examples to know how to use netmiko

Ex#1 – connect to aterm and access MSAN

Explanation
Define a host named “aterm” and assign it the needed parameters , noting that we use a device_type = ‘linux’
Connect to the host “aterm” , net_connect is the object holding the session
Now , we are on the aterm server (assume that you see this view now : [[Link]@host-213 ~]$
send the commands normally using the send_command_expect() method , the first parameter for the method is the command
itself which we need to send it , and note the ‘\n’ character to simulate “hit enter” .The second parameter is the expect string ,
you should type the expected prompt returned after executing this command , if the prompt you type not found , the program
will stop.
We receive the returned output in a variable called output

-The output of the above code will be as following:


Ex#2 – show interface configuration on PE and get the output

Ex#3 – get ip address on certain interface


-First , try to get output that can be easily parsed

-Second , our target now is to get this value ‘[Link]’ , so we’ll build our logic as following:
>split the output into separate lines , sothat we have a list of lines , as below:
['BLOUK-R30J-C-EG', 'set interfaces et-1/3/0 unit 1120 description "Main(VPN)EKB MOE:HQ"', 'set interfaces et-1/3/0
unit 1120 vlan-id 1120', 'set interfaces et-1/3/0 unit 1120 family inet address [Link]/30', '', '{master}',
'[Link]@BABLOUK-R30J-C-EG> ']

>search in the above list for the line that contains the word “address” , now we catch this line:
'set interfaces et-1/3/0 unit 1120 family inet address [Link]/30'

>split this line into words based on the ‘white space’ , now we have a list of words of this last command:
['set’,’interfaces’,’et-1/3/0’,’unit’,’1120’,’family’,’inet’,’address’,’[Link]/30']

>the last value in the above list is the ip/mask , we refer to this value by its index which is the list length-1 , so we have
this value now  [Link]/30

>split this value based on the ‘/’ character , so we have this list  [‘[Link]’,’30’]

>the needed value is the first one in the above list , which has index [0]  [Link]

You might also like