HCIA-openEuler V1.0 Learning Guide
HCIA-openEuler V1.0 Learning Guide
HCIA-openEuler V1.0 Learning Guide
HCIA-openEuler
Learning Guide
ISSUE: 1.0
2
HCIA-openEuler System Engineer Learning Guide Page 1
and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of
their respective holders.
Notice
The purchased products, services and features are stipulated by the contract made
between Huawei and the customer. All or part of the products, services and features
described in this document may not be within the purchase scope or the usage scope.
Unless otherwise specified in the contract, all statements, information, and
recommendations in this document are provided "AS IS" without warranties,
guarantees or representations of any kind, either express or implied.
The information in this document is subject to change without notice. Every effort has
been made in the preparation of this document to ensure accuracy of the contents, but
all statements, information, and recommendations in this document do not constitute
a warranty of any kind, express or implied.
Forword
As the most widely used operating system (OS), Linux has been developed for
nearly 30 years and has become the most basic platform in the information
technology (IT) industry. openEuler is an open source OS that runs on Linux
Kernel as well as an open and innovative platform. It not only supports multiple
processor architectures including Kunpeng, but also explores the potentials of
the OS and system architecture. The openEuler community will eventually
become an open source ecosystem that leads technological innovation. Open
source is an approach to construct the industry ecosystem. More and more
companies around the world use open source to promote the construction of
the industry chain ecosystem and even influence industry development, building
an ecosystem chain from open source communities to open source-based
enterprise-grade products and services.
Open source is a collaborative innovation mode. This mode greatly accelerates
the speed of software development and shortens the time for formulating
industry standards. In addition, an open and collaborative open source
environment is more likely to inspire innovations and creativity. Innovations
emerge one after another in open source communities.
Open source is a way of cultural exchange. Through open source, the wisdom
of the world can be gathered to jointly develop and evolve large-scale software
systems in different corners of the world. This has also, to a large extent,
deepened communication and understanding around the world.
Communication is the key to building a better future around the world.
openEuler is a free open source Linux distribution. In the openEuler community,
global developers join hands to build an open, diversified, and architecture-
inclusive software innovation ecosystem. In addition, openEuler is an innovative
platform that encourages anyone to propose new ideas, explore new
opportunities, and practice new solutions.
HCIA-openEuler System Engineer Learning Guide Page 5
Preface
Contents
Forword ........................................................................................................................................ 4
Preface.......................................................................................................................................... 5
1 Getting Started with openEuler .......................................................................................... 9
1.1 Introduction to the Linux OS ............................................................................................................................................... 9
1.1.1 What Is an OS? ...................................................................................................................................................................... 9
1.1.2 Common OSs ........................................................................................................................................................................11
1.1.3 Origin and Development of Linux ................................................................................................................................12
1.2 Installing the openEuler OS ................................................................................................................................................14
1.2.1 Introduction to openEuler................................................................................................................................................14
1.2.2 Installing the openEuler OS ............................................................................................................................................15
1.3 Using the openEuler OS .......................................................................................................................................................20
1.4 Quiz .............................................................................................................................................................................................21
2 CLI Basics ................................................................................................................................22
2.1 Basic Knowledge of Linux Commands ............................................................................................................................22
2.2 Basic Linux Commands.........................................................................................................................................................23
2.2.2 Login Commands ................................................................................................................................................................24
2.2.3 Power Management Commands ..................................................................................................................................26
2.2.4 File Management Commands ........................................................................................................................................27
2.2.5 Help Commands ..................................................................................................................................................................39
2.3 Quiz .............................................................................................................................................................................................41
3 Text Editors and Text Processing ......................................................................................42
3.1 Common Linux Text Editors ...............................................................................................................................................42
3.2 Text Editors and Text Processing ......................................................................................................................................44
3.2.1 Vim Text Editor ....................................................................................................................................................................44
3.2.2 Text Processing ....................................................................................................................................................................49
3.3 Quiz .............................................................................................................................................................................................57
4 User and Permission Management ..................................................................................58
4.1 User and User Group Management ................................................................................................................................58
4.1.1 User Management ..............................................................................................................................................................58
4.1.2 User Groups Management ..............................................................................................................................................61
4.2 File Permission Management.............................................................................................................................................63
4.2.1 Overview ................................................................................................................................................................................63
4.2.2 File Permission Management .........................................................................................................................................64
4.2.3 Special File Permissions ....................................................................................................................................................68
HCIA-openEuler System Engineer Learning Guide Page 7
User
Applications
Operating system
Hardware
Process management
Modern OSs provide multiprogramming technology that executes many programs
concurrently and shares system resources. After the emergence of multiprogramming
systems, the concept of "process" was refined to describe the dynamic characteristics of
concurrent programs and control their activity status. A process is the basic unit that
describes the program execution and can be used to share resources. An OS allocates
hardware resources to process and maintain the state of each process, to accomplish
concurrent computer tasks.
HCIA-openEuler System Engineer Learning Guide Page 10
To make different processes share hardware resources, the OS must manage hardware
resources. The OS provides service interfaces for processes through system calls to restrict
processes from directly performing operations on hardware resources. To perform
restricted operations, the process needs to invoke these system call interfaces to send
service requests to the OS and hand over the CPU control right to the OS. After receiving
the request, the OS invokes the corresponding processing program to complete the service
requested.
To execute concurrently, processes need to share CPU in time division multiplexing (TDM)
mode, which means the OS should support process swapping, stopping the on-going
process that occupies the CPU for a period of time and selecting the next process. To
prevent malicious CPU occupancy, the OS can use the timer interrupt to stop the current
process at regular intervals for process swapping.
Memory management
Programs and code in the system need to be loaded to the memory before being scheduled
and executed by the CPU. Therefore, when multiple processes are executed concurrently,
all of the processes need to be loaded to the memory. As a result, the memory becomes a
key factor that affects the OS performance. The OS memory management mainly solves
the memory sharing problem of concurrent processes. Technologies such as virtual memory,
paging scheme, and physical memory expansion through external storage are used to
improve the memory utilization and addressing efficiency.
User interface
The OS provides an interactive environment for ease of use. Generally, interfaces for
interaction between users and the OS are classified into command interfaces and APIs.
HCIA-openEuler System Engineer Learning Guide Page 11
⚫ Command interfaces
A user sends a series of instructions to the computer through an input device or in a job,
so that the computer performs the task according to the instructions. There are two types
of common command interfaces:
➢ Command line interface (CLI), which is a character-based user interface. The
keyboard is used as the input tool to enter commands, options, and parameters to
execute programs, achieving high efficiency. For example, the MS-DOS system.
➢ Graphical user interface (GUI), which presents all elements as graphical. The mouse
is used as the main input tool, and buttons, menus, and dialog boxes are used for
interaction, enhancing ease of use. For example, the Windows system.
⚫ APIs
An API is mainly made up of system calls, through which applications can access resources
in the system and obtain services provided by the kernel. Each system call corresponds to
a subprogram that is performed in the kernel for a specific function.
By 1985, Stallman released the General Public License (GPL) to prevent free GNU software
from becoming proprietary. It applies two measures to protect the rights of programmers:
(1) copyright protection for software; (2) license for programmers, which gives them the
legal permission to copy, distribute, and modify the software. In terms of copying and
distribution, the GPL states that "You may copy and distribute verbatim copies of the
Program's source code as you receive it, in any medium, provided that you conspicuously
and appropriately publish on each copy an appropriate copyright notice and disclaimer of
warranty; keep intact all the notices that refer to this License and to the absence of any
warranty; and give any other recipients of the Program a copy of this License along with
the Program. You may charge a fee for the physical act of transferring a copy, and you
may at your option offer warranty protection in exchange for a fee. However, if a software
product uses the GPL products ("use" refers to class library reference, modified code, or
derivative code), the software must use the GPL protocol, which must be open source and
free of charge."
Currently, in addition to GPL, the commonly used open source licenses mainly include
Mulan, LGPL, and BSD.
Mulan is China's first open source license. It involves five major aspects: copyright licensing,
patent licensing, non-trademark licensing, distribution restriction, and disclaimer and
liability restriction. It grants "every contributor" a permanent, global, free, non-exclusive,
and irrevocable copyright license. Under the license, you can copy, modify, and distribute
your "contributions" regardless of whether they are modified or not.
LGPL is an open source protocol designed for the use of class libraries. Different from GPL,
LGPL allows commercial software to use the LGPL class library in link mode without
requiring open-sourcing commercial software code. This allows open source code using the
LGPL protocol to be referenced, released, and sold as a class library by commercial software.
However, if the LGPL protocol code is modified or derived, all modified code, extra code
involving modification, and derived code must use the LGPL protocol.
BSD is an open source protocol that you can use and modify the source code freely, or
release the modified code as open source or proprietary software. When you release code
that uses the BSD protocol, or perform secondary development based on the BSD protocol
code, the following conditions must be met:
⚫ If the redistributed software contains source code, the source code must include BSD
of the original code.
⚫ If the redistribution is only a binary class library/software, you need to include BSD of
the original code in the class library/software documentation and copyright notice.
⚫ Marketing using the original open source software's name, author's name, or
institution's name is not permitted. BSD code encourages code-sharing but requires
respect for the copyright of the code author. BSD allows users to modify and
redistribute the code and allows the use or development of commercial software
distribution and sales on the BSD code. It is a very friendly license for commercial
integration.
The emergence of free software and openness in source code promote the rapid
development of IT technologies.
HCIA-openEuler System Engineer Learning Guide Page 14
Birth of Linux
In 1991, Linus Torvalds, a student of University of Helsinki, developed a new OS kernel
based on Minix. Leveraging the free software such as bash and gcc provided by GNU, Linus
successfully developed a new OS kernel, named Linux, and made it open source, calling on
thousands of developers to improve the Linux OS. After that, programmers around the
world joined with Torvalds to develop Linux. In March 1994, Linux 1.0 was officially released
with the joint efforts of developers.
Though the Linux kernel was not part of the GNU project initially, it was developed with
GNU. Currently, most of the Linux kernel-based OSs contain GNU software. Therefore,
strictly speaking, these systems should be called GNU/Linux.
Linux now has many derivative versions. A Linux distribution is a suite that provides Linux
kernel, some system software and utilities. The main differences between Linux
distributions are the supported hardware devices and software package configurations.
Mainstream Linux distributions include Red Hat, openSUSE, Ubuntu, and Deepin.
Linux distributions
You can visit https://www.kernel.org to view and download the Linux kernel version. The
Linux kernel version number is composed of three digits:
⚫ The first digit indicates the current major release.
⚫ An even second digit indicates a stable version, while an odd second digit indicates a
version under development.
⚫ The third digit indicates the number of revisions.
Take openEuler 20.03 LTS as an example. The kernel version 4.19.90 is under development.
The major release number is 4, and the number of revisions is 90. Compared with the stable
version of kernel, 4.19.90 has many new functions.
Linux distributions are classified into either commercial or community. Commercial
distributions, such as Red Hat, are maintained by companies and provide charged services,
such as patch upgrades. Community distributions, such as CentOS, Debian, and openEuler,
are maintained by community organization and free of charge.
the end of 2019, EulerOS was officially open-sourced and renamed as openEuler. openEuler
is also an innovative platform that encourages everyone to propose new ideas, explore new
approaches, and practice new solutions. openEuler community is available for all
developers, enterprises, and organizations. They can also develop their own OS versions
based on the community release.
openEuler has two kinds of releases: innovation and long-term support (LTS). The
innovation release supports technical and content innovations of Linux enthusiasts, such
as openEuler 20.09. Generally, a new version is released every half a year. LTS is a stable
version of openEuler, for example, openEuler LTS 20.03. Generally, a new version is released
every two years. This course takes openEuler 20.03 LTS as an example to illustrate all
operations involved.
The two versions involved in this course are the same. This document uses openEuler
x86_64 as an example. For details, see section 1.2 "Configuring the Virtualization
Environment" in HCIA-openEuler Lab Guide-PC.
End
After the installation is complete, restart the system, and log in to the system as the root
user, as shown in Figure 1-6.
You can run the following commands to view the system information. The description of
the commands will be described in the following sections.
⚫ View the system information.
1.4 Quiz
⚫ What are the differences between the Windows OS and the Linux OS?
⚫ What is open source software?
⚫ What are the differences between the x86 architecture and ARM architecture?
⚫ What are the differences between the root user and a common user?
⚫ What are the other shell tools besides bash? What are the differences between
them?
HCIA-openEuler System Engineer Learning Guide Page 22
2 CLI Basics
⚫ The option. The number and content of options vary with commands.
➢ If there are multiple options, you can write them together. For example, ls -la
contains two options: -l and -a. -l lists the file list and detailed file information
together. -a displays the information about all the files or directories in the
current directory.
➢ Options can be short by following one hyphen (-) or long by following two
hyphens (--). For example, ls -a equals ls --all.
⚫ The parameter indicates the operation object. Generally, it can be a file name,
directory, or username.
Getting familiar with CLI skills in advance is helpful for you to master the operations. For
example, in the bash environment, you can press Tab to automatically supplement
commands or file names, saving time and improving accuracy. If no command is entered,
press Tab twice to list all available commands. If you have entered a part of the command
name or file name, pressing Tab will supplement them automatically.
In addition, the following table lists the common shortcuts.
Login and
login, shutdown, halt, reboot,
power 2 "CLI Basics"
install, exit, and last
management
file, mkdir, grep, dd, find, mv, ls, 2 "CLI Basics" and 3 "Text
File processing
diff, cat, and ln Editors and Text Processing"
⚫ Note: Linux commands are far richer than the examples above. Common commands
of different types are introduced in later sections.
virtual console is that when a program goes wrong and causes a system deadlock, you can
switch to another virtual console and close the program.
last
last is used to display the recent logins of users or terminals, and is applicable to all users.
Run the last command to view a program's log. The user will know who used, or attempted
to connect to, the system. Main options:
⚫ -n: specifies the number of output records.
⚫ -t tty: displays the login status of the specified virtual console.
⚫ -y: displays the year, month, and day of the record.
⚫ -ID: displays the username.
⚫ -x: displays the history of system shutdowns, user logins, and user logouts.
exit
exit is used to exit the current shell, and is applicable to all users.
logout
logout is used to log out of the system, and is applicable to all users. logout can only be
used when the current shell is the login shell.
Welcome to 4.19.90-2003.4.0.0036.oe1.x86_64
[root@host ~]#
HCIA-openEuler System Engineer Learning Guide Page 26
⚫ -n: prevents synchronization of system calls. It is used after the root partition is
repaired using fsck, and prevents the kernel from overwriting the repaired superblock
with that of an earlier version. The sync command is used to forcibly write the data
in the buffer to the disk immediately. The fsck command is used to check and rectify
faults in the file system. A superblock is located at very front of a block group. It
describes the data structure of the overall information about a file system, including
the static distribution of directories and files in the file system, and the size and
quantity of each structure of the file system.
⚫ -w: writes the wtmp file in /var/log/wtmp instead of restarting or shutting down
the system. /var/log/wtmp is a binary file that records the number of login times
and duration of each user.
⚫ -i: shuts down all network interfaces before shutting down or restarting the system.
⚫ -d: shuts down the system without making a record.
reboot
reboot is used to restart the computer, and is applicable to the system administrator. Main
options:
⚫ -n: saves the data and restarts the system.
⚫ -w: writes records to the /var/log/wtmp file. It does not restart the system.
⚫ -d: does not write records to the /var/log/wtmp file. (The -n option contains -d.)
⚫ -i: restarts the system after disabling the network settings.
[root@host ~]# ls /
bin dev home lib64 media opt root sbin sys usr
boot etc lib lost+found mnt proc run srv tmp var
The following table lists the usage of some directories in the root directory:
bin is short for binary. This directory stores the most frequently used
/bin
commands.
Stores some core files used for starting the Linux OS, including some
/boot
connection files and image files.
dev is short for device, and this directory stores Linux external device
/dev files. The method used to access devices on Linux is the same as that
for accessing files.
Stores the system's most basic dynamic link libraries (DLLs). The
function of this directory is similar to the storing of DLL files on
/lib
Windows. Almost all applications need to use these shared libraries.
/lib64 stores the shared library of a 64-bit system.
/srv Stores the data that needs to be extracted after a service is started.
Many user applications and files are stored in this important directory,
which is similar to the program files directory on Windows. /usr/bin is
/usr the application used by system users. /usr/sbin is an advanced
management program and system daemon used by the superuser.
/usr/src is the default directory for storing the kernel source code.
HCIA-openEuler System Engineer Learning Guide Page 29
Stores content that is constantly expanded, such as log files. You are
/var
advised to place frequently modified directories here.
[root@host ~]# ls /
[root@host ~]# cd /
⚫ View details about all files in the root directory and sort the files by time:
⚫ Access the home directory through a relative path and the following file directory is
displayed, for example, the openEuler directory.
[root@host openEuler]# cd ..
[root@host home]# cd ~
mkdir
The mkdir command is used to create one or multiple directories or folders. If a directory
already exists, an error is reported by default. The -p option enables the command to report
no error in this case, and can also be used to automatically create a parent directory.
Syntax:
mkdir [OPTIONS] DIRECTORY
Common usage:
⚫ Create a directory named dir1:
⚫ If dir1 and dir2 do not exist, create the dir1 parent directory, dir1/dir2 subdirectory,
and dir1/dir2/dir3 subdirectory.
touch
The touch command is used to create an empty file and change the timestamp of a file.
Syntax:
touch [OPTIONS] FILE
Common usage:
⚫ Create a blank file named file and set the timestamp to the current time:
cp
The cp command is used to copy files or directories. You can copy a single file or multiple
files at a time. Exercise caution when running this command, as there is a risk of data loss.
Syntax:
cp [OPTIONS] SOURCE DIRECTORY or FILE
⚫ -a: copies the files of a directory while retaining the links and file attributes.
⚫ -p: copies the file content, modification time, and access permissions to the new file.
⚫ -r: copies all subdirectories and files in the source directory file.
⚫ -l: generates a link file but does not copy the file.
Common usage:
⚫ Copy the file f1 and name the new file f2.
[root@host ~]# cp f1 f2
⚫ Copy f1 to the d1 directory and keep the name of the new file unchanged.
⚫ Copy multiple files to the same directory. When multiple files are copied, the
destination must be a directory.
⚫ If f2 already exists, wait for confirmation before overwriting it. Enter y to overwrite
the file.
[root@host ~]# cp -i f1 f2
⚫ Copy all subdirectories and files in the d1 directory, and name the new directory d2.
The -r option is required for copying the directory.
[root@host ~]# cp -r d1 d2
⚫ Use the -a option to keep the original attributes when copying the f1 file. It can be
used to copy block devices, character devices, and pipe files.
[root@host ~]# cp -a f1 f2
mv
The mv command is used to move a file or directory. Exercise caution when running this
command, as there is a risk of data loss. If the source file and target file are in the same
parent directory, the mv command is used to rename the file.
Syntax:
mv [OPTIONS] SOURCE DIRECTORY or FILE
⚫ -b: backs up a file before overwriting it.
⚫ -f: forcibly overwrites the target file without asking the user.
⚫ -i: overwrites the target file at the destination after obtaining the user's consent.
⚫ -u: updates the target file only when the source file is newer than the target.
The usage of mv is the same as that of cp. The common usage is as follows:
⚫ Move f1 to f2.
[root@host ~]# mv f1 f2
⚫ Move f1 to the d1 directory and keep the name of the new file unchanged.
⚫ If f2 already exists, wait for confirmation before overwriting it. Enter y to overwrite
the file.
[root@host ~]# mv -i f1 f2
[root@host ~]# mv –b f1 f2
⚫ Move all subdirectories and files in the d1 directory, and name the new directory d2.
The -r option is required for moving the directory.
[root@host ~]# mv -r d1 d2
⚫ When all subdirectories and files in the d1 directory are moved, the moving process
is displayed.
[root@host ~]# mv -f f1 f2
rm
The rm command is used to delete files or directories. Exercise caution when running this
command, as it is not possible to completely restore files deleted in this manner. As the rm
command does not move files to a place from which they can be restored, such as a "recycle
bin", the deletion operation cannot be revoked.
Syntax:
rm [OPTIONS] DIRECTORY or FILE
⚫ -i: performs interactive deletion. The system asks the user before the deletion.
⚫ -f: forcibly deletes a file without asking.
⚫ -r: instructs rm to recursively delete all directories and subdirectories listed in the
parameter.
⚫ -v: displays the detailed procedure.
Common usage:
⚫ Delete the f1 file.
[root@host ~]# rm f1
[root@host ~]# rm f1 f2
⚫ Interactively delete the f1 file. Before the deletion, wait for confirmation. Enter y to
delete the file.
[root@host ~]# rm -i f1
⚫ Forcibly delete file f1. If the command contains both -i and -f, the command written
on the right takes effect.
[root@host ~]# rm -f f1
⚫ Recursively delete the d1 directory and all subdirectories and files in the directory.
[root@host ~]# rm -r d1
⚫ Recursively delete the d1 directory and all subdirectories and files in the directory,
and display the process.
find
The find command is used to search for files in a specified directory. You can specify search
criteria, such as file name, file type, user, and even timestamp.
Syntax:
find [PATH] [EXPRESSION]
⚫ -name: searches for files by file name.
⚫ -perm: searches for files by file permission.
⚫ -user: searches for files by file owner.
⚫ -mtime -n +n: searches for files by modification time.
⚫ Search for files whose names contain book.
⚫ Search for files whose names contain passwd in the /etc directory.
locate
The locate command is used to quickly check whether a specified file exists in the file
system. It creates a database with a file name and path, and then searches the database
for the file name and path.
Syntax:
locate [OPTIONS] PATTERN
⚫ -e: specifies the exempt scope.
⚫ -f: excludes specified files.
⚫ -r: uses a regular expression as the search criteria.
⚫ -o: specifies the file name.
⚫ -d: specifies the file path.
When you run the locate command to search for a file, the system searches for the file in
the index database. If the database is not updated for a long time or does not exist, the
system displays the message "locate: can not open `/var/lib/mlocate/mlocate.db`: No such
file or directory". In this case, run the updatedb command to update the database.
HCIA-openEuler System Engineer Learning Guide Page 36
which
The which command is used to search for executable files in the directory specified by
PATH. You can run the which command to check whether a system command exists and
where the command is executed.
Syntax:
which [OPTIONS] PROGRAMNAME
Common usage:
⚫ Search for the absolute path of the ls command.
⚫ Search for the absolute path of the ls command. If there are matched files in
multiple directories, all the files are displayed.
ln
ln is short for link. The ln command is used to create a link file. It creates a synchronous
link for a file in another location. When the same file is required in different directories,
instead of placing the file in each required directory, users only need to place it in a fixed
directory and then run the ln command to create a link to the file in other directories,
which also saves disk space.
There are two types of links on Linux: soft link (also known as symbolic link) and hard link,
as shown in the following table.
A link, which becomes invalid after A link, which has no impact on the
the source file is deleted source file after being deleted
If the ln command does not contain any option, a hard link is created by default.
Syntax:
ln [OPTIONS] SOURCE [DIRECTORY or FILE]
⚫ -b: deletes and overwrites the existing link.
HCIA-openEuler System Engineer Learning Guide Page 37
[root@host ~]# ln f1 f2
[root@host ~]# ln -s d1 d2
⚫ Interactively create the f1 file link and name it f2. If f2 already exists, the system
asks you whether to continue the creation. Enter y to confirm the creation and
overwrite the original file.
[root@host ~]# ln –i f1 f2
[root@host ~]# ln –f f1 f2
[root@host ~]# ln –b f1 f2
For more exercises about basic file operations, see section 2.2 "Basic Operations of the bash
Command" in the HCIA-openEuler Lab Guide (PC Edition).
Common usage:
⚫ Compress file f1.
tar
The tar command is used to pack files. You can pack multiple files into a package to
facilitate data transfers. The tar command is usually used together with options -z, -j, and
-J, which corresponds to the gzip, bzip2, and xz compression tools, respectively. After a
compression option is specified, the tar command starts the corresponding compression
tool to compress or decompress data and transmits data through the pipe and compression
tool.
Syntax:
tar [OPTIONS] [FILE]
⚫ -c: creates a compressed file.
⚫ -x: extracts files from a compressed file.
⚫ -t: displays the content of a compressed file.
⚫ -z: supports gzip decompression.
⚫ -j: supports bzip2 decompression.
⚫ -v: displays the operation process.
Common usage:
⚫ Pack the dir1 directory and all the content in the directory.
⚫ Decompress the package to the /tmp directory. (By default, the path is the current
directory.)
For more exercises about basic file operations, see section 2.4 "Packaging and Compression
Commands" in the HCIA-openEuler Lab Guide (PC Edition).
6 Games
The common types of man documents are 1, 4, 5, and 8. man searches results by chapter
number in the manual. For example, after man sleep is entered, only command manuals
are displayed by default. To view library functions, enter man 3 sleep, in which the type 3
represents some common functions and function libraries. You can search for the man
document by keyword (man –k KEYWORD). For example, enter sleep and view the type
corresponding to the keyword.
As shown in Figure 2-4, the following information is displayed after you run help for the
pwd command:
HCIA-openEuler System Engineer Learning Guide Page 41
Figure 2-4 Running the help command to obtain the help information about
the pwd command
For more exercises about help commands, see section 2.5 "Help Command" in the HCIA-
openEuler Lab Guide (PC Edition).
2.3 Quiz
⚫ Which home directories will be accessed when you run the cd ~ command for
different users?
⚫ What are the differences between the shutdown and halt commands?
⚫ What are the differences between absolute paths and relative paths? How to use
them?
⚫ What are the differences between soft links and hard links?
⚫ What are the impacts on soft links and hard links after source files are deleted?
HCIA-openEuler System Engineer Learning Guide Page 42
Vi, the oldest text editor, is a standard Unix text editor and one of the most popular text
editors. All Linux and Unix OSs have the Vi text editor by default. Although Vi operations
are different from those of other text editors (such as gedit), Vi is still used frequently
because it only needs a character interface and can be used in all Unix and Linux
environments. Vi has three command modes:
⚫ Command: used to enter commands
⚫ Insert: used to insert text
⚫ Visual: used to browse text
Vim
Vim is a text editor developed from Vi. Equipped with many convenient programming
functions such as code completion, compilation, and error redirection, Vim is frequently
used by programmers, and is also one of Unix-like system users' favorite editors alongside
Emacs. The first version of Vim was released in 1991 by Bram Moolenaar. The initial name
was Vi IMitation. After it developed more functions, the name was changed to Vi IMproved.
It is now free and open-source software. Vim has multiple modes:
⚫ Basic modes:
➢ Normal: This mode allows the usage of editor commands, such as moving a
cursor and deleting text. It is the default mode after Vim is started, which is the
opposite of what many new users expect (most editors are in Insert mode by
default). Vim's powerful editing capabilities come from its Normal-mode
commands, which require an operator at the command end. For example, the dd
command is used to delete the current line, and you can replace the second d
with another move command (for example, j) to move one line down and delete
both the current and next lines. In addition, you can specify the number of times
that a command can be repeated. For example, 2dd indicates that the command
is repeated twice, and the effect is the same as that of dj. After learning various
move and jump commands and Normal-mode edit commands, and
understanding how to flexibly combine these commands, you can edit text more
efficiently, compared with using modeless editors. There are many ways to enter
Insert mode from Normal mode. For example, press a (append) or i (insert).
➢ Insert: In this mode, most keys are used to insert text into the text buffer. New
users often want the text editor to remain in this mode throughout the editing
process. You can press Esc to enter Normal mode from Insert mode.
➢ Visual: While this mode is similar to Normal mode, the main difference is that
using a move command will enlarge the highlighted text area, which can be a
character, a line, or a piece of text. A non-move command is executed on the
highlighted area. Vim's text object can also be used in this mode, similar to the
move command.
➢ Select: This mode is similar to a modeless editor in terms of function (Windows
standard text control). In this mode, you can use a mouse or an arrow key to
highlight the text. However, if you enter any character, Vim replaces the selected
highlighted text block with that character and automatically enters Insert mode.
➢ Command-line: In this mode, you can enter text that will be interpreted and
executed. For example, you can search (using / and ?) as well as execute and
filter commands (using : and ! respectively). After a command is executed, Vim
HCIA-openEuler System Engineer Learning Guide Page 44
⚫ If the filename file is opened in read-only mode, Vim displays [readonly] at the
bottom of the screen and saves it forcibly.
⚫ When the :wq command is executed, a message indicating that ! needs to be added
to forcibly overwrite the file is displayed.
⚫ The filename file is displayed in read-only mode, but it cannot be forcibly saved.
h or left arrow key (←) Moves the cursor back one character.
j or down arrow key (↓) Moves the cursor down one character.
l or right arrow key (→) Moves the cursor forward one character.
Data Operations
In Vim Normal mode, you can use shortcut keys to copy, paste, and delete content in Vim.
The following table lists common shortcut keys.
p below the current line Pastes data below the current line.
p above the current line Pastes data above the current line.
Paste
p behind the cursor Pastes data behind the cursor.
Examples:
⚫ Run :set nu to display a line number.
1 hello
2 openEuler
~
~
~
~
~
:set nu
:/word
# Press n to search forwards, and Shift+n to search backwards.
:?word
# Press n to search forwards.
:1,5s/word1/word2/g
# If g is not added, only the first word1 in each line is replaced.
:%s/word1/word2/gi
:set hlsearch
:/hello
# Command output:
HCIA-openEuler System Engineer Learning Guide Page 48
hello
openEuler
hello
world
~
~
:/hello
:set nohlsearch
Modifying a File
After you run the vim filename command to open a file, the system enters Normal mode.
To modify the file, press i to enter Insert mode. The system displays a message at the
bottom, indicating that the current mode is Insert. You can press Ecs to exit Insert mode
and return to Normal mode. The following is an example:
⚫ Run the following command, and "hello openEuler" is input in the filename file:
Undoing or Redoing
The following describes how to undo or redo an operation in the inserted text content.
⚫ Input u in Normal mode to undo the latest change. For example, if the input "hello
openEuler" is undid, the following information is displayed:
⚫ Input U in Normal mode to undo all changes at the current line since the cursor has
been positioned at the line. The command output is similar to the preceding
information.
⚫ Press Ctrl+R to redo the last undid change. For example, if the canceled "hello
openEuler" is restored, the following information is displayed:
⚫ View the /etc/profile file content and number non-blank lines starting from 1.
⚫ View the /etc/profile file content and display the line number at the beginning of
each line.
⚫ View the /etc/profile file content. If multiple blank lines exist, only one is displayed.
q Exits more.
q Exits less.
HCIA-openEuler System Engineer Learning Guide Page 52
Examples:
⚫ Display the first 20 lines in the /etc/passwd file.
⚫ To display all the lines before the last 20 lines in the /etc/passwd file, set the
variable to a negative value. For example, if a file contains 37 lines, you can display
the first 17 lines by running the following command.
⚫ To display all the lines after the 20th line in the /etc/passwd file, add + before the
variable value. For example, if a file contains 37 lines, you can display lines 21 to 37
by running the following command.
⚫ Display the third to eighth characters in each line in the /etc/passwd file.
# $1 is the variable name, indicating that the printed object is the content in the first column. $2 and
$3 are the content in the second and third columns. The rule applies to other $N variables. If the
variable is $0, an entire line of data is printed.
⚫ Compare f1 with f2, display all the content, and mark the differences.
sed
Compared with tr, sed can modify character strings. sed, a streamlined, noninteractive
editor, can edit standard input and text from files. When a command is executed, sed reads
a line from the file or standard input and copies it to buffers. sed continues to read each
next line until all lines have been edited. As such, sed only changes the copied text stored
in buffers. To edit the original file directly, use the -i option. You can also redirect results
to a new file. The syntax is as follows:
sed [OPTIONS] {ACTION} [INPUT_FILE]
⚫ Display the content of the /etc/passwd file, excluding the content after line 10.
⚫ Display the content of the /etc/passwd file. However, "openEuler" is added to line 3.
⚫ Display the content of the /etc/passwd file. "openEuler" is added to line 2, and the
original file can be edited.
⚫ Display the content of the /etc/passwd file. Replace the content in lines 10 to 20
with openEuler.
For more examples about file viewing, see "Viewing a File" in the HCIA-openEuler Lab
Guide (PC Edition).
3.3 Quiz
⚫ What are the functions of the Vim Normal, Insert, and Command-line modes? How
do we switch between these modes?
⚫ What is the difference between :wq and :wq!? When to use them?
⚫ What are the similarities and differences between cut and grep?
⚫ How to fix or upgrade files when diff is used to find their differences?
⚫ What sed commands have the same effect as head, tail, and cut commands?
HCIA-openEuler System Engineer Learning Guide Page 58
On Linux, each user has an account containing information such as a user name, password,
and home directory. Some users are created by the user administrator, and some are
created by the system for special usages. The most important user is the administrator user,
with the default user name root. To facilitate managing permissions of different accounts,
Linux designs another concept: user group. Each user belongs to at least one group so that
users with the same permissions can be easily managed.
User and user group management is an important part of system security management.
This chapter describes user and group management commands provided by openEuler and
explains how to assign permissions to common users.
For example, to create a user named openEuler, run the following command as the root
user:
If no prompt is displayed, the user is successfully created. After the user is created, run the
passwd command to assign a password to the user. A new user without a password cannot
log in to the system.
To view information of the new user, run the id command:
HCIA-openEuler System Engineer Learning Guide Page 59
When changing a user password, ensure that the password meets the following complexity
requirements:
⚫ A password is a string of at least eight characters.
⚫ A password contains at least any three of the following: uppercase letters, lowercase
letters, digits, and special characters.
⚫ A password must be different from the user name.
⚫ A password cannot contain words in the dictionary.
Then, type the password and confirm it as prompted: The process is as follows:
For example, to change the shell of user openEuler to csh, run the following command:
To move the content of the existing home directory to a new directory, use the -m option:
Changing a UID
Run the following command as the root user to change the UID. In the command, UID
indicates the target user ID, and username indicates the user name. Change them to the
actual ID and name.
This command can change a user's UID in all files and directories under the user's home
directory. For files outside the home directory, you can only run the chown command to
manually change the ownership.
Changing the User Validity Period
If a shadow password is used, run the following command as the root user to change the
validity period of a user. In the command, MM indicates the month, DD indicates the day,
YY indicates the year, and username indicates the user name. Change them to the actual
time and name.
If you need to delete a user home directory and all contents in the directory, run the
userdel command with the -r option to delete them recursively.
⚫ Note: Do not directly delete a user who has logged in to the system. To forcibly
delete a user, run the userdel -f Test command.
HCIA-openEuler System Engineer Learning Guide Page 61
The sudo configuration can specify the dos and don'ts for a common user specified in the
/etc/sudoers file.
The configuration line of /etc/sudoers is as follows:
⚫ Note: A blank line or commented line (starting with #) has no specific function.
4.1.2.1 Operations
Adding a User Group
To add a new user group to the system, run the groupadd command as the root user. In
HCIA-openEuler System Engineer Learning Guide Page 62
the command, options indicate related parameters, and groupname indicates the user
group name.
Modifying a GID
To change a user group ID, run the following command as the root user. In the command,
GID indicates the target user group ID, and groupname indicates the user group.
⚫ Note: The groupdel command cannot delete the primary group of a user. To forcibly
delete the primary group of a user, run the groupdel -f Test command.
Adding a User to or Removing a User from a User Group
To add a user to or remove a user from a user group, run the gpasswd command as the
root user.
For example, to add the user openEuler to the user group Test, run the following
command:
For example, to remove the user openEuler from the user group Test, run the following
command:
[root@host bin]# ls -l
total 97224
-rwxr-xr-x. 1 root root 55624 Mar 24 2020 '['
-rwxr-xr-x. 1 root root 39248 Mar 24 2020 addftinfo
-rwxr-xr-x. 1 root root 35488 Mar 24 2020 addr2line
In the preceding example, the first In attribute of the addftinfo file is represented by a
hyphen (-). In Linux, the hyphen indicates that the file is a common file.
In openEuler, the first character indicates that the file is a directory, file, or link file.
D Directory
S Socket file
In subsequent characters, three characters are classified into one group combined based
on [rwx]. In the combination, [r] indicates read, [w] indicates write, and [x] indicates
execute. Note that the order of the three permission bits remains unchanged. If the
corresponding permission is not granted, the corresponding letter will be replaced by a
minus sign [-].
⚫ Read
⚫ Permission to read the actual content of a file.
⚫ Permission to read the directory structure list.
⚫ Write Permission
⚫ Permission to edit, add, or modify file content.
⚫ Permission to modify, delete, or move files in a directory.
⚫ Execution
⚫ Permission to execute files.
⚫ Permission to access a directory.
In most cases, binary numbers are used to replace the corresponding permission to
facilitate operations. For example, 7 indicates rwx.
4.2.2.2 Number
The openEuler file has nine basic permissions: owner, owner group, and other user roles
have their read, write, and execute permissions.
The three permissions of each role can be converted to binary numbers. For example, if the
permission is -rwxrwx---, the associated numbers are:
⚫ Owner: rwx = 4+2+1 = 7
⚫ Owner group: rwx = 4+2+1 = 7
⚫ Other users: --- = 0+0+0 = 0
Therefore, you can use 770 to change permissions. The syntax of the chmod command is
as follows:
What if you want to change the permission to -rwxr-xr--? Then the permission associated
number is:
[4+2+1][4+0+1][4+0+0]=754.
4.2.2.3 Symbol
As mentioned above, a file has nine permissions, which belong to the following:
⚫ user: owner
⚫ group: owner group
⚫ others: other users
In this case, u, g, and o can be used to represent the three roles.
In addition, a represents all, that is, all roles. The read and write permissions can be written
as r, w, or x.
HCIA-openEuler System Engineer Learning Guide Page 66
u
+ (add) r
g File or
chmod - (remove) w
o directory
= (set) x
a
To set the file permission to -rwxr-xr--, run the chmod u=rwx,g=rx,o=r command.
What if you want to remove a permission without changing other existing permissions?
For example, to remove the execute permission of all users, run the following command:
Examples:
⚫ Go to the / directory and change the owner of the test.txt file.
[root@host /]# cd /
[root@host /]# touch test.txt
[root@host /]# chown openEuler test.txt
[root@host /]# ls -l
total 64
-rw------- 1 openEuler root 0 Dec 14 14:47 test.txt
⚫ Change the owner and group owner of the test.txt file back to root.
[root@host /]# ls -l
total 64
dr-xr-xr-x 13 root root 0 Dec 14 14:47 sys
-rw------- 1 root root 0 Dec 14 14:49 test.txt
Or
Options:
⚫ -c or --changes: similar to the -v option, but returns only the modified part.
⚫ -f, --quiet, or --silent: does not display error information.
⚫ -h or --no-dereference: modifies only symbolic link files.
⚫ -R, --recursive: recursively processes all files and subdirectories in a specified
directory.
⚫ -v, --verbose: displays the command execution process.
⚫ --help: provides online help.
⚫ --reference=<Reference file or directory>: sets an owner group of a specified file or
directory to be the same as the owner group of a reference file or directory.
⚫ --version: shows version number.
Examples:
⚫ Change the group attribute of a file.
[root@host /]# ll
total 64K
-rw------- 1 root openEuler 0 Dec 14 14:49 test.txt
Options:
⚫ -S: specifies a permission mask in text format.
Examples:
⚫ Check the current permission mask.
0077
⚫ Run the mkdir command to create a directory, and then run the ls command to
obtain detailed information about the directory.
The following example shows setting the SUID permission on a file. If the file is executable,
it will execute with the permissions of its owner.
Common users do not have root permission. Therefore, they cannot view the information.
After the s permission is added, the openEuler user has the root permission temporarily.
chmod u-s filename: removes the s permission of a common user.
chmod u=rws filename can also be set, but u=rwS. S indicates that the x permission is
not enabled.
SGID: enables a common user to temporarily becomes a member of the owner group of a
file.
When SGID is applied to a directory, the directory or file created by any user in the directory
belongs to the same group as the directory, as shown in the following.
SBIT prevents a user except for the root user from deleting files of other users.
Syntax: chmod o+t File/Directory
file owner, user group, and other users. However, as technology develops, traditional
file permission control cannot meet the requirements of complex scenarios. For
example, there are multiple employees (such as user01 and user02) in a department
(a user group), and different permissions are assigned to employees with different
responsibilities. For example, the read and write permissions are assigned to user01,
the read-only permission is assigned to user02, and no permissions are assigned to
user03. As these employees belong to the same department, employee permissions
cannot be further refined. The access control list (ACL) is developed to solve this
problem. ACL provides permission settings in addition to common permissions (such
as rwx and ugo), and you can set specific permissions for a single user or a user
group.
Common types
⚫ Assign permissions to a file owner.
⚫ Assign permissions to a user group of a file.
⚫ Assign permissions to other users.
⚫ Etc
⚫ ...
4.2.4.2 Operations
On Linux, we can use ACL to manage a file and its specific user and user group permissions.
Simply put, an ACL requires only three commands: setfacl, getfacl, and chacl.
⚫ getfacl: obtains a file ACL.
ACL Rules
The setfacl command can identify the following rule formats:
⚫ - [d[efault]:] [u[ser]:]uid [:perms] specifies the permission of the user and the
permission of the file owner (if uid is not specified).
⚫ - [d[efault]:] g[roup]:gid [:perms] specifies the permission of a group and the
permission of owner group of the file (if gid is not specified).
⚫ - [d[efault]:] m[ask][:] [:perms] specifies the effective rights mask.
⚫ - [d[efault]:] o[ther] [:perms] specifies the permission of others.
Proper ACL rules are used in modify and set operations. You can specify either a name or
a number for uid and gid. The perms field is a combination of characters that indicate the
read (r), write (w), execute (x) permissions. The execute permission applies only to
directories and some executable files. The pers field can also be set to the octal format.
Automatically Created Rules
Initially, files and directories contain only three base ACL rules. To validate an ACL rule, the
following conditions must be satisfied:
⚫ - The three base rules cannot be removed.
⚫ - Whenever an ACL contains named users or named groups, it must also contain an
effective permission combination.
⚫ - Whenever an ACL contains any default ACL rules, the default ACL rules must exist.
Definition of ACL
HCIA-openEuler System Engineer Learning Guide Page 71
An ACL consists of a series of access entries. Each access entry defines the operation
permissions of a specific user type on files.
An access entry consists of three parts:
⚫ - Entry tag type
⚫ - Qualifier (optional)
⚫ - Permission
The following lists some entry tag types:
⚫ ACL_USER_OBJ: permission of file owner
⚫ ACL_USER: permissions that additional users can have on a file
⚫ ACL_GROUP_OBJ: permission of a group
⚫ ACL_GROUP: permissions that additional groups can have on a file
⚫ ACL_MASK: the maximum permissions of ACL_USER, ACL_GROUP_OBJ, and
ACL_GROUP.
⚫ ACL_OTHER: permission of others
⚫ chacl: changes the ACL of a file or directory.
The chacl command is similar to the chmod command, but is more powerful and precise.
While the chmod command specifies who can invoke a file, if a file of a user needs to be
viewed only by a specific user, the chacl command must be executed to meet the user's
requirements.
Example:
Other users have the read, write, and execute permissions. Now, we modify the ACL policy
so that the user code has only the read permission.
# group: root
user::rwx
user:code:r--
group::rwx
mask::rwx
other::rwx
The user permission is not determined only by the ACL configuration. It is determined by
the AND operation between the basic permission of the user code and the configured ACL
permissions, that is, other:rwx and code:r-- = code:r--.
Now check whether the user code has write permission.
When a file is written, the following information is displayed:
ACL can also be set for user groups and effective rights mask. For example, for a user group,
you can set g:[user group]:[rwx].
The user code has read permission on the /test file. If we change the effective rights mask
to write-only, the ACL permission is not within the effective rights mask. In this case, the
user code cannot read the /test file.
[root@host ~]# setfacl -m m:w /test //Set the effective rights mask to write-only.
⚫ Before reading the file content as the user code, write some content as the root user
to make the test more intuitive.
# owner: root
# group: root
user::rwx
group::rwx
other::rwx
[root@host ~]# ll /test
-rwxrwxrwx 1 root root 24 Nov 22 11:13 /test //Run properly.
su [-fmp] [-c command] [-s shell] [--help] [--version] [-] [USER [ARG]]
Options:
⚫ -f or --fast: does not need to read the boot file (such as csh.cshrc). This parameter is
used only for csh or tcsh.
⚫ -m, -p, or --preserve-environment: specifies that environment variables are not
changed when the su command is executed.
⚫ -c command or --command=command: switches to the account USER and restores
to the original user after the command is executed.
⚫ -s shell or --shell=shell: specifies the shell to be executed (such as bash, csh, and
tcsh). The preset value is the USER shell in /etc/passwd.
⚫ --help: shows the description file.
⚫ --version: shows version information.
⚫ --l or --login: After this option is added, it seems that the user logs in. Most
environment variables (such as HOME SHELL USER) are owned by the USER, and
the working directory changes. If the USER is not specified, the value is root.
HCIA-openEuler System Engineer Learning Guide Page 74
sudo -V
sudo -h
sudo -l
sudo -v
sudo -k
sudo -s
sudo -H
sudo [ -b ] [ -p prompt ] [ -u username/#uid] -s
sudo command
Options:
⚫ -V: displays the version number.
⚫ -h: displays a version number and command instructions.
⚫ -l: displays the permissions of the user who executes the sudo command.
⚫ -v: confirms a password after sudo is executed for the first time, or if it is not
executed within N minutes (N is set to 5 by default). If the execution duration
exceeds N minutes, password confirmation is also required.
⚫ -k: forces a user to enter a password when the sudo command is next executed
(regardless of whether the user has run the sudo command within N minutes).
⚫ -b: executes a command in the background.
⚫ -p prompt: changes the password request prompt. %u is replaced with the user's
account name. %h is replaced with a host name.
⚫ -u username/#uid: specifies that if this option is not added, the command is
executed as the root user. If this option is added, the command is executed as the
username user. #uid indicates the user ID of username.
⚫ -s: executes a shell specified by the environment variable SHELL, or a shell specified
in /etc/passwd.
⚫ -H: specifies the environment variable HOME to a home directory of the target user.
(If the -u is not added, the user is the root system administrator.)
⚫ Commands are executed as the system administrator or another user specified by -u.
Examples:
⚫ Run the sudo command.
$ sudo ls
[sudo] password for openEuler:
openEuler is not in the sudoers file. This incident will be reported.
# sudo -u userb ls -l
$ sudo
Edit text as a specific user.
sudo -l
sudo –V
4.4 Quiz
⚫ Create user group it whose GID is 1010, and create user group mg whose GID is
1020.
⚫ Create a user named user1, whose primary group is its private group and secondary
group is it. Create a user named user2, whose primary group is mg and secondary
group is it.
⚫ Set the password validity period of user1 and user2 to 30 days and set the
notification days before password expiration to 3.
⚫ Create a /tmp/test.txt file. The owner of the test file must be root and the owner
group must be it. user1 has the read permission on the file, and user2 has the read
and write permissions on the file.
HCIA-openEuler System Engineer Learning Guide Page 76
rpm [OPTION...]
Main options:
⚫ -i: specifies the software package to be installed.
⚫ -h: uses a number sign (#) to display the process and progress of RPM installation.
⚫ -v: displays details of the installation process.
⚫ -U: upgrades a specified software package.
⚫ -q: queries whether a specified software package has been installed on the system or
queries the content of a specified RPM package.
⚫ -a: views all software packages that have been installed on the system.
⚫ -V: queries the version of an installed software package.
⚫ -c: displays all configuration files.
⚫ -p: queries or validates files in a software package.
⚫ -vh: displays the installation progress.
⚫ -qpl: lists the files in an RPM software package.
⚫ -qpi: displays the description of an RPM software package.
⚫ -qf: searches for the RPM software package to which a specified file belongs.
⚫ -Va: validates all RPM software packages to search for lost files.
⚫ -qa: searches for a file, for example, rpm -qa mysql.
Example:
⚫ Install software.
DNF is a Linux software package management tool that manages RPM software packages.
DNF can query software package information, obtain required software packages from a
specified software repository, install and uninstall the software packages by automatically
processing dependencies, and update the system to the latest available version.
DNF is fully compatible with YUM and provides YUM-compatible command lines and APIs
for extensions and plugins.
To use DNF and run commands in this chapter, you must have the administrator
permissions.
[main]
gpgcheck=1
installonly_limit=3
clean_requirements_on_remove=True
best=True
[repository]
name=repository_name
baseurl=repository_url
Configuration example:
⚫ openEuler provides multiple repo sources for online use. You can obtain the meaning
of each repo source in system installation. The following uses the OS repo source of
the AArch64 architecture as an example. Add the openEuler repo source to the
openEuler_aarch64.repo file as user root as follows:
# vi /etc/yum.repos.d/openEuler_aarch64.repo
[OS]
name=openEuler-$releasever - OS
baseurl=https://repo.openEuler.org/openEuler-20.03-LTS/OS/$basearch/
enabled=1
gpgcheck=1
gpgkey=https://repo.openEuler.org/openEuler-20.03-LTS/OS/$basearch/RPM-GPG-KEY-openEuler
[update]
name=openEuler-$releasever - Update
baseurl=http://repo.openEuler.org/openEuler-20.03-LTS/update/$basearch/
enabled=1
gpgcheck=1
gpgkey=http://repo.openEuler.org/openEuler-20.03-LTS/update/$basearch/RPM-GPG-KEY-openEuler
[extras]
name=openEuler-$releasever - Extras
baseurl=http://repo.openEuler.org/openEuler-20.03-LTS/extras/$basearch/
enabled=0
gpgcheck=1
gpgkey=http://repo.openEuler.org/openEuler-20.03-LTS/extras/$basearch/RPM-GPG-KEY-openEuler
⚫ Notes:
⚫ enabled indicates whether to enable the software source repository. The value can
be 1 or 0. The default value is 1, indicating that the software source repository is
enabled.
⚫ gpgkey is the public key used to verify the signature.
HCIA-openEuler System Engineer Learning Guide Page 81
To display the configuration of a software source, run the following command to query the
corresponding repo ID first:
dnf repolist
Then run the following command, in which repository is the queried repo ID.
You can also use a global regular expression to view the configurations of all matching
sections.
Example:
To list the installed and available RPM packages that match a particular global regular
HCIA-openEuler System Engineer Learning Guide Page 82
Example:
Search example:
You can also install multiple packages simultaneously by appending their names as
arguments. Add strict=False to the /etc/dnf/dnf.conf configuration file and run the dnf
command to add --setopt=strict=0 to the file. To do so, run the following command as
user root:
Example:
⚫ Note: If an RPM package fails to be installed, rectify the fault according to the
HCIA-openEuler System Engineer Learning Guide Page 83
installation prompts, such as those for software package conflicts, file conflicts, and
package missing.
To download non-installed dependencies, add --resolve and run the following command:
Example:
Example:
Example:
To list all package groups and their IDs, run the following command:
Example:
HCIA-openEuler System Engineer Learning Guide Page 84
For example, to install the software package group of Development Tools, run the
following commands:
HCIA-openEuler System Engineer Learning Guide Page 85
For example, to delete the software package group of Development Tools, run the
following commands:
dnf check-update
Example:
Upgrading
To upgrade a single software package, run the following command as user root:
Last metadata expiration check: 0:02:10 ago on Sun 01 Sep 2019 11:30:27 PM CST.
Dependencies Resolved
================================================================================
Package Arch Version Repository Size
================================================================================
Updating:
anaconda-gui aarch64 19.31.123-1.14 updates 461 k
anaconda-core aarch64 19.31.123-1.14 updates 1.4 M
anaconda-tui aarch64 19.31.123-1.14 updates 274 k
anaconda-user-help aarch64 19.31.123-1.14 updates 315 k
anaconda-widgets aarch64 19.31.123-1.14 updates 748 k
Transaction Summary
================================================================================
Upgrade 5 Package
Similarly, to upgrade a software package group, run the following command as user root:
dnf update
Disadvantages:
⚫ The configuration and compilation processes are complex.
⚫ The dependency package may not exist following a new software installation (or
other problems). Consequently, software upgrade is complex and risky.
wget https://www.python.org/ftp/python/3.7.7/Python-3.7.7.tgz
tar -zxvf Python-3.7.7.tgz
cat Python-3.7.7/README.rst
./configure --prefix=/usr/local/Python
make/make clean
make install
mount & automount point management. With systemd, the service control logic and
parallelization are refined.
In systemd, the targets of most actions are units. Units are categorized by the type of
resources they represent and defined in unit configuration files. For example, the
avahi.service unit represents the Avahi daemon and is defined in the avahi.service file.
systemctl status
service network network.service Checks the service running
status status.
For example, to display the status of gdm.service, run the following command.
Starting a Service
To start a service, run the following command as user root:
For example, to start the httpd service, run the following command:
Stopping a Service
To stop a service, run the following command as user root:
For example, to stop the bluetooth service, run the following command:
HCIA-openEuler System Engineer Learning Guide Page 90
Restarting a Service
To restart a service, run the following command as user root:
This command stops the selected service and immediately starts it again. If the selected
service is not running, this command starts it too.
For example, to restart the bluetooth service, run the following command:
Enabling a Service
To configure a service to start automatically at system boot time, run the following
command as user root:
For example, to configure the httpd service to start automatically at system boot time, run
the following command:
Disabling a Service
To prevent a service from starting automatically at system boot time, run the following
command as user root:
For example, to prevent the bluetooth service from starting automatically at system boot
time, run the following command:
systemctl poweroff
To shut down the system without powering it off, run the following command as user root:
systemctl halt
After each of the preceding commands is executed, a message is sent to all login users. If
you do not want systemd to send the message, add the --no-wall parameter. The
command is as follows:
systemctl reboot
After the preceding command is executed, a message is sent to all login users. If you do
not want systemd to send the message, add the --no-wall parameter. The command is as
follows:
systemctl suspend
systemctl hibernate
To suspend and hibernate the system, run the following command as user root:
systemctl hybrid-sleep
HCIA-openEuler System Engineer Learning Guide Page 92
5.6 Quiz
⚫ Download the Nginx source code from the Huawei Cloud Mirrors, and compile and
install Nginx.
⚫ Configure the host firewall service to ensure that the computer can still access the
Nginx home page through a web page after the computer is restarted.
HCIA-openEuler System Engineer Learning Guide Page 93
Basic Concepts
Physical media: physical storage device of the system, such as a hard disk drive (HDD). In
Linux, files such as /dev/hda and /dev/sda are storage units at the lowest layer of the
storage system.
Logical volume: Linux partitions are different from Windows partitions. In Linux, the drive
device name is hdx (x ranges from a to d) as a maximum of four IDE drives are supported.
SCSI, SATA, and USB drives are sdx (x ranges from a to z). A drive can have a maximum
of four primary partitions. Therefore, the primary partitions start from sdb1 to sdb4, and
the logical partitions start from sdb5.
Physical Volume (PV): a drive partition or a device (such as a RAID group) that logically
functions the same function as a drive partition. A PV is a basic logical storage block of
LVM. A PV has a special label that is stored in the second 512-byte sector by default or one
of the first four sectors. This label contains a random unique identifier (UUID) of the PV
and records the size of the block device and the storage location of LVM metadata in the
device.
Volume group (VG): consists of PVs and shields the details of underlying PVs.
Logical volume (LV): A VG can be used only after it is partitioned into LVs. LVs can be
formatted into different file systems and can be directly used after being mounted.
Physical extent (PE): A PV is stored as PEs of the same size. The size of a PE is the same as
that of a logical extent in a VG.
Logical extent (LE): LVs are stored as LEs. The LE sizes of all LVs in a VG are the same.
Through drive partitioning, a drive is divided into multiple logical storage units called
partitions. The system administrator can use different partitions for different functions.
Advantages of drive partitioning:
⚫ The available space of applications or users can be restricted.
⚫ The machine can boot into multiple OSs from different partitions on the same drive.
⚫ OS files are separated from program and user files.
⚫ A separate area can be created for OS virtual memory swapping.
⚫ Drive space usage can be restricted to improve the performance of diagnosis tools
and image backups.
Command (m for help): t # Change the partitions type. In CentOS 8, you do not need to set the
partition type to 8e.
Selected partition 1
Hex code (type L to list all codes): 8e # LVM type
Changed type of partition 'Linux' to 'Linux LVM'.
In the command:
⚫ option: specifies the command option. Common options include:
− -f: forcibly creates a PV without user confirmation.
− -u: specifies the UUID of the device.
− -y: answers yes to all questions.
⚫ devname: specifies the device file name for the PV to be created. If multiple devices
are created, use spaces to separate them.
Example 1: Create /dev/sdb and /dev/sdc as PVs.
In the command:
⚫ option: specifies the command option. Common options include:
− -s: indicates that the output is in short format.
− -m: displays the mapping from the PE to the LE.
⚫ devname: specifies the device file name for the PV to be viewed. If no PV name is
specified, information about all PVs is displayed.
Example: Display the basic information about the physical volume /dev/sdb.
# pvdisplay /dev/sdb
In the command:
⚫ option: specifies the command option. Common options include:
− -u: creates a new UUID.
− -x: indicates whether to allow PE allocation.
⚫ pvname: specifies the name of the device corresponding to the PV whose attributes
are to be modified. To modify attributes in batches, enter multiple device names and
HCIA-openEuler System Engineer Learning Guide Page 99
# pvchange -x n /dev/sdb
In the command:
⚫ option: specifies the command option. Common options include:
− -f: forcibly deletes a PV without user confirmation.
− -y: answers yes to all questions.
⚫ pvname: specifies the name of the device corresponding to the PV to be deleted. To
delete in batches, enter multiple device names and separate them with spaces.
Example: Delete the physical volume /dev/sdb.
In the command:
⚫ option: specifies the command option. Common options include:
− -l: specifies the maximum number of LVs that can be created on the VG.
− -p: specifies the maximum number of PVs that can be added to the VG.
− -s: specifies the PE size of a PV in the VG.
⚫ vgname: specifies the name of the VG to be created.
⚫ pvname: specifies the name of the PV to be added to the VG.
Example: Create VG vg1 and add the PVs /dev/sdb and /dev/sdc to the VG.
In the command:
⚫ option: specifies the command option. Common options include:
− -s: indicates that the output is in short format.
− -A: displays only the attributes of the active VG.
⚫ vgname: specifies the name of the VG to be viewed. If no VG name is specified,
information about all VGs is displayed.
Example: Display the basic information about VG vg1.
In the command:
⚫ option: specifies the command option. Common options include:
− -a: sets the activity status of the VG.
⚫ vgname: specifies the name of the VG whose attributes are to be modified.
Example: Change the status of vg1 to active.
In the command:
⚫ option: specifies the command option. Common options include:
− -d: debugging mode.
− -t: test only.
⚫ vgname: specifies the name of the VG whose capacity is to be expanded.
⚫ pvname: specifies the name of the PV to be added to the VG.
Example, add the physical volume /dev/sdb to the VG vg1.
In the command:
⚫ option: specifies the command parameter option. Common parameter options are as
follows:
− -a: If the PV to be deleted is not specified in the command line, all empty
PVs are deleted.
− --removemissing: deletes the lost physical volumes from the volume
group to restore the volume group to the normal state.
⚫ vgname: specifies the name of the VG whose capacity is to be shrunk.
⚫ pvname: specifies the name of the PV to be deleted from the VG.
Example: Remove the physical volume /dev/sdb2 from the volume group vg1.
In the command:
⚫ option: specifies the command parameter option. Common parameter options are as
follows:
− -f: forcibly deletes a VG without user confirmation.
⚫ vgname: specifies the name of the VG to be deleted.
Example: Delete the VG vg1.
In the command:
⚫ option: specifies the command parameter option. Common parameter options are as
follows:
− -L specifies the size of the LV. The unit can be K, M, G, or T (case-
insensitive).
− -l: specifies the size of the LV (number of LEs).
− -n: specifies the name of the LV to be created.
HCIA-openEuler System Engineer Learning Guide Page 102
In the command:
⚫ option: command parameter option. Common parameter options are as follows:
− -v: displays the mapping from the LE to the PE.
⚫ lvname: specifies the device file corresponding to the LV whose attributes are to be
displayed. If no LV is specified, all LV attributes are displayed.
Note: The device file corresponding to the LV is stored in the VG directory. For example, if
the LV lv1 is created in the VG vg1, the device file corresponding to the LV is /dev/vg1/lv1.
Example: Display the basic information about the LV lv1.
# lvdisplay /dev/vg1/lv1
In the command:
⚫ option: specifies the command parameter option. Common parameter options are as
follows:
− -L specifies the size of the LV. The unit can be K, M, G, or T (case-
insensitive).
− -l: specifies the size of the LV (number of LEs).
− -f: forcibly adjusts the size of an LV without user confirmation.
⚫ lvname: specifies the name of the LV to be adjusted.
Example 1: Add 200 MB space to the LV /dev/vg1/lv1.
HCIA-openEuler System Engineer Learning Guide Page 103
In the command:
⚫ option: specifies the command parameter option. Common parameter options are as
follows:
− -L specifies the size of the LV. The unit can be K, M, G, or T (case-
insensitive).
− -l: specifies the size of the LV (number of LEs).
− -f: forcibly adjusts the size of an LV without user confirmation.
⚫ lvname: specifies the device file of the LV whose space is to be expanded.
Example: Add 100 MB space to the LV /dev/vg1/lv1.
In the command:
⚫ option: specifies the command parameter option. Common parameter options are as
follows:
− -L specifies the size of the LV. The unit can be K, M, G, or T (case-
insensitive).
− -l: specifies the size of the LV (number of LEs).
− -f: forcibly adjusts the size of an LV without user confirmation.
⚫ lvname: specifies the device file of the LV whose space is to be expanded.
Example: Reduce the space of the LV /dev/vg1/lv1 by 100 MB.
In the command:
⚫ option: specifies the command parameter option. Common parameter options are as
follows:
− -f: forcibly deletes an LV without user confirmation.
⚫ vgname: specifies the LV to be deleted.
Example: Delete the LV /dev/vg1/lv1.
In the command:
⚫ option: specifies the command parameter option. Common parameter options are as
follows:
− -t: specifies the type of the Linux file system to be created, such as ext2,
ext3, and ext4. The default type is ext2.
⚫ lvname: specifies the device file name of the LV corresponding to the file system to
be created.
Example: Create an ext4 file system on the LV /dev/vg1/lv1.
In the command:
⚫ lvname: specifies the device file name of the LV to which the file system is to be
HCIA-openEuler System Engineer Learning Guide Page 105
mounted.
⚫ mntpath: specifies the mount path.
Example: Mount the LV /dev/vg1/lv1 to the /mnt/data directory.
Check the printed information. The printed information contains the following information,
in which uuidnumber is a string of digits, indicating the UUID, and fstype indicates the
file system.
Run the vi /etc/fstab command to edit the fstab file and add the following content to the
end of the file:
⚫ Run the following command to remount the file systems corresponding to the
HCIA-openEuler System Engineer Learning Guide Page 106
⚫ Run the following command to query the mounting information about the file
system. The mount directory /mnt/data is used as an example.
⚫ Check the command output. If the command output contains the following
information, the automatic mounting function takes effect:
/dev/vg1/lv1 on /mnt/data
6.3 Quiz
⚫ You need to consider security of LVs. Create an LVM that prevents data loss when a
drive at the bottom layer is damaged.
⚫ Configure an LVM that contains 100 LEs., and the size of each PE is 8 MB.
HCIA-openEuler System Engineer Learning Guide Page 107
7 System Management
*/5 * * * * /root/backupscript.sh
0 1 * * * /root/backupscript.sh
⚫ Run the backupscript.sh script at 3:15 on the first day of each month.
15 3 1 * * /root/backupscript.sh
Operators
Operators are used to specify multiple values for a field. There are three operators available:
⚫ Asterisk (*): This operator specifies all available values for a field. For example, in the
hour field, an asterisk mean every hour; in the month field, an asterisk means every
month.
⚫ Comma (,): This operator specifies a list containing multiple values, for example,
1,5,10,15,20,25.
⚫ Hyphen (-): This operator specifies a value range, for example, 5-15, which is the
same as 5,6,7,8,9,10,11,12,13,14,15 entered using the comma (,) operator.
⚫ Forward slash (/): This operator specifies a step value. For example, 0-23/ can be
used in the hour field to specify that a command is executed every hour. The step
value can also be followed by the asterisk (*) operator. If you want a command line
to be executed every two hours, use */2.
transparently transmits bit streams between adjacent computer nodes and shields
the differences between transmission media and physical devices. The data link layer
does not need to consider the specific transmission media of the network.
Transparent transmission of bit streams indicates that the bit streams transmitted
through the actual circuit do not change. The circuit is invisible for the transmitted
bit streams.
Data Link Layer
Data format: data frames encapsulated from bit streams.
Main functions and connection modes: establishing, canceling, and identifying logical links
at the physical layer, multiplexing links, and checking errors, as well as addressing by using
the hardware address or physical address of the receiving system.
Typical devices: bridges and switches.
⚫ Description: The data link layer is the second layer of the OSI model and is
responsible for establishing and managing links between nodes. The main function
of this layer is to convert error physical channels into error-free data links that can
reliably transmit data frames through various control protocols.
This layer is usually divided into two sublayers: Media Access Control (MAC) and Logical
Link Control (LLC).
⚫ The main task of the MAC sublayer is to solve the problem of multi-user channel
competition in shared network and complete the access control of network media.
⚫ The main task of the LLC sublayer is to establish and maintain network connections,
and perform error check, flow control, and link control.
The data link layer receives bit streams from the physical layer, encapsulates the bit
streams into data frames, and transmits the data frames to the upper layer. Similarly, the
data link layer disassembles the data frames from the upper layer into bit streams and
forwards the bit streams to the physical layer. In addition, it is also responsible for
processing the information of the acknowledgment frame returned by the receive end, to
provide reliable data transmission.
Network Layer
Data format: split and reassembled data packets.
Main functions and connection modes: path selection between different network systems
based on network layer addresses (IP addresses).
Typical devices: gateways and routers.
⚫ Description: The network layer is the third layer of the OSI model and is the most
complex layer in the OSI reference model. Its main task is to select the most
appropriate path for messages or packets through the communication subnet based
on the route selection algorithm. This layer controls information forwarding between
the data link layer and the transport layer, and establishes, maintains, and
terminates network connections. Specifically, data at the data link layer is converted
into data packets and then transmitted from one network device to another through
control such as path selection, segment combination, sequencing, and
incoming/outgoing routing. Generally, the data link layer is used for communication
between nodes on the same network, and the network layer is used for
communication between different subnets. For example, when communication is
HCIA-openEuler System Engineer Learning Guide Page 111
performed between WANs, a route selection problem (that is, there may be multiple
paths between two nodes) is inevitably encountered.
To implement network layer functions, the following problems need to be solved:
⚫ Addressing: Physical addresses (such as MAC addresses) used at the data link layer
solve only the addressing problem within the network. When different subnets
communicate with each other, a unique address is assigned to each device on the
subnet to identify and find the device on the network. Subnets may use different
physical technologies. Therefore, this address should be a logical address (such as an
IP address).
⚫ Exchange: Different information exchange modes are specified. Common switching
technologies include line switching and store-and-forward switching. The store-and-
forward switching includes message switching and packet switching.
⚫ Routing algorithm: When multiple paths exist between the source node and the
destination node, this layer can select the optimal path for data packets through the
network based on the routing algorithm, and transmit the information from the
most appropriate path to the receive end.
⚫ Connection service: Different from the data link layer which controls the traffic
between adjacent nodes on the network, the network layer controls the traffic from
the source node to the destination node. The purpose is to prevent blocking and
detect errors.
Transport Layer
Data format: data segments.
Main functions and connection modes: using an addressing mechanism to identify a specific
application (port number).
Typical devices: terminal devices (such as PCs, mobile phones, and tablets).
⚫ Description: The main task of the lower three layers of the OSI model is data
communication, and the task of the upper three layers is data processing. The
transport layer is the fourth layer of the OSI model. This layer is the interface and
bridge between the communication subnet and the resource subnet. The main task
of this layer is to provide reliable end-to-end error and flow control for users to
ensure correct packet transmission. It shields the details of the lower-layer data
communication from the upper layer, to transparently transmit packets to users.
Common protocols at this layer include Transmission Control Protocol (TCP) in
TCP/IP, Sequenced Packet Exchange (SPX) used by Novell Netware, and Network
Basic Input/Output System (NetBIOS) and NetBIOS Extended User Interface
(NetBEUI) of Microsoft.
The transport layer provides the transmission service between the session layer and the
network layer. The service obtains data from the session layer and segments the data if
necessary. The transport layer then passes the data to the network layer and ensures that
the data can be correctly transmitted to the network layer. Therefore, the transport layer
provides reliable data transmission between two nodes. After the connection between the
two nodes is determined, the transport layer will monitor the connection. In conclusion,
the main functions of the transport layer are described as follows:
⚫ Transmission connection management: establishing, maintaining, and removing
transmission connections. Based on the network layer, the transport layer provides
HCIA-openEuler System Engineer Learning Guide Page 112
⚫ Description: The presentation layer is the sixth layer of the OSI model. It interprets
the commands and data from the application layer, assigns meanings to various
syntaxes, and transmits the syntaxes to the session layer in a certain format. Its main
function is to process the representation of user information, such as encoding, data
format conversion, encryption, and decryption.
The functions of the presentation layer are as follows:
⚫ Data format processing: negotiating and establishing the format for data exchange
to resolve the differences in data format representation between applications.
⚫ Data encoding: converting character sets and numbers. For example, a data type
(integer or real, signed or unsigned, or the like) and a user identifier in a user
program may have different representation manners. Therefore, a function of
converting between different character sets or formats is required between devices.
⚫ Compression and decompression: To reduce the amount of data to be transmitted,
this layer is also responsible for data compression and restoration.
⚫ Data encryption and decryption: improving network security.
Application Layer
Data format: ATPUs.
Main functions and connection modes: an interface between network services and user
applications.
Typical devices: terminal devices (such as PCs, mobile phones, and tablets).
⚫ Description: The application layer is the highest layer of the OSI reference model. It is
the interface between computer users and various applications and the network. It
directly provides services for users and completes the tasks that users want to
complete on the network. Based on the work of the other six layers, it completes the
connection between the application program and the network OS, establishing and
terminating the connection between users, and completing various network services
proposed by network users and various protocols such as supervision, management,
and service required by applications. In addition, this layer coordinates the work
between applications.
The application layer provides the following services and protocols for users: file service,
directory service, file transfer service (FTP), remote login service (Telnet), email service,
printing service, security service, network management service, and database service. The
preceding network services are implemented by different application protocols and
programs at this layer. Different network OSs differ greatly in terms of functions, interfaces,
implementation technologies, hardware support, security and reliability, and application
programming interfaces (APIs). The application layer provides the following functions:
⚫ User interface: The application layer is a direct interface between users and the
network and between applications and the network. It enables users to interact with
the network.
⚫ Implementing various services: Various applications at this layer can implement
various services requested by users.
The seven-layer OSI model is too ideal and is seldom used in actual production
environments. Most applications are designed and implemented based on the TCP/IP
protocol stack. In the seven-layer model, each layer provides a special network function.
HCIA-openEuler System Engineer Learning Guide Page 114
From the perspective of network functions, the lower four layers (physical layer, data link
layer, network layer, and transport layer) mainly provide data transmission and switching
functions, that is, communication between nodes. Layer 4 functions as a bridge between
the upper and lower parts and is the most important part of the entire network architecture.
The upper three layers (session layer, presentation layer, and application layer) mainly
provide information and data processing functions between users and applications. In short,
the lower four layers implement the functions of the communication subnet, and the upper
three layers implement the functions of the resource subnet.
and connections up and active when they are available. The traditional ifcfg type
configuration files are still supported.
OPTIONS
-a, --ask ask for missing parameters
-c, --colors auto|yes|no whether to use colors in output
-e, --escape yes|no escape columns separators in values
-f, --fields <field,...>|all|common specify fields to output
-g, --get-values <field,...>|all|common shortcut for -m tabular -t -f
-h, --help print this help
-m, --mode tabular|multiline output mode
-o, --overview overview mode
-p, --pretty pretty output
-s, --show-secrets allow displaying passwords
-t, --terse terse output
-v, --version show program version
-w, --wait <seconds> set timeout waiting for finishing operations
OBJECT
g[eneral] NetworkManager's general status and operations
n[etworking] overall networking control
r[adio] NetworkManager radio switches
c[onnection] NetworkManager's connections
HCIA-openEuler System Engineer Learning Guide Page 116
status
hostname [<hostname>]
permissions
In the second example above, the help information is related to the general object.
The following shows how to use nmcli.
# You can use the nmcli utility to start and stop any network interface, including the main interface.
Example:
nmcli con up id bond0
nmcli con up id port0
nmcli dev disconnect iface bond0
nmcli dev disconnect iface ens3
The functions of many nmcli commands are implied by their names, but the following
options need to be further explained.
type: connection type.
⚫ Allowed values: adsl, bond, bond-slave, bridge, bridge-slave, bluetooth, cdma,
ethernet, gsm, infiniband, olpc-mesh, team, team-slave, vlan, wifi, wimax.
⚫ Each connection type has type-specific command options. Press Tab to display the
HCIA-openEuler System Engineer Learning Guide Page 117
option list, or view the TYPE_SPECIFIC_OPTIONS list on the nmcli(1) man page. The
type option can be used in the following commands: nmcli connection add and
nmcli connection edit.
⚫ con-name: name assigned to a connection profile.
⚫ If no name is specified, a name is generated in the following format:
type-ifname[-number]
⚫ A connection name is the name of a connection profile and cannot be confused with
the name of a device such as wlan0, ens3, and em1. Although users can name
connections based on interfaces, they are different. A device can have multiple
connection profiles. This is helpful for mobile devices, or for repeatedly switching
network cables between different devices. Instead of editing the profile, create
another profile and apply it to the interface as needed. The id option also refers to
the name of a connection profile.
id: identification string assigned by the user to a connection profile.
⚫ id can be used in the nmcli connection commands to identify a connection. The
NAME field in the command output always denotes the connection ID (name). It
refers to the same connection profile name that the con-name does.
⚫ uuid: unique identification string assigned by the system to a connection profile.
⚫ uuid can be used in the nmcli connection commands to identify a connection.
To use the nmcli tool to configure static routes, you can use either the nmcli command line
or the nmcli interactive editor.
To configure a static route for an existing Ethernet connection using the command line,
run the following command:
This will direct traffic for the 192.168.122.0/24 subnet to the gateway at 10.10.10.1.
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=none
IPADDR=192.168.0.10
PREFIX=24
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=enp4s0static
UUID=08c3a30e-c5e2-4d7b-831f-26c3cdc29293
DEVICE=enp4s0
ONBOOT=yes
To configure a dynamic network for the em1 interface through the ifcfg file, generate an
ifcfg-em1 file in the /etc/sysconfig/network-scripts/ directory. The following is an
example:
DEVICE=em1
BOOTPROTO=dhcp
ONBOOT=yes
To configure an interface to send different host names to the DHCP server, add the
following content to the ifcfg file:
DHCP_HOSTNAME=hostname
HCIA-openEuler System Engineer Learning Guide Page 119
To ignore the impact of the DHCP server on the /etc/resolv.conf file, add the following
content to the ifcfg file:
PEERDNS=no
To configure an interface to use specific DNS servers, set PEERDNS to no and add the
following content to the ifcfg file:
DNS1=ip-address
DNS2=ip-address
ip-address specifies the IP address of the DNS server. In this way, the network service uses
the specified DNS servers to update the /etc/resolv.conf file.
hostnamectl status
To set all the host names on a system, run the following command as the root user:
To set a particular host name, run the following command as the root user:
To set the static host name to host-server, run the following command as the root user:
To enable hostnamectl to detect the change of the static host name, run the following
command the root user to restart the hostnamed service:
7.3.1.5 Threads
A thread is a lightweight process in Linux. A process has an independent memory address
space, but a thread does not. Threads cannot exist independently. They are created by
processes.
⚫ VIRT: total amount of virtual memory used by the task, in KiB. VIRT = SWAP + RES
⚫ SWAP: swapped size of the virtual memory, in KiB.
⚫ RES: non-swapped size of the physical memory, in KiB. RES = CODE + DATA
⚫ CODE: size of the physical memory occupied by the executable code, in KiB.
⚫ DATA: physical memory occupied by non-executable code (data segments + stacks),
in KiB.
⚫ SHR: shared memory size, in KiB.
⚫ nFLT: page errors.
⚫ nDRT: number of pages that have been modified since they were last written to
auxiliary storage.
⚫ S: process state.
⚫ D: uninterruptible sleep.
⚫ R: running.
⚫ S: sleeping.
⚫ T: traced/stopped.
⚫ Z: zombie.
⚫ COMMAND: command name or command line.
⚫ WCHAN: shows the name of the kernel function in which the task is currently
sleeping.
⚫ Flags: task flags. For details, see sched.h.
killall svnserver
7.4 Quiz
⚫ Change the host name to openEuler.
⚫ Add a NIC to the VM. Set the IP address of the NIC to 192.168.101.100/24 and the
gateway to 192.168.101.254. Set the default route of the 192.168.0.0/16 network
segment to pass through the NIC.
⚫ Create a scheduled task to export the current time at 17:30.
⚫ Create a periodic task to back up the /etc directory to the /backup directory at 02:00
every day. The name of the backup directory must be changed to Current date-etc,
for example, 20201202-etc.
⚫ Create a periodic task to check the root partition usage every hour. If the root
partition usage exceeds 50%, an alarm is generated and all data in the /tmp
directory is deleted.
HCIA-openEuler System Engineer Learning Guide Page 128
8 Shell Scripts
languages and can easily process objects such as files and directories. The disadvantage is
that they are usually less efficient than compiled languages. However, it is worthwhile to
use scripting languages. It takes an hour to write a simple script. It may take two days to
compile and implement the same function in C or C++. In addition, the script execution
speed is high enough to ignore its performance problem. Common scripting languages are
AWK, Perl, Python, Ruby, and Shell.
development.
variableName="value"
Note that there is no space between the variable name and the equal sign, which may not
be the same as any programming language you are familiar with. In addition, variable
names must comply with the following rules:
⚫ The first character must be a letter (a-z or A-Z).
⚫ No space is allowed. You can use underscores (_) instead.
⚫ Punctuation is not allowed.
⚫ Keywords in Bash cannot be used. You can run the help command to view the
reserved keywords.
Using Variables
To use a defined variable, you only need to add the dollar sign ($) before the variable
name. Example:
your_name="mozhiyan"
echo $your_name
echo ${your_name}
The braces outside the variable name are optional. They are used to help the interpreter
identify the boundary of the variable. For example:
do
echo "I am good at ${skill}Script"
done
If you do not add braces to the skill variable and write it as echo "I am good at
$skillScript", the interpreter regards $skillScript as a variable (the value is empty). As a
result, the code execution result is not as expected.
It is recommended that all variables be enclosed in braces, which is a good style in
programming.
Redefining Variables
Defined variables can be redefined. Example:
myUrl="http://see.xidian.edu.cn/cpp/linux/"
echo ${myUrl}
myUrl="http://see.xidian.edu.cn/cpp/shell/"
echo ${myUrl}
#!/bin/bash
myUrl="http://see.xidian.edu.cn/cpp/shell/"
readonly myUrl
myUrl="http://see.xidian.edu.cn/cpp/danpianji/"
Deleting Variables
You can run the unset command to delete a variable. Syntax:
unset variable_name
A deleted variable cannot be used again. The unset command cannot delete a read-only
variable.
Example:
#!/bin/sh
myUrl="http://see.xidian.edu.cn/cpp/u/xitong/"
unset myUrl
echo $myUrl
HCIA-openEuler System Engineer Learning Guide Page 133
Location Parameters
The parameters passed to the script when the script is run are called command line
parameters. Command line parameters are represented by $n. For example, $1 indicates
the first parameter, $2 indicates the second parameter, and so on. Example:
cat /root/test.sh
#!/bin/bash
HCIA-openEuler System Engineer Learning Guide Page 134
#!/bin/bash
a=10
echo -e "Value of a is $a \n"
Output:
Value of a is 10
Value of a is 10\n
\ Escape
\a Alert
\b Backspace
\n New line
\r Carriage return
HCIA-openEuler System Engineer Learning Guide Page 135
\t Horizontal tab
\v Vertical tab
Command Replacement
Command replacement means that the shell can run the command first, save the output
temporarily, and output the output in a proper place.
Syntax: `command`
The command is enclosed in back quotes (the key under the Esc key) instead of single
quotation marks.
The following example shows how to save the command output in a variable.
#!/bin/bash
DATE=`date`
echo "Date is $DATE"
USERS=`who | wc -l`
echo "Logged in user are $USERS"
UP=`date ; uptime`
echo "Uptime is $UP"
Output:
Variable Replacement
Variable replacement refers to change the value of a variable based on the variable status
(whether the variable is empty or defined).
The following table describes variable replacement syntax.
Syntax Description
running.
Example:
#!/bin/bash
unset var
echo ${var:+"This is default value"}
echo "3 - Value of var is $var"
var="Prefix"
echo ${var:+"This is default value"}
echo "4 - Value of var is $var"
Output:
3 - Value of var is
This is default value
4 - Value of var is Prefix
Prefix
5 - Value of var is Prefix
#!/bin/sh
a=10
b=20
HCIA-openEuler System Engineer Learning Guide Page 137
val=`expr $a + $b`
echo "a + b : $val"
val=`expr $a - $b`
echo "a - b : $val"
val=`expr $a \* $b`
echo "a * b : $val"
val=`expr $b / $a`
echo "b / a : $val"
val=`expr $b % $a`
echo "b % a : $val"
if [ $a == $b ]
then
echo "a is equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
fi
Output:
a + b : 30
a - b : -10
a * b : 200
b/a:2
b%a:0
a is not equal to b
Note: The condition expression must be enclosed by square brackets and must contain
spaces. For example, [$a==$b] is incorrect and must be written as [ $a == $b ].
Relational Operators
Relational operators support only digits and do not support character strings unless the
value of a character string is a number.
-eq Checks whether two numbers are equal. If yes, true is returned.
Checks whether two numbers are equal. If they are not equal, true is
-ne
returned.
Checks whether the number on the left is greater than that on the
-gt
right. If yes, true is returned.
Checks whether the number on the left is less than that on the right. If
-lt
yes, true is returned.
Checks whether the number on the left is greater than or equal to that
-ge
on the right. If yes, true is returned.
Checks whether the number on the left is less than or equal to that on
-le
the right. If yes, true is returned.
Example:
#!/bin/sh
a=10
b=20
if [ $a -eq $b ]
then
echo "$a -eq $b : a is equal to b"
else
echo "$a -eq $b: a is not equal to b"
fi
if [ $a -ne $b ]
then
echo "$a -ne $b: a is not equal to b"
else
echo "$a -ne $b : a is equal to b"
fi
HCIA-openEuler System Engineer Learning Guide Page 139
if [ $a -gt $b ]
then
echo "$a -gt $b: a is greater than b"
else
echo "$a -gt $b: a is not greater than b"
fi
if [ $a -lt $b ]
then
echo "$a -lt $b: a is less than b"
else
echo "$a -lt $b: a is not less than b"
fi
if [ $a -ge $b ]
then
echo "$a -ge $b: a is greater or equal to b"
else
echo "$a -ge $b: a is not greater or equal to b"
fi
if [ $a -le $b ]
then
echo "$a -le $b: a is less or equal to b"
else
echo "$a -le $b: a is not less or equal to b"
fi
Output:
Boolean Operators
Example:
#!/bin/sh
a=10
b=20
if [ $a != $b ]
then
echo "$a != $b : a is not equal to b"
else
echo "$a != $b: a is equal to b"
fi
Output:
10 != 20 : a is not equal to b
10 -lt 100 -a 20 -gt 15 : returns true
10 -lt 100 -o 20 -gt 100 : returns true
10 -lt 5 -o 20 -gt 100 : returns false
String Operators
Example:
#!/bin/sh
a="abc"
b="efg"
if [ $a = $b ]
then
echo "$a = $b : a is equal to b"
else
echo "$a = $b: a is not equal to b"
fi
HCIA-openEuler System Engineer Learning Guide Page 141
if [ $a != $b ]
then
echo "$a != $b : a is not equal to b"
else
echo "$a != $b: a is equal to b"
fi
if [ -z $a ]
then
echo "-z $a : string length is zero"
else
echo "-z $a : string length is not zero"
fi
if [ -n $a ]
then
echo "-n $a : string length is not zero"
else
echo "-n $a : string length is zero"
fi
if [ $a ]
then
echo "$a : string is not empty"
else
echo "$a : string is empty"
fi
Output:
#!/bin/sh
file="/var/www/tutorialspoint/unix/test.sh"
if [ -r $file ]
then
echo "File has read access"
else
echo "File does not have read access"
fi
if [ -w $file ]
then
echo "File has write permission"
else
echo "File does not have write permission"
fi
if [ -x $file ]
then
echo "File has execute permission"
else
echo "File does not have execute permission"
fi
if [ -f $file ]
then
echo "File is an ordinary file"
else
echo "This is special file"
fi
if [ -d $file ]
then
echo "File is a directory"
else
echo "This is not a directory"
fi
if [ -s $file ]
then
echo "File size is zero"
else
HCIA-openEuler System Engineer Learning Guide Page 143
if [ -e $file ]
then
echo "File exists"
else
echo "File does not exist"
fi
Output:
Checks whether the SGID bit is set for a file. If yes, [ -g $file ] returns
-g file
true is returned. false.
Checks whether a sticky bit is set for a file. If yes, [ -k $file ] returns
-k file
true is returned. false.
Checks whether the SUID bit is set for a file. If yes, [ -u $file ] returns
-u file
true is returned. false.
HCIA-openEuler System Engineer Learning Guide Page 144
str='this is a string'
Restrictions: Any characters enclosed in single quotation marks are output without any
changes. Variables in the string enclosed in single quotation marks are invalid. Strings
enclosed in single quotation marks cannot contain extra single quotation marks (even if
escape characters are used for the single quotation marks).
Double Quotation Marks
your_name='openEuler'
str="Hello, I know your are \"$your_name\"! \n"
Advantages: Strings enclosed in double quotation marks can contain variables and support
escape characters.
Concatenate strings.
your_name="openEuler"
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
string="abcd"
echo ${#string} #Outputs 4.
Extract substrings.
if [ expression ]
then
Statement(s) to be executed if expression is true
fi
if...else...fi
Syntax
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
fi
if...elif...else...fi
Syntax
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
HCIA-openEuler System Engineer Learning Guide Page 146
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi
case value in
Pattern 1
command1
command2
command3
;;
Pattern 2
command1
command2
command3
;;
*)
command1
command2
command3
;;
esac
The patterns of the case statement are shown in the above code. The value must be
followed by the keyword in, and each pattern must end with a right parenthesis. The value
can be a variable or a constant. If the value complies with a pattern, all commands in front
of ;; will be executed. Similar to the break in other languages, ;; means to jump to the end
of the entire case statement.
The value tries to match each pattern. Once a pattern is matched, other patterns will not
be continued after the corresponding commands of the matched pattern are executed. If
no pattern is matched, the asterisk (*) is used to capture the value and the commands
followed will be executed.
commandN
done
A list is a sequence of values (digits, strings, etc.) separated by space. Each time a loop
occurs, the next value in the list is assigned to the variable. The in list is optional. If it is not
used, the for loop uses the location parameter of the command line.
Output the numbers in the current list in ascending order.
for loop in 1 2 3 4 5
do
echo "The value is: $loop"
done
Output:
Output:
This is a string
Display the files whose names start with .bash in the home directory.
#!/bin/bash
Output:
/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc
while command
do
Statement(s) to be executed if command is true
done
After the command is executed, the control returns to the beginning of the loop until the
test condition is false.
#!/bin/bash
a=3
b=$1
if [ $a == $b ]
then
echo "You win!"
else
echo "Please guess again."
fi
while + if
⚫ Check whether the location parameter is a file. If yes, the file content is displayed. If
no, a message is displayed.
#!/bin/bash
while [ $1 ]
do
if [ -f $1 ]
then echo "display:$1"
cat $1
else echo "$1 is not a file name"
fi
shift
done
for
⚫ Read each line of information from the file and output the information.
#!/bin/bash
for Name in $(cat ./namefile)
do
echo $Name
done
case
⚫ Input data from the keyboard and selectively output data based on the input data.
HCIA-openEuler System Engineer Learning Guide Page 149
#!/bin/bash
echo 'Input a number between 1 to 4'
printf 'Your number is:\n'
read aNum
case $aNum in
1) echo 'You select 1'
;;
2) echo 'You select 2'
;;
3) echo 'You select 3'
;;
4) echo 'You select 4'
;;
*) echo 'You do not select a number between 1 to 4'
;;
esac
8.3 Quiz
⚫ Create a userlist file and write 10 user names (a user name per line) in the file.
Create a useradd.sh script that is able to automatically create users written in the
userlist file, with the password openEuler12#$. The home directory of the new user
contains a hello.txt file, and the owner and group of the file is the user.
HCIA-openEuler System Engineer Learning Guide Page 156
⚫ samba-common: provides data used by both the server and the client, including the
main configuration file smb.conf and the syntax check command testparm.
In addition, there is information about log files, including the following parameters:
log file = The log file. The file name can contain variables.
max log size = Maximum size of the log file, in KB. When this value is exceeded, the earliest logs are
HCIA-openEuler System Engineer Learning Guide Page 158
rotated.
The shared resources are mainly related to file permissions of Linux. Therefore, the
parameters in the file are related to permissions.
smb.conf Variables
To simplify configuration, Samba provides the following variables:
⚫ %S: indicates the current item value.
⚫ %m: indicates the NetBIOS host name of the client.
⚫ %M: indicates the Internet host name of the client.
⚫ %L: indicates the NetBIOS host name of the Samba host.
⚫ %H: indicates the home directory of the user.
⚫ %U: indicates the name of the current login user.
⚫ %g: indicates the group name of the login user.
⚫ %h: indicates the host name of the current Samba host.
⚫ %I: indicates the IP address of the client.
⚫ %T: current date and time
⚫ Start the Samba service and enable it to start upon system startup.
⚫ Check the listening status of the server. The server is listening on TCP ports 139 and
445.
⚫ Set the Samba server password for the smb user, for example, Huawei12#$.
printing = cups
printcap name = cups
load printers = yes
cups options = raw
⚫ Add the share directory for public sharing and allow anonymous access to the
directory.
[share]
comment = share
path = /var/share
guest ok = yes
writeable = yes
browseable = yes
⚫ Add the smb directory and allow the share access user to access the directory.
[smb]
comment = smb
path = /var/smb
write list = smb
browseable = yes
writeable = yes
read list = smb
valid users = smb
create mask = 0777
directory mask = 0777
⚫ Save the configuration and exit. Then, restart the Samba service.
⚫ Now, you can use Windows or other Linux systems with the CIFS access client
installed to access the shared resources.
HCIA-openEuler System Engineer Learning Guide Page 161
9.3 Quiz
⚫ How do you configure Samba to ensure privacy when a user accesses shared
resources?
Tip: You can configure the home directory.
HCIA-openEuler System Engineer Learning Guide Page 162
10 Reference
https://www.openeuler.org/en/
https://www.runoob.com/linux/linux-tutorial.html
https://www.cnblogs.com/xiangsikai/p/10683209.html
http://cn.linux.vbird.org/linux_server/0370samba.php
https://wiki.jikexueyuan.com/project/shell-tutorial/
https://juejin.cn/post/6844903938823553031