18.1 Introduction To Network Programming and Automation
18.1 Introduction To Network Programming and Automation
The following are some classic network operation and maintenance scenarios that
you may have encountered in your work.
1. Device upgrade: there are thousands of network devices in the network, and you
need to upgrade the devices in a regular basis and in bulk.
2. Configuration audits: enterprises need to conduct configuration audits on devices,
for example, requiring all devices to be enabled with STelnet function and all
Ethernet switches to be configured with Spanning Tree security. You need to
quickly identify devices that do not meet the requirements.
3. Configuration changes: because of the network security requirements, the
accounts and passwords of devices need to be changed every 3 months. You
need to delete the original accounts and create new ones on thousands of network
devices.
Fig. 18.1 Write a Python script to pass the configuration to the device for automated configuration
link library functions of the linker. The machine language program has to match
the instruction set of the CPU, and is loaded into memory by the loader when it is
run. Then the CPU executes the instructions. The source code of a compiled
language is compiled and converted into a format that the computer can execute,
such as .exe, .dll, and .ocx.
2. Interpreted languages
Interpreted languages do not require prior compilation, and the source code is
directly interpreted into machine code, so the program can be run as long as
the platform provides the corresponding interpreter. Interpreted languages require
the source code to be interpreted into machine code and executed every time the
program is run, which is inefficient. Both Python and Perl are typical interpreted
languages.
Figure 18.4 shows the process of interpreted languages from source code to
program: the source code file (Python file) is converted into a byte code file (.pyc
file) by an interpreter and then run on a Python virtual machine (Python
VM, PVM).
Fig. 18.3 The process of compiling a language from source code to program
3. The interpreter runs Python source code and interprets it to generate a .pyc file
(byte code).
4. The Python virtual machine converts the byte code into the machine language.
5. The hardware executes the machine language.
Python can run codes in two ways: interactive mode and scripted mode.
Programming in the interactive mode (i.e., interactive programming) does not
require the creation of a script file, and code can be written by the interactive mode of
the Python interpreter. Figure 18.7 illustrates the process of interactive programming
on a Windows system. [Note: in Fig. 18.7, Print( ) is a built-in Python function that
serves to output the contents in the parentheses.]
Code written in the scripted mode of programming (i.e., scripted programming)
can be run on a variety of Python interpreters or integrated development environ-
ments. For example, IDLE, Atom, Visual Studio, Pycharm, and Anaconda that come
with Python. A typical script-based programming process is shown in Fig. 18.8.
First, write a Python script using Notepad software, save the script file and change its
extension to .py, and then execute the script file in the Python interpreter.
Coding specifications are the naming rules, code indentation, code and statement
splitting and so on that should be followed when writing code in Python. Good
coding specifications help improve the readability of code and make it easier to
maintain and modify.
1. Suggestions for the use of semicolons, blank lines, parentheses and spaces.
Semicolons: Python programs allow semicolons at the end of lines, but it is not
suggested to use semicolons to isolate statements. It is recommended that each
statement occupy a separate line. If there are multiple statements on a line, they
can be separated by semicolons.
Blank lines: blank lines can be used to separate different functions or statement
blocks so as to distinguish between two pieces of code and improve the readabil-
ity of the code.
Parentheses: parentheses can be used to continue long statements, and unnec-
essary brackets are generally eliminated.
Spaces: it is not recommended to use spaces within the parentheses. You can
decide whether to add spaces on both sides of an operator according to your
personal habits.
2. Identifier naming conventions.
Python identifiers are commonly used to represent the names of constants,
variables, functions, and other objects. Identifiers usually consist of letters,
numbers and underlines, but they cannot begin with a number. Identifiers are
case-sensitive and do not allow renaming. If an identifier does not conform to the
naming convention, the compiler will output a SyntaxError error message when it
runs the code. As shown in Fig. 18.9, the fifth identifier starts with a number,
which is an incorrect identifier.
3. Code indentation.
When writing conditional and looping statements in Python, you need to use
the concept of code blocks. A code block is a set of statements that are executed
when certain conditions are met. In Python programs, code indentation can be
used to delimit a code block. If a code block contains two or more statements,
they must have the same amount of indentation, and the Python language uses
code indentation and colons to distinguish between levels of code. For Python,
code indentation is a syntax rule.
When writing code, it is recommended to use four spaces for indentation. If the
wrong indentation is used in the code, an IndentationError message will be
returned when the program is run. The judgment statements shown in
Fig. 18.10 list the beginning and end of code blocks, as well as examples of
correct and incorrect indentation. The if line and the else line in the figure belong
to the same code block and have the same indentation. The last line print
(a) belongs to the same block as the if and else lines, so the indentation should
be the same.
4. Use comments
Comments are explanatory notes added to the program that can enhance the
readability of the program. As shown in Fig. 18.11, in Python programs, com-
ments are divided into single-line comments and multi-line comments. Single-
line comments begin with # and end at the end of the line. Multi-line comments
can contain multiple lines of contents that are contained within a pair of triple
quotes (“‘. . .”’ or “““. . .”””).
5. The structure of code file.
A complete Python source code file generally contains an interpreter and
encoding format declarations, documentation strings, module imports and
runtime code.
If you need to call classes from the standard library or other third-party
libraries in your program, you need to first use the “import” or “from . . . import”
statement to import the relevant module. The import statement is always located
at the top of the file after the module comment or documentation string. Fig-
ure 18.12 is an example of the structure of a source code file.
• The interpreter declaration is used to specify the path to the compiler that runs
this file (the compiler is installed via a non-default path or there are multiple
18.3 Python Language 547
Python compilers). The interpreter declaration in the first line of this example
can be omitted on Windows operating systems.
• The encoding format declaration is used to specify the encoding type used by
this program and to read the source code in the specified encoding type.
Python 2 uses ASCII encoding by default (Chinese is not supported), and
Python 3 supports UTF-8 encoding by default (Chinese is supported).
• The documentation string serves as a general introduction to the program’s
functionality.
• The module import section imports the time module, which is a built-in Python
module that provides functions for handling time-related issues.
548 18 Network Programming and Automation
Telnet defines the Network Virtual Terminal (NVT). It describes a standard repre-
sentation of data and command sequences transmitted over the Internet, thus
shielding differences across platforms and operating systems, such as different
commands for line breaks on different platforms. In order to distinguish Telnet
commands from ordinary data, Telnet uses escape sequences. Each escape sequence
consists of two bytes. The first byte is 0xFF, called IAC (Interpret as Command,
which is an escape character indicating that the byte following the character is the
command code); and the second byte is the code of the command to be executed.
Telnet can be used on Windows or Linux systems to remotely configure network
devices such as Huawei routers and switches.
The telnetlib is a module in the Python standard library. It provides a class
telnetlib.Telnet that implements the functions of Telnet. Table 18.1 shows the
methods defined by the telnetlib module, where different functions can be enabled
by calling different methods of the Telnet class of the telnetlib module.
This case will show how to import the telnetlib module using Python script file, how
to configure Huawei router via Telnet and how to change the device name, create
VLAN, and set the interface IP address of a Huawei router.
1. First, configure the interface IP address of the Huawei router.
[Huawei]user-interface vty 0 4
[Huawei-ui-vty0-4]authentication-mode password
Please configure the login password (maximum length 16):huawei@123
[Huawei-ui-vty0-4]user privilege level 15
[Huawei-ui-vty0-4]quit
3. Use Telnet to login to the router on Windows, and observe the interaction
process.
C:\Users\hanlg>telnet 192.168.80.99
Login authentication
Password:
<Huawei>system-view
Enter system view, return user view with Ctrl+Z.
[Huawei]quit
4. Based on the Telnet interaction in the previous step, write a Python script to read
the Telnet output using the telnetlib module, and then enter the Telnet command
to configure the network device.
The encode() and decode() functions of Python are used to encode and decode
strings in the specified way. In this case, password.encode(’ ascii’) means to convert
the string huawei@123 to ASCII. Here the encoding format follows the official
requirements of the telnetlib module.
Python prefixes the string with a b, such as b‘string’, to convert the string to bytes.
In this case, b‘Password:’ indicates that the string Password: is converted to a byte-
type string. The encoding format here follows the official requirements of the
telnetlib module.
18.5 Exercises
Open Access This chapter is licensed under the terms of the Creative Commons Attribution-
NonCommercial-NoDerivatives 4.0 International License (http://creativecommons.org/licenses/by-
nc-nd/4.0/), which permits any noncommercial use, sharing, distribution and reproduction in any
medium or format, as long as you give appropriate credit to the original author(s) and the source,
provide a link to the Creative Commons license and indicate if you modified the licensed material.
You do not have permission under this license to share adapted material derived from this chapter or
parts of it.
The images or other third party material in this chapter are included in the chapter’s Creative
Commons license, unless indicated otherwise in a credit line to the material. If material is not
included in the chapter’s Creative Commons license and your intended use is not permitted by
statutory regulation or exceeds the permitted use, you will need to obtain permission directly from
the copyright holder.