0% found this document useful (0 votes)
17 views32 pages

Network Programmability and Automation

The document discusses network programmability and automation, highlighting the inefficiencies of conventional network operations and the need for automation tools. It emphasizes the importance of Python as a programming language for network automation, detailing its advantages, execution process, and coding guidelines. The document also covers the structure of Python source code and the use of functions and modules to enhance code reusability.

Uploaded by

toufik
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)
17 views32 pages

Network Programmability and Automation

The document discusses network programmability and automation, highlighting the inefficiencies of conventional network operations and the need for automation tools. It emphasizes the importance of Python as a programming language for network automation, detailing its advantages, execution process, and coding guidelines. The document also covers the structure of Python source code and the use of functions and modules to enhance code reusability.

Uploaded by

toufik
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/ 32

Network Programmability and Automation

Contents

1 Introduction to Network Programmability and Automation


• Introduction to Network Programmability and Automation

2 Overview of Programming Language and Python

3 Cases

Page 1 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Background: Difficulties in Conventional Network O&M
⚫ Conventional network O&M requires network engineers to manually log in to network devices, query and execute
configuration commands, and filter command output. This highly human-dependent working mode is time-
consuming, inefficient, and difficult to audit.

Numerous devices Typical O&M Scenarios


Complex operations
Low efficiency Are the following working scenes familiar to you?
1. Device upgrade: Thousands of network devices reside on a live network.
You have to periodically upgrade the devices in batches.
2. Configuration audit: An enterprise needs to audit the configuration of
devices every year. For example, the enterprise requires that STelnet be
enabled on all devices and spanning tree security be configured on
Ethernet switches. In this case, you have to quickly find out the devices
that do not meet the requirements.
3. Configuration change: Due to network security requirements, device
accounts and passwords need to be changed every three months. You
have to delete the original account and create an account on thousands
Network device of network devices.

Page 2 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Network Automation
⚫ Network automation: Tools are used to implement automated network deployment, operations, and O&M,
gradually reducing dependency on human. This solves the conventional network O&M problems.

⚫ Many open-source tools, such as Ansible, SaltStack, Puppet, and Chef, are available for network automation in the
industry. From the perspective of network engineering capability construction, it is recommended that engineers
acquire the code programming capability.

Keywords of network
Chef automation SaltStack

NMS
tool
Ansible Python Automated
scripts
Shell

Page 3 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Programming-based Network Automation
⚫ In recent years, with the emergence of network automation technologies, Python-based programming capabilities
have become a new skill requirement for network engineers.
⚫ Automation script written in Python can execute repeated, time-consuming, and rule-based operations.
Example: Implementing automated device configuration
Python file
using Python
Configuration File • What can network automation do? The most intuitive
example of network automation is automated device
Sysname SW1 SSH/Telnet configuration. This process can be divided into two steps:
Vlan 10
description A writing a configuration file, and writing Python code to push
Vlan20 the configuration file to a device.
description B Network • Write the configuration script in command line interface (CLI)
VLAN 30 device mode, and then upload the script to the device using
description C
Telnet/SSH. This method is easy to understand for network
engineers who are beginning to learn network
programmability and automation. This presentation describes
how to implement network automation.

Page 4 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Contents

1 Introduction to Network Programmability and Automation

2 Overview of Programming Language and Python


• Overview of Programming Language and Python

3 Cases

Page 5 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Programming Languages
⚫ A programming language is used to write a computer program and control behavior of a computer.
⚫ According to whether compilation is required before execution of a language, the programming language may be
classified into the compiled language, and interpreted language that does not need to be compiled.

Compiled language Interpreted language


(Source code) (Source code)

Compiler
Interpreter: Interprets
source code line by
line.
Executable file

Operating system (Windows/Linux/Mac OS)

CPU (x86/ARM architecture)

Page 6 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Computing Technology Stack and Program Execution Process
Computing Technology Stack Program Execution Process

Application
temp = v [k]; TEMP = V[K]
Algorithm High-level v[k] = v[k+1]; V[K] = V[K+1]
Increasing order of Complexity

programming
Increasing order of Abstraction

v[k+1] = temp; V[K+1] = TEMP

Software
High-Level Language language C/C++ Fortran
compiler compiler
Assembly Language
lw $t0, 0($2)
lw $t1, 4($2)
Machine Code Assembly sw $t1, 0($2)
language sw $t0, 4($2)
Instruction Set Architecture
Assembler
Micro Architecture

