You are on page 1of 44

PYTHON FOR

NETWORK ENGINEERS

PRESENTED BY
TOLGA KOCA
TRAINER:
TOLGA KOCA
Network Engineer
- Huawei (7 years)
- Customer Support for Turkcell (5 years)

- İşNet (1 Month)

- Python experience (1 year)


WHAT WILL YOU LEARN IN THIS WEBINAR?

1- Python Basics
2- Connect Network Devices
3- Log Management
CONTENT

● Python Introduction
● Data Types (String, List, Dictionary)
● Conditions (If, For)
● File Handling
● Re Module
● Device Connections
● Log Management
PYTHON BASICS
Presented content overview
Why Python?

Open Source
Interpreted

Object-oriented
Easy Syntax
High-level

Good Community
Dynamic Semantics

Platform Independent
Why we need Python For Network Engineering?

- Reduce human mistakes


- Faster operations and troubleshooting
- Create own automation tool for specific expectation
- Better log management
Python - Data Types

Text Type: string (str)


Numeric Types: integer (int), float, complex
Sequence Types: list, tuple, range
Mapping Type: dictionary

Set Types: set, frozenset


Boolean Type: bool

Binary Types:bytes, bytearray, memoryview


Data Types – String & Integer

my_string = "1-Hello World"


my_string = '2-Hello World'
my_string = '''3-Hello my_string = 23 #Interger
World
!!! '''
my_string = "23" #String
Data Types – Lists

- Lists are the sequence of arbitrary objects.


- Lists are ordered and changeable
- It allows duplicate members.
- Created with items inside [ ]

devices = ["Router", "Switch", "Firewall"]


print (devices[0]) output: Router
print (devices[1]) output: Switch
print (devices[2]) output: Firewall
Data Types – Dictionary

my_dictionary = { “router" : “NE40E", “switch" : “S9300", “Quantity" : 5 }

Unordered Changeable Indexed


Written with {}
Keys and Values
Each key seperated with “:” and the items are separated by commas
Keys are unique, values can be same
Values can be anytype, keys must be immutable data type
Python – If Statements

IF condition :
Do this

a = 33
b = 200
if b > a:
print("b is greater than a")
Python – If Statements

IF condition : a = 200
Do this b = 33
ELIF condition : if b > a:
Do this print("b is greater than a")
ELIF condition : elif a == b:
Do this print("a and b are equal")
... else:
ELSE : print("a is greater than b")
Do this
Python – For Loop Statements

FOR variable IN iterable :


statements(s)

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

Output: apple
banana
cherry
Python – For Loop Statements

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]


sum = 0 # variable to store the sum
for val in numbers: # iterate over the list
sum = sum+val

print("The sum is", sum)

Output: The sum is 48


Python - RE Module

Findall () Returns a list containing all matches


Search () Searches the string for a match
Split () Split the string at every white-space character
Sub () Replaces the matches with the text of your choice
Span () Returns a tuple containing the start and end positions of the match
String () Returns the string passed into the function
Group () Returns the part of the string where there was a match
RE Module – Findall ()

import re
re.findall ( Find the characters , string_name )

import re
my_string = "He finally went to the school at the end of
the year."
x = re.findall ( "he" , my_string )
print(x) Output: ['he', 'he', 'he']
RE Module – Split ()
import re
re.split ( Find the characters , string_name , (optional) Number of times )

import re import re
my_string= "The rain in Spain" my_string= "The rain in Spain"
x = re.split( "i", my_string) x = re.split ( "i", my_string, 2 )
print(x) print(x)

Output: ['The ra', 'n ', 'n Spa', 'n'] Output: ['The ra', 'n ', 'n Spain']
RE Module - Special Sequences
\A Returns a match if the specified characters are at the beginning of the string

\b Returns a match where the specified characters are at the beginning or at the end of a word

\B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a
word

\d Returns a match where the string contains digits (numbers from 0-9)

\D Returns a match where the string DOES NOT contain digits

\s Returns a match where the string contains a whitespace character

\S Returns a match where the string DOES NOT contain a white space character

\w Returns a match where the string contains any word characters ( character from a to Z, from 0-9, and the
underscore _ )

\W Returns a match where the string DOES NOT contain any word characters

\Z Returns a match if the specified characters are at the end of the string
RE Module - Special Sequences

import re import re
str = "+44 (231) 231 12" my_string = "I’m learning python"
x = re.findall("\d", str) x = re.findall("\w", my_string)
print(x) print(x)

Output: ['4', '4', '2', '3', '1', '2', '3', '1', '1', Output: ['I', 'm', 'l', 'e', 'a', 'r', 'n', 'i', 'n', 'g',
'2'] 'p', 'y', 't', 'h', 'o', 'n']
RE Module - Special Sequences

import re x = re.findall("E\w+", my_string)


my_string = "Clint Eastwood1930 print(x)
USA"
x = re.findall("E\w", my_string) Ouput: ['Eastwood1930']
print(x)

Output: ['Ea']

x = re.findall("E\D+", my_string)
print(x)

Output: ['Eastwood']
PYTHON IN NETWORK
Ping Test
import subprocess
reached = []
not_reached = []
hosts = ["192.168.1.1","123.214.2.2","www.google.com"]
for ip in hosts:
ping_test = subprocess.call('ping %s -n 2' % ip)
if ping_test == 0:
reached.append(ip)
else:
not_reached.append(ip)
print("{} is reachable".format(reached))
print("{} not reachable".format(not_reached))
Paramiko - Collect Logs From Multiple Devices