Hardware
0000 1001 1100 0110 1010 1111 0101 1000
1010 1111 0101 1000 0000 1001 1100 0110
Gates/Registers Machine 1100 0110 1010 1111 0101 1000 0000 1001
code 0101 1000 0000 1001 1100 0110 1010 1111
Transistors
Instruction
Physics Instruction 1 Data 1
set
Page 7 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
High-level Programming Language - Compiled Language
⚫ Compiled language: Before a program in a compiled language is executed, a compilation process is performed to
compile the program into a machine language file. The compilation result can be directly used without re-
translation during running. Typical compiled languages include C/C++ and Go.
⚫ From source code to program: The source code needs to be translated into machine instructions by the compiler
and assembler, and then the linker uses the link library function to generate the machine language program. The
machine language must match the instruction set of the CPU, which is loaded to the memory by the loader during
running and executed by the CPU.

Assembly Object module: Executable code:


C/C++ source
Compiler language Assembler machine Linker machine language Loader Memory
code
program language module program

Target library: library


function (machine
language)

Page 8 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
High-level Programming Language - Interpreted Language
⚫ Interpreted language: Interpreted language programs do not need to be compiled before running. They are
translated line by line when running. Typically, Java and Python are interpreted languages.

⚫ Process from source code to programs: Source code of an interpreted language is generated by the compiler and
then interpreted and executed by a virtual machine (VM) (for example, JVM/PVM). The VM shields the differences
between CPU instruction sets. Therefore, portability of the interpreted language is relatively good.
Java language
Python program
program

Compiler Compiler

Class file Java library function Python library


.pyc file
(byte code) (machine language) functions (machine
(byte code)
language)

JVM PVM

Page 9 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
What Is Python?
⚫ Python is a fully-open-source high-level programming language. Its author is Guido Van Rossum.

Advantages of Python: Disadvantages of Python:


• Is a dynamically typed interpreted language with elegant • Runs slow. Is an interpreted language
syntax. It allows learners to focus on program logic rather than that runs without being compiled. Code
syntax detail learning. is translated line by line at run time
• Supports both process- and object-oriented programming. into machine code that the CPU can
• Provides abundant third-party libraries. understand, which is time-consuming.
• Is nicknamed the glue language because it can call code written
in other languages.

With support for abundant third-party libraries and advantages of the Python language, Python can be
used in many fields, such as AI, data science, apps, and scripts for automated O&M.

Page 10 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Python Code Execution Process
Process of compiling and
running a Python program Operation

Python source code 1. Install Python and the running environment in


an operating system.

2. Compile Python source code.


Compiler
3. The compiler runs the Python source code and
generates a .pyc file (byte code).
.pyc file (byte code)
4. A Python VM converts the byte code into the
machine language.
Running of the Python
VM 5. Hardware executes the machine language.

Page 11 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Getting Started with Python Code - Interactive Running
⚫ Python runs in either interactive or script mode.
⚫ Interactive programming does not require script files to be created, and code is written in the
interactive mode of the Python interpreter.

C:\Users\Richard>python
Python 3.7.4 (default, Aug 9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] ::
Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
1. Input -- >>> print ("hello world")
2. Output -- hello world
3. Input -- >>> a = 1
4. Input -- >>> b = 2
5. Input -- >>> print ( a + b )
6. Output -- 3
>>>

Page 12 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Getting Started with Python Code - Script-based Running
⚫ Code in script mode can run on various Python compilers or in integrated development environments.
For example, IDLE, Atom, Visual Studio, Pycharm, and Anaconda provided by Python can be used.

demo.py

print ("hello world") 1. Input -- C:\Users\Richard>python demo.py


a=1 2. Output -- hello world
b=2 3. Output -- 3
print ( a + b )

1 Write a Python script file (.py). 2 Execute the script file.

Page 13 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Code Style Guide for Python
⚫ Code style rules refer to naming rules, code indentation, and code and statement segmentation modes that must be
complied with when Python is used to write code. Good style rules help improve code readability and facilitate code
maintenance and modification.
⚫ For example, the following rules for using semicolons, parentheses, blank lines, and spaces are recommended:

Semicolon Blank line


• A semicolon can be added at the end of a line in • Different functions or statement blocks can be
Python, but is not recommended to separate separated by spaces. A blank line helps differentiate
statements. two segments of code, improving code readability.
• It is recommended that each sentence be in a
separate line.

Parentheses Space
• Parentheses can be used for the continuation of • Spaces are not recommended in parentheses.
long statements. Avoid unnecessary parentheses. • You can determine whether to add spaces on both
ends of an operator.

Page 14 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Code Style Guide for Python - Identifier Naming
• A Python identifier represents the name of a constant, variable, function, or another object.

• An identifier is usually composed of letters, digits, and underscores, but cannot start with a digit. Identifiers are case
sensitive and must be unique. If an identifier does not comply with the rules, the compiler will output a SyntaxError
message when running the code.

1. Assign a value -- User_ID = 10 print ( User_ID )


2. Assign a value -- user_id = 20 print ( user_id )
3. Assign a string -- User_Name = ‘Richard’ print ( User_Name )
4. Assign a value -- Count = 1 + 1 print ( Count )
5. Incorrect identifier -- 4_passwd = "Huawei" print ( 4_passwd )

print() is a built-in function of Python and is used to output content in parentheses.

Question: What is the output of the print command on the right?

Page 15 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Code Style Guide for Python - Code Indentation
⚫ In Python programs, code indentation represents the scope of a code block. If a code block contains
two or more statements, the statements must have the same indentation. For Python, code indentation
is a syntax rule that uses code indentation and colons to distinguish between layers of code.
⚫ When writing code, you are advised to use four spaces for indentation. If incorrect indentation is used
in the program code, an IndentationError error message is displayed during code running.

if True:
Correct indentation -- print ("Hello")
else:
Correct indentation -- print (0)

a = “Python”
Incorrect indentation -- print (a)

Page 16 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Code Style Guide for Python - Using Comments
⚫ Comments are explanations added to programs to improve program readability. In the Python program,
comments are classified into single-line comments and multi-line comments.
⚫ A single-line comment starts with a pound sign (#).
⚫ A multi-line comment can contain multiple lines, which are enclosed in a pair of three quotation marks
('''...''' or '''''' ...'''''').
Single-line comment -- # Assign a string to a.
a = “Python”
print (a)

“””
Multi-line comment -- The output is Python.
“””

Page 17 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Code Style Guide for Python - Source Code File Structure
⚫ A complete Python source code file generally consists of interpreter and encoding format declaration,
document string, module import, and running code.
⚫ If you need to call a class of a standard library or a third-party library in a program, use "import" or
"from... import" statement to import related modules. The import statement is always after the module
comment or document string (docstring) at the top of the file.
Interpreter declaration -- #!/usr/bin/env python
Encoding format declaration -- #-*- coding:utf-8 -*-

Module comment or document string -- Description of a document (docstring)

This document is intended for...


“””

Time when a module is imported -- import time


Code is running -- …
Page 18 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Python Functions and Modules
⚫ A function is a block of organized, reusable code that is used to perform a single, related action. It can improve the
modularity of the program and code utilization. The function is defined using the def keyword.

⚫ A module is a saved Python file. Modules can contain definitions of functions, classes, and variables that can then
be utilized in other Python programs. The only difference between a module and a regular Python program is that
the module is used for importing by other programs. Therefore, a module usually does not have a main function.

demo.py test.py
def sit(): #Define a function. import demo #Import a module.
print ('A dog is now sitting’)
demo.sit() #Call a function.
sit() #Call a function.
Execution result:
Execution result:
A dog is now sitting.
A dog is now sitting. A dog is now sitting.

1 Write a Python file (.py). 2 Import a module.


Page 19 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Python Classes and Methods
⚫ A class is a collection of properties and methods that are the same. The class keyword is used to define
a class.
⚫ The function of an instantiated class is called a method. When you define a method, a class must carry
the self keyword, which indicates the instance of the class.
demo.py

class Dog(): #Define a class. test.py


def sit(self): #Define a method.
print(“A dog is now sitting.") import demo

Richard = Dog() #The class is instantiated. demo.Dog.sit


print (type(Richard.sit)) #The function of an instantiated type is
called a method.
print (type(Dog.sit)) #The type is function.
Execution result:

Execution result: A dog is now sitting.


<class 'method'>
<class 'method'> <class 'function'>
<class 'function'>

1 Write a Python file (.py). 2 Import a module.


Page 20 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Introduction to telnetlib
⚫ telnetlib is a module in the standard Python library. It provides the telnetlib.Telnet class for implementing the Telnet
function.

⚫ Different methods in the telnetlib.Telnet class are called to implement different functions.
Import the Telnet class of the telnetlib module. -- from telnetlib import Telnet
Create a Telnet connection to a specified server. -- tn = Telnet(host=None, port=0[, timeout])
Invoke the read_all() method. -- tn.read_all()

Method Function
Read data until a given byte string, expected, is encountered or until timeout seconds have
Telnet.read_until (expected, timeout=None)
passed.
Telnet.read_all () Read all data until EOF as bytes; block until connection closed.
Read everything that can be without blocking in I/O (eager). Raise EOFError if connection
Telnet.read_very_eager() closed and no cooked data available. Return b'' if no cooked data available otherwise. Do not
block unless in the midst of an IAC sequence.

Telnet.write(buffer) Write a byte string to the socket, doubling any IAC characters.

Telnet.close() Close the connection.

Page 21 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Contents

1 Introduction to Network Programmability and Automation

2 Overview of Programming Language and Python

3 Cases
• Cases

Page 22 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Case: Logging In to a Device Using telnetlib
⚫ Case description :
⚫ A network device functions as a Telnet server, and the Python telnetlib needs to be used as a Telnet client to log in
to the device. Verify the Telnet login Verify the
Configure Telnet. Write Python code.
procedure. result.

192.168.10.10 192.168.10.20

GE1/0/10
Telnet server Telnet client

⚫ The implementation process is as follows :


⚫ Configure the Telnet service.
⚫ Manually verify and view the Telnet login procedure as a reference for code implementation.

⚫ Compile and run Python code.


⚫ Verify the result.

Page 23 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Case: Logging In to a Device Using telnetlib
Configure Telnet. Verify the Telnet login Verify the
Write Python code.
procedure. result.

192.168.10.10 192.168.10.20

GE1/0/10
Telnet server Telnet client

Configure the IP address of Configure the Telnet service:


interface on the device:

[Huawei] interface GE 1/0/0 [Huawei] user-interface vty 0 4


[Huawei -GE1/0/0] ip add 192.168.10.10 24 [Huawei-ui-vty0-4] authentication-mode password
[Huawei -GE1/0/0] quit [Huawei-ui-vty0-4] set authentication password simple Huawei@123
[Huawei-ui-vty0-4] protocol inbound telnet
[Huawei-ui-vty0-4] user privilege level 15
[Huawei-ui-vty0-4] quit
[Huawei] telnet server enable

Page 24 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Case: Logging In to a Device Using telnetlib
Configure Telnet. Verify the Telnet login procedure. Write Python code. Verify the result.

192.168.10.10 192.168.10.20

GE1/0/10
Telnet server Telnet client

Telnet login:

1 Run a login C:\Users\Richard>telnet 192.168.10.10


command.
Command output Login authentication

2 Enter a password. Password:


Command output
Info: The max number of VTY users is 5, and the number of current VTY users on line is 1.
The current login time is 2020-01-15 21:12:57.
<Huawei>

Page 25 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Case: Logging In to a Device Using telnetlib
Verify the Telnet login
Configure Telnet. Write Python code. Verify the result.
procedure.

192.168.10.10 192.168.10.20

GE1/0/10
Telnet server Telnet client

Imports the module. -- import telnetlib


Sets the IP address for a host. -- host = '192.168.10.10'
Sets the password for logging in to the device. -- password = 'Huawei@123'

Logs in to the host through Telnet. -- tn = telnetlib.Telnet(host)


Prints data until Password: is displayed. -- tn.read_until(b'Password:')
Sets an ASCII password and starts a new line. -- tn.write(password.encode('ascii') + b"\n")
Prints data until <Huawei> is displayed. -- print (tn.read_until(b'<Huawei>').decode('ascii’))
Closes the Telnet connection. -- tn.close()
Page 26 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Case: Running Result Comparison
Verify the Telnet login
Configure Telnet. Write Python code. Verify the result.
procedure.

C:\Users\Richard>telnet 192.168.10.10
Login authentication
Manual Telnet login
result: Password:
Info: The max number of VTY users is 5, and the number of current VTY users on line is 1.
The current login time is 2020-01-15 21:12:57.
<Huawei>

#Run Python code in the compiler.


Python code execution Info: The max number of VTY users is 5, and the number
result: of current VTY users on line is 1.
The current login time is 2020-01-15 22:12:57.
<Huawei>

Page 27 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Quiz
1. Python is a compiled language. ( )
A. True

B. False

2. How to create VLAN 10 using telnetlib?

Page 28 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Summary
⚫ Network automation uses tools to implement automated network deployment, operation,
and O&M, gradually reducing dependency on people. You can use a programming language
or tool to implement the network automation.

⚫ Python is a fully-open-source high-level programming language that is simple syntax and is


easy to learn. It has rich standard libraries and third-party libraries, which are applicable to
the network engineering field.

⚫ The telnetlib module of Python provides the telnetlib.Telnet class for implementing the
Telnet function. It helps you enter the network programmability and automation world!

Page 29 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
More Information
⚫ For more information about Python, visit https://www.python.org/.

Page 30 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.
Thank You
www.huawei.com

Page 31 Copyright © 2020 Huawei Technologies Co., Ltd. All rights reserved.

You might also like