import paramiko
import time
c = open("Command_List.txt", "r")
command_list = c.read().split("\n")
d = open("Device_List.txt", "r")
hosts = d.read().split("\n")
port = 22
username = "root"
password = "Test1234."
logs = []
logs1= []
Paramiko - Collect Logs From Multiple Devices

for ip in hosts:
print("Try to login:", ip)
conn = paramiko.SSHClient()
conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn.connect(ip, port, username, password)
comm = conn.invoke_shell()

for command in command_list:


comm.send(' %s \n' %command)
time.sleep(.5)
output = comm.recv(65535)
output = output.decode("utf-8")
Paramiko - Collect Logs From Multiple Devices

logs = output.split("xxxxx")
print("logs",logs)
logs1.extend(logs)
logs1 = ''.join(map(str, logs1))
with open("{}.txt".format(ip), "w") as f:

f.write(logs1)
logs1 = []
Netmiko- Collect Logs From One Device

from netmiko import Netmiko


import logging
logging.basicConfig(filename="test.log", level=logging.DEBUG)

logger = logging.getLogger("netmiko")
host = {
"host": "129.9.0.101",
"username": "root",
"password": "Test1234.",
"device_type": "huawei",
"global_delay_factor": 0.1,
}
Netmiko- Collect Logs From One Device

net_connect = Netmiko(**host)
print("Connected to:", net_connect.find_prompt())
output = net_connect.send_config_set(command, delay_factor=.5)
net_connect.disconnect()
print(output)
LOG MANAGEMENT
Configuration Change in File

with open("config.txt") as old_config:


x = old_config.read()

x = x.replace("user-interface con 0\n authentication-mode password", " user-interface con 0\n authentication-
mode aaa")
x = x.replace("interface GigabitEthernet0/0/0", " interface GigabitEthernet0/0/0\nip address 1.1.1.1 24")

with open("2.txt","w") as new_config:


new_config.write(x)
Collect Device Name and Version
Collect Device Name and Version
import re
switch_name = []
device_model = []
soft_version = []
with open("R1.txt") as switches:
x = switches.read()
names = re.findall("\[(.*)\]",x) # (.*) Any character, \[ => [ as a character
switch_name.append(names[0])
print(switch_name)

model = re.findall("Version 5.130 \((\w+)",x)


device_model.append(model[0])
print(device_model)

version = re.findall("(V\w+)\)",x)
soft_version.append(version[0])
print(soft_version)
Collect Device Name and Version
import re
from pandas import DataFrame
switch_name = []
device_model = []
soft_version = []
hosts = ["R1.txt","R2.txt","R3.txt","R4.txt"]
for i in hosts:
with open(i) as switches: #Open text file as switches
x = switches.read()
names = re.findall("\[(.*)\]",x)
switch_name.append(names[0])
model = re.findall("Version 5.130 \((\w+)",x)
device_model.append(model[0])
version = re.findall("(V\w+)\)", x)
soft_version.append(version[0])
print(switch_name)
print(device_model)
print(soft_version)
Collect Device Name and Version
df = DataFrame({'Device Name' : switch_name, 'Device Model' : device_model,
'Software Version': soft_version})
print(df)
df.to_excel("result.xlsx")
Precheck & Postcheck Compare
for i in range(6):
if precheck[i] == postcheck[i]:
result.append("OK")
else:
result.append("NOK")
Udemy – Ansible Training
Thank you

Tolga Koca
koca.tolga@gmail.com
HUAWEI ENTERPRISE SUPPORT COMMUNITY

• Technical community for all Huawei Enterprise products and certifications


• Over 172.000 members, including engineers, experts, customers, partners and students
• Extensive knowledge base with over 44.000 posts to learn from
• Average solving time for technical issues is under 24 hours
• Public recognition and rewards for the most active members (MVE Program, HiCoins, Rewards)
• Monthly activities and webinars
Visit our Community for a chance to win!
Go to the webinar post on the Huawei Enterprise Community to answer the following 3
questions and get a chance to win a $20 Amazon.com gift card! Make sure to register or log in
first and then leave your comment under this post:
https://forum.huawei.com/enterprise/en/webinar-on-python-for-network-engineers-phase-10/thread/
638865-861
QUESTION 1.

Which one of the below variable is a LIST?

a) x= ("router", "switch", "firewall")


b) x= {"router": "NE40E", "switch": "S9300", "firewall": "Eudemon"}
c) x= ["router", "switch", "firewall"]
d) x= {"router", "switch", "firewall"}
QUESTION 2.
You have a variable x as string. There are 5 underline between words.
Need to change it with whitespace.
x = "Python_is_a_good_scripting_language"
….. # The code you must write
print (x) # Output: Python is a good scripting language,

a) x= x.replace ("_","")
b) x= x.replace ("_"," ")
c) x= x.split ("_"," ")
d) x= x.add ("_"," ")
QUESTION 3.

Find the digits as number and write as list for x string.


import re
x="Manchester United founded in 1878"
….. # The code you must write
print(x) # Output: ['1878‘]

a) x = re.search ("\d+", x)
b) x = re.findall ("\d", x)
c) x = re.findall ("\d+", x)
d) x = re.findall ("\D", x)

You might also like