100% found this document useful (2 votes)
2K views1,130 pages

Linux LPIC-1 Study Guide PDF

Uploaded by

GiàNam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
2K views1,130 pages

Linux LPIC-1 Study Guide PDF

Uploaded by

GiàNam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1130

This page is blank.

Table of Contents
Topic 1: Performing Basic Linux Tasks ........................................................................................ 1
Identify the Linux Design Philosophy................................................................................................... 3
Enter Shell Commands .......................................................................................................................20
Get Help with Linux............................................................................................................................37
Topic 2: Managing Users and Groups........................................................................................51
Assume Superuser Privileges..............................................................................................................53
Create, Modify, and Delete Users.......................................................................................................67
Create, Modify, and Delete Groups ....................................................................................................83
Query Users and Groups ....................................................................................................................93
Configure Account Profiles ...............................................................................................................107
Topic 3: Managing Permissions and Ownership ......................................................................121
Modify File and Directory Permissions .............................................................................................123
Modify File and Directory Ownership ...............................................................................................140
Configure Special Permissions and Attributes...................................................................................146
Troubleshoot Permissions Issues......................................................................................................164
Topic 4: Managing Storage.....................................................................................................174
Create Partitions ..............................................................................................................................176
Manage Logical Volumes..................................................................................................................208
Mount File Systems..........................................................................................................................222
Manage File Systems........................................................................................................................231
Navigate the Linux Directory Structure.............................................................................................249
Troubleshoot Storage Issues ............................................................................................................265
Topic 5: Managing Files and Directories .................................................................................286
Create and Edit Text Files .................................................................................................................288
Search for Files.................................................................................................................................311
Perform Operations on Files and Directories ....................................................................................322
Process Text Files .............................................................................................................................337
Manipulate File Output ....................................................................................................................364
Topic 6: Managing Kernel Modules.........................................................................................380
Explore the Linux Kernel ..................................................................................................................382
Install and Configure Kernel Modules...............................................................................................395
Monitor Kernel Modules ..................................................................................................................408
Topic 7: Managing the Linux Boot Process ..............................................................................417

Linux LPIC-1 I
Configure Linux Boot Components ...................................................................................................419
Configure GRUB 2 ............................................................................................................................442
Topic 8: Managing System Components .................................................................................459
Configure Localization Options.........................................................................................................461
Configure GUIs .................................................................................................................................476
Manage Services ..............................................................................................................................498
Troubleshoot Process Issues.............................................................................................................519
Troubleshoot CPU and Memory Issues .............................................................................................547
Topic 9: Managing Devices .....................................................................................................570
Identify the Types of Linux Devices ..................................................................................................572
Configure Devices ............................................................................................................................588
Monitor Devices...............................................................................................................................603
Troubleshoot Hardware Issues .........................................................................................................614
Topic 10: Managing Networking.............................................................................................629
Identify TCP/IP Fundamentals ..........................................................................................................631
Identify Linux Server Roles ...............................................................................................................648
Connect to a Network ......................................................................................................................669
Configure DHCP and DNS Client Services ..........................................................................................694
Configure Cloud and Virtualization Technologies..............................................................................710
Troubleshoot Networking Issues ......................................................................................................725
Topic 11: Managing Packages and Software...........................................................................759
Identify Package Managers ..............................................................................................................761
Manage RPM Packages with YUM ....................................................................................................771
Manage Debian Packages with APT..................................................................................................783
Configure Repositories .....................................................................................................................790
Acquire Software .............................................................................................................................798
Build Software from Source Code.....................................................................................................806
Troubleshoot Software Dependency Issues ......................................................................................815
Topic 12: Securing Linux Systems ............................................................................................823
Implement Cybersecurity Best Practices...........................................................................................825
Implement Identity and Access Management Methods....................................................................847
Configure SELinux or AppArmor .......................................................................................................869
Configure Firewalls ..........................................................................................................................885
Implement Logging Services .............................................................................................................908
Back Up, Restore, and Verify Data....................................................................................................924

Linux LPIC-1 II
Topic 13: Working with Bash Scripts .......................................................................................955
Customize the Bash Shell Environment ............................................................................................957
Identify Scripting and Programming Fundamentals ..........................................................................977
Write and Execute a Simple Bash Script............................................................................................989
Incorporate Control Statements in Bash Scripts..............................................................................1006
Topic 14: Automating Tasks..................................................................................................1028
Schedule Jobs.................................................................................................................................1030
Implement Version Control Using Git .............................................................................................1042
Identify Orchestration Concepts.....................................................................................................1052
Topic 15: Installing Linux ......................................................................................................1064
Prepare for Linux Installation .........................................................................................................1066
Perform the Installation .................................................................................................................1082

Linux LPIC-1 III


This page is blank.
There is a great amount of depth to the Linux® operating system. Rather than dive right into the
specifics, you'll do well to get a high-level overview of what it is you're about to work with.
Also, by operating Linux in some fundamental ways, you'll be better prepared for the journey
ahead.

Linux LPIC-1 1
In this topic, you will:

• Identify the high-level design concepts that make up the Linux operating system.
• Use fundamental Linux shell commands to get started with the command-line interface (CLI).
• Use various resources to find help on the Linux operating system.

Linux LPIC-1 2
Linux LPIC-1 3
OPEN SOURCE SOFTWARE
Open source software (OSS) refers to computer code that any user is permitted to view, copy,
and modify for any reason, as well as distribute to anyone. Users are granted these rights when
the author of the software releases the source code under one of several open source licenses.
The opposite of OSS is proprietary software— software that is released under a license that
imposes restrictions on one or more of the rights just mentioned (view, copy, modify,
distribute).
OSS provides several advantages to users, administrators, and programmers alike. Perhaps the
most important element of OSS is that it encourages the ongoing improvement of software in a
collaborative, community-driven environment. Individuals or groups of developers may build
upon another developer's work to create enhanced or customized software, all while avoiding
legal issues. There are many examples of OSS, one of which is the Linux kernel.

Linux LPIC-1 4
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 5
FREE SOFTWARE VS. OPEN SOURCE SOFTWARE
The term free so=ware is oNen used interchangeably with OSS, and both share a great deal of
overlap. However, some draw a disPncPon between the two. Richard Stallman, the founder of
the free soNware movement, argues that the terms share different values—in his words, "Open
source is a development methodology; free soNware is a social movement." In other words,
OSS is most concerned with fostering open collaboraPon, whereas free soNware is most
concerned with upholding users' rights. Note that "free" is being used in the sense of freedom,
not in the sense of having no monetary cost.
In an aUempt to resolve this terminology dispute, some developers have adopted the term free
and open source so=ware (FOSS) to describe any project that embodies the values of both
movements.

Linux LPIC-1 6
FREE AND OPEN SOURCE LICENSES
There are several FOSS licenses that a developer can release their soNware under. These
licenses may differ when it comes to addiPonal restricPons or compaPbility with other licenses.
The following are some examples of FOSS licenses:
• Apache License
• Berkeley SoNware DistribuPon (BSD) license family
• CreaPve Commons Zero (CC0)
• Eclipse Public License (EPL)
• GNU General Public License (GPL)
• MassachuseUs InsPtute of Technology (MIT) License
• Mozilla Public License (MPL

Linux LPIC-1 7
THE GNU PROJECT
The GNU Project is a free software project led by Richard Stallman. Announced in 1983, it was
the first project of its kind, and effectively launched the free software movement. The GNU
Project's goal is to create an operating system that is composed of entirely free software. By
the early 1990s, the GNU Project had not completed a full OS, but had created several
programs. Stallman wrote much of the GNU software himself, including the GNU C Compiler
(GCC) and the Emacs text editor. Later, several programmers worked together to develop more
utilities that are compatible with GNU software.
Stallman chose the recursive acronym "GNU's Not Unix" to show that GNU software was
similar in design to the proprietary Unix operating system, but did not actually contain any Unix
code.

Linux LPIC-1 8
FREE SOFTWARE FOUNDATION AND THE GNU GPL
Shortly after kicking off the GNU Project, Stallman founded the nonprofit Free Software
Foundation (FSF) to promote the philosophy behind free software. Stallman and the FSF
created the GNU General Public License (GPL) to support the GNU Project. One of the
requirements of the GPL is that any derivative of a GPL work must also be distributed under
that same license—a concept known as copyleft.

THE UNIX PHILOSOPHY


Because GNU software is based on the design of Unix®, it tends to conform to the Unix
philosophy. The Unix philosophy is a set of best practices and approaches to software
development that emphasize simplicity and modularity. This philosophy was created by the
lead developers of the Unix operating system and has been summarized in many ways. Some of
the key high-level points include:
• Do one thing and do it well. Rather than writing a monolithic software tool that
accomplishes a variety of disparate tasks, write individual tools that fulfill a specific function.
• Worse is better. Software that is limited in functionality ("worse") is often preferable
("better") because it tends to be easier to use and maintain.
• Support interactivity. Write individual tools so that they work well with other tools.
• Handle input/output streams. Feeding one tool's output as input into another tool is a
universally desirable feature.

Linux LPIC-1 9
THE LINUX OPERATING SYSTEM FAMILY
Linux is a family of operaPng systems based on the Linux kernel, the central core of the OS that
manages all components in the system. The Linux kernel was developed by Finnish programmer
Linus Torvalds in 1991, while he was a student at the University of Helsinki.

FOSS, the GNU Project, and the Unix design philosophy have all played an important role in the
development of Linux. Torvalds released the Linux kernel under version 2 of the GPL. Most
distribuPons of Linux add GNU soNware wriUen by Stallman and other free soNware
components on top of the Linux kernel. In other words, Linux is the first complete operaPng
system family to qualify as FOSS, and like GNU soNware, it follows the principles of simplicity
and modularity set forth in the Unix design philosophy.

Linux LPIC-1 10
Fundamentally, Linux is a combinaPon of the Linux kernel and GNU soNware.

GNU/LINUX
Because most members of the Linux OS family incorporate GNU uPliPes along with the Linux
kernel, the FSF prefers to call the OS family "GNU/Linux" rather than just "Linux." This supports
the idea that the Linux kernel was the "missing piece" to the GNU Project, and gives credit to
GNU for its tools and the free soNware movement itself. However, Torvalds and others disagree
with this assessment, and the name "Linux" is by far the most common way of referring to the
OS family.

Linux LPIC-1 11
ADVANTAGES OF USING LINUX
To summarize, the following are some of the major advantages of using Linux:
• Its FOSS nature promotes transparency.
• Its design emphasizes simplicity and modularity.
• It is highly customizable.
• It is highly reliable and stable.
• It has strong integration with several major programming languages, like C, C++, Python®,
Ruby, etc.
• It places an emphasis on security and privacy.
• Most distributions are free of monetary cost.
• It has a passionate community willing to provide support.

Linux LPIC-1 12
DISADVANTAGES OF USING LINUX
No system is perfect, including Linux. The following are some potential disadvantages:
• It has a sharper learning curve than other general purpose operating systems like Windows®
and macOS®.
• Desktop software is not as well-supported as it is in other operating systems like Windows
and macOS.
• There is no definitive or official version, which can be confusing to new users.
• With some exceptions, there is no official vendor-provided support.

Linux LPIC-1 13
LINUX DISTRIBUTIONS
As a family of operaPng systems, there is no official OS called "Linux." Instead, there are disPnct
members of the family called Linux distribuTons, or distros. All Linux distros are based on the
Linux kernel; they differ primarily in what addiPonal soNware they add on top of the kernel to
create a fully funcPonal OS, as well as the version of the kernel they run. There are also
differences in community, rate of release, and other factors. Choosing a distribuPon is a maUer
of idenPfying which one most closely aligns with your business needs as well as your familiarity
with its tools.

Linux LPIC-1 14
LIST OF LINUX DISTRIBUTIONS
There are hundreds of distros available. The above table includes some of the most historic
and/or popular ones.

Linux LPIC-1 15
MORE ON CENTOS
The CentOS Linux distribution is a stable, predictable, manageable, and reproducible platform
derived from the sources of RHEL. CentOS is maintained by the CentOS Project, a community-
driven free software effort that has its own governing board. The members of the CentOS
Project work independently of the RHEL team. However, CentOS benefits from Red Hat's
ongoing contributions and investment, and the CentOS trademark is owned by Red Hat.

This course uses CentOS because it provides a free enterprise-class computing platform that
aims to be functionally compatible with the upstream product (RHEL) that it derives from.
CentOS does not contain Red Hat's product or certifications, although it is built from the same
sources as the upstream enterprise products. More details about this are available in the
CentOS FAQ here: https://wiki.centos.org/FAQ/ General.

For production environments, the licensed and fully supported RHEL product is recommended.

Linux LPIC-1 16
USES FOR LINUX
One of the main advantages of Linux is that it is highly extensible. As a result, Linux has been
applied to many different computing roles. The above table describes these roles.

Linux LPIC-1 17
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 18
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 19
Linux LPIC-1 20
The design of the Linux operating system emphasizes a particular kind of user interface; one in
which the user types text commands into a prompt in order to interact with the system. This
differs from the primarily visual operating systems like Windows and macOS. Therefore, one of
the most crucial skills in Linux administration is becoming comfortable at entering text
commands. In this topic, you'll enter a few basic commands to become more familiar with the
process.

THE CLI
The command-line interface (CLI) is a text-based interface between the user and the operating
system that accepts input in the form of commands. The CLI presents a command prompt to
the user, and the user enters a command to interact with the system in a variety of ways.
Working at the command-line is an important tool in any administrator's arsenal. Developers
and administrators often use the CLI, whereas regular users will typically rely on a graphical
user interface (GUI).

Comfort at the command-line is essential for administrators. Command-line administration is


an assumed skill in Linux. The GUI is not a required component of Linux. In fact, Linux includes
many GUIs. Any or none of those may be installed on the system. Assuming you want to
maximize the use of hardware for the system's specified purpose, you can perform all
administration at the CLI.

Linux LPIC-1 21
CLI ADVANTAGES AND CHALLENGES
Some advantages to using the CLI include:
• It's faster for the system to process.
• It's faster for administrators to enter informaPon.
• Commands can be stored in text files called scripts that you can execute with one
• command, resulPng in a long series of acPviPes by the system.
• Scripts can be scheduled to execute on a regular basis.
• AddiPonal opPons are available in the CLI that may not be present in the GUI.

Likewise, there are some challenges to using the CLI:


• It's more difficult to learn than a GUI.
• Commands have many opPons and are not always consistent.
• It's oNen mistakenly thought of as legacy.
• There are many command-line environments among the Linux, Unix, macOS, and
• Windows plajorms.

Linux LPIC-1 22
SHELLS
A shell envelops the core portion of the operating system—referred to as the kernel—
permitting the user to pass commands and information to the kernel. The kernel is also able to
respond back to the user via the shell. The shell can be thought of as an interpreter between
human and kernel languages. Linux users issue commands in the shell to tell the operating
system what to do. The operating system responds back to the user with the results.

Linux LPIC-1 23
A shell can be implemented as either a CLI or a graphical user interface (GUI). The following
table lists some common CLI-based shells that are used in Linux.

Shell Description

This is the original Unix shell that is still available on Linux systems,
Bourne shell (sh)
though not widely used.
This is the default Linux shell and a replacement for the Bourne
Bash (bash)
shell. Its full name comes from the term Bourne-again shell.
This shell is based on the C programming language and was
C shell (csh)
designed to support C language development environments.
KornShell (ksh) This shell uses the features of the C shell with the syntax of the
Bourne shell. It is common on Unix systems.

Linux LPIC-1 24
MORE ON BASH
As a Linux user, it is essential to be comfortable using the default Bash shell. Virtually every
Linux distribution will use this shell as the translator between the user and the system. It is
possible to install and use other shells in Linux if users are more comfortable with them, but
the default will almost always be Bash.
Some characteristics of Bash include:
• It's been around for a very long time, so it is well documented with many existing scripts.
• It's commonly used in Linux and macOS (where it is also the default) and with various other
operating systems.
• It's not always consistent, since there have been a great many modifications by various
groups since its creation.
• It includes history and tab completion features.

BASH SYNTAX
Command-line administration includes the idea of "syntax," or the proper way of structuring a
command and any supporting information. The many CLIs have their own unique ways of
entering information. You need to understand this syntax to be able to effectively communicate
with the interface.
Bash shell syntax contains three main components: the command, options to modify the
command, and an argument for the command to act upon. It is common for new users to Bash
to forget the spaces between the three components.
The basic syntax of Bash is therefore: command [-options] [arguments]
The above table lists an example of each type of basic syntax format using the ls command.

Linux LPIC-1 25
The ls -la command displaying the list of files in the /usr directory.

Linux LPIC-1 26
ERRORS
If you fail to enter a command in the proper syntax, Bash will return an error. Typically, these
error messages are descriptive and will help you to understand what Bash expects. For
"command not found" errors, check for typos in the command. For "no such file or directory"
errors, check for typos in the directory, file, or file path names.

BASIC BASH COMMANDS


There are several commands that are important for accomplishing basic tasks. Many of these
commands will be covered in greater depth throughout the course but are included in this topic
to provide basic command vocabulary and to get you started with hands-on practice at the
Bash shell.

Linux LPIC-1 27
FILE VIEWING COMMANDS
Linux system configurations are held in text files, so you'll need to be able to view the contents
of those files.

The cat command is used to view the contents of a file without the option to edit that file. An
example of using cat is cat file1 to show the contents of file1 on the screen.

The less command is used to view the contents of a file when those contents won't fit entirely
on one screen. This command breaks the content output into pages that you can scroll through
at the CLI. An example of using less is less file1 to break the contents of file1 into multiple
pages when its contents are lengthy enough to go past a single screen. Press Page Up and Page
Down to scroll screens, and press q to exit the command.

Linux LPIC-1 28
FILE EDITING COMMANDS
Just as you'll need to view the contents of text files, you'll also need to edit them.

vim
1. vim file1 to open file.
2. Press i to insert.
3. Press Esc to leave insert.
4. :wq to save/quit.

nano
1. nano file1 to open file.
2. Enter text directly.
3. Press Ctrl+O to save.
4. Press Ctrl+X to quit.

gedit
1. Select Applications→Accessories→Text Editor.
2. Enter text directly.
3. Use menu to save/quit.

Linux LPIC-1 29
POWER MANAGEMENT COMMANDS
Periodically, it may be necessary to reboot or shut down the system. There are several
commands to accomplish this, but for now you will focus on the shutdown command. Some
examples of the shutdown command include:
• shutdown -h now shuts down the system with no time delay.
• shutdown -h -t 90 shuts down the system in 90 seconds.
• shutdown -r now reboots the system with no time delay.

THE sleep COMMAND


The sleep command is used to pause system activities for a specified time.
The command sleep {seconds} hangs up the prompt for the number of seconds specified.

Linux LPIC-1 30
SUPERUSER COMMANDS
In Linux, the user with administrator credentials is the superuser. The superuser is typically
named root. It is generally a bad practice to log onto the system as the superuser, and you
should get in the habit of logging in with a non-privileged account. However, there will be times
when you need to assume the privileges of the superuser in order to perform an administrative
task.
The su - command ("substitute user") switches user credentials, and su - root switches
credentials to the root user. The system will prompt you to enter the root user's password for
authorization purposes. Once you are logged in as root, you will be able to perform tasks that
you were previously unable to.

Linux LPIC-1 31
SHELL HISTORY
The Bash shell keeps a history file of all commands entered. You can reference this file and
repeat commands, increasing efficiency and consistency of entered commands.

Examples of using shell history include:


• The history command outputs the most recently entered commands in a list format.
• The Up Arrow and Down Arrow keys cycle through the command history. Press Enter to
reissue the desired command from the history.

Linux LPIC-1 32
TAB COMPLETION
The Bash shell supports tab completion, enabling users to type in enough of a command, file
name, or directory name to be unique, then filling in the remainder of the entry. This feature
reduces typographical errors and speeds up the entering of commands.

Examples of using tab completion include:


• Typing his and pressing Tab will automatically fill the rest of the history command.
• Typing cd /home/user1/Aug and pressing Tab will automatically fill the directory path to cd
/home/user1/AugustProjects assuming such a directory already exists.

Linux LPIC-1 33
SHELL TIPS AND TRICKS
While the command-line interface can be intimidating, there are several ways of making it
easier to work with and more efficient. As you get more comfortable with Bash, you may find
you prefer working at the CLI much of the time.

Here are a few tips to help make working at the command-line easier:
• Tab completion: Get in the habit of using tab completion for speed and to minimize typos.
• Use history instead of re-writing long commands: When you make a typographical error in a
command or file name, do not manually re-type the entire line. Repeat the line with the
mistake by hitting the Up Arrow key one time, and then use the Left and Right Arrow keys to
move to the mistake so that you can correct it.
• Read the command backward: When troubleshooting your commands, start from the right
and read to the left. This method makes it a great deal easier to notice missing or duplicate
characters.
• Clear the screen: Enter the clear command to clear the CLI of all text. This is useful when
you're starting a new task and want to eliminate any distracting information from past
command entries.

Linux LPIC-1 34
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 35
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 36
Linux LPIC-1 37
Now that you are familiar with the Linux shell, you may want to begin using commands in your
system. However, there will be times when you need assistance with the various available
commands. In this topic, you will identify the help and support options offered by Linux.

LINUX DOCUMENTATION
Documentation is a necessity in any major computing project, and Linux is no different.
Documentation helps users of the Linux operating system, no matter their role or experience
level, to perform a wide range of activities and resolve a wide range of issues. However, just like
there is not one official form of Linux, neither is there a single, authoritative source of
documentation. Documentation is spread across multiple sources that appear in multiple
forms, each one suited to a particular context.
Some of major sources of Linux documentation include:
• Manual pages
• Built-in help commands
• Online documentation projects
• Usenet newsgroups
• Internet mailing lists
• Question and answer websites
• Forums and social media
• Books and other print resources

Linux LPIC-1 38
MANUAL PAGES
Linux manual pages, or man pages, contain the complete documentation that is specific to
each Linux command. The man pages are available on Linux systems by default. The man page
for a specific command is displayed using the man command. They usually include information
such as the name of the command, its syntax, a description of its purpose, the options it
supports, examples of common usage of the command, and a list of related commands.

Man pages are perhaps the most immediate source of help available when you need to learn
more about what a command does or how to operate it. They are especially useful in situations
where Internet access is not available. However, man pages can be difficult to parse for
someone not familiar with how they're formatted.

Linux LPIC-1 39
SYNTAX
The syntax of the man command is man {command}

SYNOPSIS FORMAT
Most of the components of a man page are self-explanatory, but the SYNOPSIS component can
be somewhat confusing to new users. This part of a man page provides the syntax of the
command along with some example use cases. These use cases are formatted as such:
• bold text should be typed exactly as shown.
• italic text should be replaced with the appropriate argument. Note that this may be
formatted differently on certain systems, like underlined text or colored text.
• [-abc] indicates that all arguments within the brackets are optional.
• -a|-b indicates that the arguments on either side of the pipe (|) cannot be used together.
• italic text with ... (ellipsis) after it indicates that the argument can be repeated.
• [italic] text with ... after it indicates that the entire expression within the brackets can be
repeated.

Linux LPIC-1 40
man COMMAND OPTIONS
The man command supports different options. Some of the frequently used options are listed
above.

Linux LPIC-1 41
MAN PAGE SECTIONS
Man pages for commands may be listed under one or more sections. A section defines what
category the command belongs to. When a command has more than one section listed, it
means that documentation for the same command is available from more than one source.
These sections are identified by the number displayed beside the command; for example, fsck
(8)
Various man page sections are provided in the above table

Linux LPIC-1 42
MAN PAGES NAVIGATION
You can navigate through Linux man pages using a number of keys. These keys are described in
the above table.

Linux LPIC-1 43
OTHER BUILT-IN HELP OPTIONS
In addition to the man command, Linux offers other built-in options for help.

Help Option Description


• Searches NAME section of man pages based on keyword.
apropos • Helps you find the right command to use for a certain task.
• Syntax: apropos {keyword}
• Displays brief description of given command.
whatis • Helps you figure out what a command does.
• Syntax: whatis {command}
• Displays info page of command.
• Similar to man pages, with some improvements.
info
• Not as widely adopted as man pages.
• Syntax: info {command}
• Displays quick summary of command usage and arguments.
--help
• Syntax: <command> --help
• Directory of documentation for software packages.
/usr/share/doc/
• Includes author, licensing, installation, README, etc.

Linux LPIC-1 44
ONLINE DOCUMENTATION
The Internet is one of the best places to go to for help with Linux. There is not one single online
source that is necessarily better than the others; the choice often comes down to what type of
help you're looking for. The above table lists some of the best online sources for Linux
documentation.

Linux LPIC-1 45
The online documentation for the RHEL 7 distribution.

Linux LPIC-1 46
INTERACTIVE HELP
Online documentation is a quick and easy reference point, but it's not always the best source
for answering your Linux questions, especially if those questions are complex or apply to
unconventional scenarios. These questions are often best answered by interacting with other
people directly, whether in real-time or asynchronously. The above table lists some of the
major sources of interactive help on the Internet for Linux issues.

Linux LPIC-1 47
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 48
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 49
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 50
Now that you've performed some basic Linux® tasks, you're ready to start diving deeper into
configuring the operating system for use by yourself and others. Before users can take
advantage of Linux, you'll need to create and manage accounts for them. So, in this topic, you
will manage user and group accounts.

Linux LPIC-1 51
In this topic, you will:

• Assume superuser privileges when necessary.


• Create, modify, and delete user accounts.
• Create, modify, and delete group accounts.
• Query user and group accounts.
• Configure user account profiles.

Linux LPIC-1 52
Linux LPIC-1 53
USER ACCOUNTS
Accounts are objects that represent users and services to Linux. If these entities are
represented by an account, then that account can be managed. User accounts represent
identities that authenticate to the system and can use authentication credentials to do specific
tasks. User information includes group memberships.

Individuals who will be using the Linux computer should have their own unique user accounts.
Administrators will use these accounts to control the user's access to files, directories, and
commands on the system. Each account is referenced by the system using a user ID (UID),
rather than a name. Names are used for the convenience of the users.

User accounts have several attributes, including password information, group memberships,
expiration dates, comments, etc.

Linux LPIC-1 54
TYPES OF USER ACCOUNTS
There are three different types of accounts: root, standard user, and service.
The root user account plays two roles on a Linux system. The first role is that of the local
administrator. A user logged on as root can do administrative tasks such as password resets,
system configuration changes, user account management, etc. The second role played by the
root user account is to provide a security context for some applications and commands. These
applications and commands may be called by the system or manually entered by a user logged
on as root. The root user account in Linux is significantly more powerful than the local
administrator account on a Windows® system. It is a bad practice to log on to any system with
administrative credentials. On a Linux system, this can be particularly dangerous. The root user
can take destructive action on the system, often without any verification prompt.
Standard user accounts represent regular system users who may log on to run applications,
configure databases, build websites, etc. Each user should have their own account and these
accounts should not be shared. Most tasks that a user should be doing on the system should
only require standard user account privileges. It is possible to set a standard user account to
have administrative privileges. The advantage of this over permitting the user to log on as root
directly is that the privileges of the standard user can be limited, whereas the root user
privileges cannot.
Applications also consume resources on the system, so they are often represented by their own
service accounts. These accounts are usually specific to the service (such as the httpd web
service or a database service). They are disabled for regular log on, and the accounts are
usually created as part of the service installation process. They will often own configuration
files or executables associated with the service.

Linux LPIC-1 55
SUPERUSER
In Linux, the local administrator account is named root. The account is used to perform
administrative functions like managing users, configuring devices, configuring network settings,
etc. The system also runs services with root credentials. The system does not necessarily
confirm with the root user potentially destructive commands. The authority to log on to the
system with root credentials is usually associated with the knowledge of administrative
functions.
The root account is also referred to as the superuser. The security best practice is to never log
on to the system with administrative credentials, but rather to log on with a non-privileged
account and elevate credentials when necessary.

Linux LPIC-1 56
PRINCIPLE OF LEAST PRIVILEGE
In information security, the principle of least privilege states that users should be given no more
authority on the system than they need to perform their job. If a user needs to be able to read
but not write to a file, then give them only read. If a user needs to be able to restart the server
but not reconfigure the server, then only give them privileges to restart. It is much easier to
correct privilege issues by giving a little more access than it is to remove existing access. By
giving the user the access they need to do their jobs and no more than that, the system will
remain significantly more secure.

Linux LPIC-1 57
THE su COMMAND
As you have seen, it is a poor practice to log on to the server directly with root privileges. The
better practice is to log on with a standard user account, then elevate your privileges to root as
needed. One way of elevating privileges is to "substitute user" using the su command.

The su command, without an option, enables a user to switch their identity to that of another
user, but it retains the original user's profile and variables. The switched user also remains in
the home directory of the original user. Anyone using su except the root user will be challenged
for the password of the user account they are switching to.

Using su with a hyphen following it enables a user to change users and launch a new shell
under the context of that new user. This is a much better practice. Anyone using su – except the
root user will be challenged for the password of the user they are switching to. It is most
common to switch to the root user, but any user can switch to any other user so long as they
know the user's password.

SYNTAX
The syntax of the su command is su [-] [user name]

Linux LPIC-1 58
Substituting another user for the current one.

Linux LPIC-1 59
THE sudo COMMAND
With the su command, any user who knows the root password can "get root" and do anything
the root user can do. An account using su – root essentially is the server administrator. This is
often much more power than should be delegated to users. A better practice is to delegate
specific functions to users, rather than granting system- wide root privileges.

The sudo command enables the server administrator to delegate specific commands to specific
users, without granting them full privileges on the server. Delegation is done in the
/etc/sudoers file by using the visudo editor. Users and groups may be given specific commands
to run in order to fulfill their responsibilities without having full administrator privileges.

SYNTAX
The syntax of the sudo command is sudo [options] {command}

Linux LPIC-1 60
THE sudoedit COMMAND
Some Linux files require root user privileges to edit. This could be accomplished with a sudo
configuration, but a simpler and more secure option is to use the sudoedit command. This
command permits a user to edit a file with their own credentials, even if the file is only
available to the root user. In addition, the user can use their preferred text editor.
To use sudoedit, you must make an entry in the sudoers file. For example, the following line
could be added to the sudoers file:

%editors ALL = sudoedit /path/to/file a file: sudoedit /path/to/file

The sudo configuration is appropriate for commands that need to be executed with elevated
privileges, while the sudoedit option is appropriate for files that need to be edited with
elevated privileges.

SYNTAX
The syntax of the sudoedit command is sudoedit [options] {file name}

Linux LPIC-1 61
THE visudo COMMAND
While the /etc/sudoers file is a normal text file, it is essential not to directly edit it with a
standard text editor like Vim or nano. The /etc/sudoers file controls access to all elevated
privileges and a mistake in this file can render it impossible to gain root privileges on the server.
Most distributions will set a default editor (usually Vim or nano) for /etc/sudoers. When using
the visudo command, the system verifies the syntax of the /etc/sudoers file before committing
changes, enabling the administrator an opportunity to correct mistakes before they become
part of the running configuration.

Linux LPIC-1 62
SYNTAX
The syntax of the visudo command is visudo [options]

visudo COMMAND OPTIONS


The following are some options you can use with the visudo command.

Option Used to

-c Check the existing sudoers file for errors.

Edit or check a sudoers file in a different location than the


-f {file name}
default.
Check the sudoers file in strict mode any aliases that are used
-s
before being defined will result in errors.
Output the sudoers file to the specified file in JavaScript Object
-x { file name}
Notation (JSON) format.

Linux LPIC-1 63
THE wheel GROUP
The root system account is used for a great deal more than just administrative tasks. Many
parts of the actual Linux operating system run under root credentials. Many distributions
disable the actual root account for users and instead allow administrative functions based on
membership in the wheel group.

Members of the wheel group exercise the administrative privileges of root with less potential
for damaging the system. For example, members of the wheel group can use the sudo
command to avoid having to sign in as the root user. You can use the visudo command to edit
the privileges of the wheel group, if necessary. You can add users to the wheel group to give
them privileges. Be very cautious about the membership of the wheel group.

Linux LPIC-1 64
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 65
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 66
Linux LPIC-1 67
THE useradd COMMAND
The useradd command is used to create user accounts and configure basic settings. As part of
the account creation process, useradd references several files:
• The account is stored in the /etc/passwd file.
• The account is configured according to various options set in the /etc/login.defs file.
• The account's home directory is created at the /home/<account name> directory.
• The account's home directory is populated using files from the /etc/skel directory.

By default, the useradd command does not set a password for the account. Since most Linux
distributions will not permit a blank password, the account will exist but is not yet usable.

Linux LPIC-1 68
SYNTAX
The syntax of the useradd command is useradd [options] [user name]

useradd COMMAND OPTIONS


The useradd command includes many options to customize user accounts, as detailed in the
above table.

Linux LPIC-1 69
THE passwd COMMAND
The passwd command is used by root to set or reset a password for any user. A user can use
the passwd command themselves to reset their own password. It is also used to set the initial
password for a user after creating the account with the useradd command.

Linux LPIC-1 70
SYNTAX
The syntax of the passwd command is passwd [user name] where [user name] can be used by
root to set a specific user's password.

Linux LPIC-1 71
THE /etc/passwd FILE
The /etc/passwd file stores user account information. All accounts, default or user-specific, will
be found in this file. It is common for administrators to reference this file to learn about specific
user accounts on the system. Each account contains seven fields of information. Each field is
separated by a colon. The fields are not necessarily all populated.

EDITING THE /etc/passwd FILE


The proper way to edit the /etc/passwd file is via the useradd, usermod, and userdel
commands. Manual editing of the file may result in mistakes that render the system unusable.

Field Content
User name Name user logs into system with.
Password Password assigned to user (x means stored elsewhere).
User ID Unique number representing user.
Group ID Unique number of user's primary group.
Comment User's full name (usually).
Home directory Path to user's home directory.
Login shell Path to shell launched when user logs in.

Linux LPIC-1 72
THE /etc/shadow FILE
The /etc/passwd file was once used to store the cryptographically hashed version of
passwords. That file is world-readable, however, meaning that one user could see the hashed
version of another user's password. By entering that hashed password in a password cracking
utility, a user could discover another user's password.

The /etc/shadow file is the modern storage location for hashed passwords, as well as
additional account information. This additional information includes password requirements
and expiration information. Only root has access to the content of
the /etc/shadow file, preventing users from attempting to crack each other's passwords.

Linux LPIC-1 73
THE /etc/shadow FILE FORMAT
The following table details the format of the /etc/shadow file.
Field Content/Additional Information
User name The name the user logs into the system with.
Password The hash value of the password that is assigned to the user.
Days since password
Days are counted from January 1, 1970.
changed
Days before password
Typically set as 1 day.
must be changed
Days until user is warned A value of 99999 means the password never needs to be
to change password changed.
Days after password
expires that account is Ideally, this should be immediate.
disabled
Days the account has been
Days are counted from January 1, 1970.
disabled
Unused field Reserved for potential use in the future.

Linux LPIC-1 74
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 75
THE chage COMMAND
The chage or "change age" command is used to control password expiration, expiration
warnings, inactive days, and other information for existing accounts. Changes to a security
policy or potential security breach may prompt the administrator to alter the password settings
for existing accounts. These changes are reflected in the /etc/shadow file.

SYNTAX
The syntax of the chage command is chage [options] {user name}

Linux LPIC-1 76
THE usermod COMMAND
The usermod command is used to modify settings for regular users. It edits
the /etc/passwd file, avoiding the need for administrators to edit the file directly. There are
many modifications an administrator can make to an existing user account.

The above table lists some options for the usermod command.

SYNTAX
The syntax of the usermod command is usermod [options] {user name}

Linux LPIC-1 77
LOCK USER LOGIN
An administrator may lock a user account if that user leaves the company, if there's a security
breach, or if the user takes a long leave of absence. Locking the account renders it unusable
without deleting the account or its settings. The account can be unlocked when needed.

User accounts can be locked with either the passwd or usermod commands.
To lock:
• passwd -l {user name}
• usermod -L {user name}

To unlock:
• passwd -u {user name}
• usermod -U {user name}

Linux LPIC-1 78
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 79
THE userdel COMMAND
The userdel command is used to delete user accounts. By default, it does not delete the user's
home directory, unless you use the -r option. Deleting the user account removes all references
to it. You would have to recreate the account and re-add it to groups in order to resemble the
original identity. Use caution before deleting a user account.

SYNTAX
The syntax of the userdel command is userdel [options] {user names}

Linux LPIC-1 80
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 81
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 82
Linux LPIC-1 83
GROUP ACCOUNTS
Groups associate user accounts that have similar security requirements. Groups simplify
administrative tasks, allowing multiple users to be granted permissions to resources. Groups
are represented on the system by a group ID number (GID). Users may be a member of more
than one group.

Linux LPIC-1 84
THE /etc/group FILE
The /etc/group file is the storage location for groups. All groups, default or user- specific, will
be found in this file. It is common for administrators to reference the /etc/group file to find
information about the groups on the system. Each group contains four fields of information.
Each field is separated by a colon. The fields are not necessarily all populated.

Linux LPIC-1 85
The proper way to edit the /etc/group file is with the groupadd, groupmod, and groupdel
commands. Manually editing the file is not recommended, as a mistake could render the
system unusable.

Linux LPIC-1 86
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 87
THE groupadd COMMAND
The groupadd command creates a group. By default, the group has no members and no
password. In addition to creating a group with a friendly name, you can also specify a group ID
using the -g option.

Some groupadd options include the above.

SYNTAX
The syntax of the groupadd command is groupadd [options] {group names}

Linux LPIC-1 88
THE groupmod COMMAND
The groupmod command is used to change the group's own attributes. It will edit the
/etc/group file for you. Modifications of the group might include changing its name or GID.

SYNTAX
The syntax of the groupmod command is groupmod [options] {group names}

Linux LPIC-1 89
THE groupdel COMMAND
The groupdel command will delete groups from the /etc/group file. It does not delete user
accounts that are members of the group. Exercise caution when deleting groups as a mistake
can cause users to not be able to access resources.

SYNTAX
The syntax of the groupdel command is groupdel [options] {group names}

Linux LPIC-1 90
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 91
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 92
Linux LPIC-1 93
ACCOUNT QUERYING
Administrators and users may need to gather information about their identity on the system.
There are many commands that will report user and group information. This information is
useful for troubleshooting access problems or verifying what account the user is currently
logged on with.

Linux LPIC-1 94
THE whoami COMMAND
The whoami command is used to display the user name with which you are currently logged in
to the system. Sometimes, you may need to log in to a system and switch among different
users, and you may not be sure with which user you are currently logged in. In such instances,
you can use the whoami command to verify your current user name.

Linux LPIC-1 95
COMMAND PROMPT IDENTIFICATION
Many Linux distributions will show the user name of the currently logged in user at the
command prompt. For the root user, the prompt will show a # character. For standard users,
the prompt will show a $ character.

Linux LPIC-1 96
THE who COMMAND
The who command is used to determine the details of users currently logged in to a system.
The output of the who command includes the user name, the name of the system from which
the user is connected, and the date and time that the user has been connected since.

Linux LPIC-1 97
SYNTAX
The syntax of the who command is who [options]

who COMMAND OPTIONS


The -u option can be used to see how long users have been idle. A dot indicates that the users
were active up to the last minute, old indicates that the users have been inactive for over 24
hours, and anything between 2 minutes and 23 hours 59 minutes shows the length of time they
have been idle. The am i option displays information only for the user who runs the command.

Linux LPIC-1 98
THE w COMMAND
The w command is primarily used to display the details of users who are currently logged in to
a system and their transactions. The first line of the output displays the status of the system.
The second line of the output displays a table with the first column listing the users logged in to
the system and the last column indicating the current activities of the users. The remaining
columns of the table show different attributes associated with the users.

SYNTAX
The syntax of the w command is w [options] [user name]

Linux LPIC-1 99
Displaying user details and transactions.

Linux LPIC-1 100


THE last COMMAND
The last command displays the history of user login and logout actions, along with the actual
time and date. It also has options that enable you to filter users who have logged in through a
specific terminal. For example, last 1 will display the details of users who logged in using the
first terminal. The last command retrieves information from the /var/log/wtmp file.

SYNTAX
The syntax of the last command is last [options]

Linux LPIC-1 101


Displaying user login/logout history.

Linux LPIC-1 102


THE id COMMAND
The id command is used to display user ID (UID) and group ID (GID) information. Entering the
command with no options displays information about the user who is currently logged in. You
can also specify a user name as an option to display ID information about a specific user.

SYNTAX
The syntax of the id command is id [options] [user name]

Linux LPIC-1 103


Showing UID and GID information for a specific user.

Linux LPIC-1 104


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 105


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 106


Linux LPIC-1 107
USER PROFILES
Individual users have personal habits and preferences for their Linux work environment, and so
a variety of profile file configurations are available to help them customize their experience.
These customizations are referred to as profiles. An initial profile is created when the user
account is created. There are many files and directories from which information is initially
pulled to create a standard profile.

Linux LPIC-1 108


THE .bashrc FILE
The .bashrc file enables customization of the user's own environment. The file is stored in a
user's home directory. Because the .bashrc file is unique to each user, it can be configured to a
user's own specific needs or preferences.

A good example of the use of the .bashrc file is the use of aliases. Users can specify their own
abbreviated commands without impacting the experience of any other user on the system.
Another common configuration within .bashrc is environment variables. Users can also use the
file to customize the command prompt to provide the information they want.

Linux LPIC-1 109


EXAMPLE CONFIGURATIONS
Other than creating aliases, the .bashrc file is often configured to set default directory and file
permissions for the user. Also, the default command prompt can be altered to provide more
information. Most distributions place the user name, system hostname, and current directory
in the prompt, but that can be changed.

Linux LPIC-1 110


THE .bash_profile FILE
The .bash_profile file provides shell configuration for the initial login environment. This differs
from the .bashrc file, which provides settings for all of the user's interactive shells. The
.bash_profile file is only read with the first login, while the .bashrc is read with all subsequent
logins.
A default .bash_profile can be provided to new users via the /etc/skel directory.

Linux LPIC-1 111


The .bash_profile file.

Linux LPIC-1 112


GLOBAL USER PROFILES
An administrator may find it desirable to define system-wide settings or to configure initial
settings for users. The files and directories that follow give the administrator the flexibility to
make a variety of configurations, which may be later customized by a user for their own specific
needs.

Linux LPIC-1 113


THE /etc/skel/ DIRECTORY
The contents of the /etc/skel/ directory are automatically copied into the home directories of
new users. Administrators can pre-populate the /etc/skel/ directory with configuration files or
other content. When the useradd command is run, the /etc/skel/ directory's contents are
copied to the new user's home directory, immediately giving them the configurations they
might need.
Note that files added to the /etc/skel/ directory after a user account is created will not be
copied to the home directories of existing users.

Linux LPIC-1 114


THE /etc/profile FILE
The /etc/profile file provides system-wide environment variables. This may be more effective
for administrators to configure if there are settings that apply to all users.
During the initial login process for a user, the system reads the /etc/profile file first for Bash
shell configurations, and then any user-specific Bash customizations are pulled from the .profile
file located in the user's home directory. The .profile file runs each time a new shell is started,
whereas /etc/profile is only run at login. This approach enables administrators to define global
shell settings, but still allow user-specific customizations.

EXAMPLE
An example of a .profile is as follows:
PATH=$PATH:$HOME/bin:/scripts
MAIL=/var/mail/$LOGNAME
EDITOR=emacs
export PATH MAIL EDITOR

The first line defines the paths of executable files; the second line defines the path for where
incoming email messages are stored; and the third line defines the default text editor. The last
line actually ensures these variables are implemented in the environment.

Linux LPIC-1 115


THE /etc/profile.d/ DIRECTORY
The /etc/profile.d/ directory serves as a storage location for scripts administrators may use to
set additional system-wide variables. It is recommended you set the environment variables via
scripts contained in /etc/profile.d/ rather than editing the /etc/profile file directly.

Linux LPIC-1 116


THE /etc/bashrc FILE
The /etc/bashrc file provides system-wide Bash settings. This is a little different than
/etc/profile, which is used for variables.

Linux LPIC-1 117


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 118


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 119


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 120


Creating accounts is more than just about allowing people to log in; it's also necessary for
delegating access to system resources. However, managing accounts is not enough to
accomplish this. The other important part of the process is configuring permissions and
ownership. In this topic, you'll ensure that the right people have the right access to the right
resources in Linux®, while ensuring that no one has more access than is necessary.

Linux LPIC-1 121


In this topic, you will:

• Modify permissions for files and directories.


• Modify ownership of files and directories.
• Configure special permissions and attributes.
• Troubleshoot issues with permissions and ownership.

Linux LPIC-1 122


Linux LPIC-1 123
You'll begin restricting access to files and directories by applying the proper permissions to
those resources. This is a crucial step in ensuring the security of your data.

PERMISSIONS
Permissions are access rights assigned to users, which enable them to access or modify certain
files and directories. Permissions can be set at different levels and for different access contexts.
They enable you to configure who is allowed to access an object, and who is restricted from
accessing that object. Controlling access through permissions mitigates risk by ensuring that
users are only able to access what they need to get their job done, and no more.

THE ls -l COMMAND
The ls -l command gives you a long list of the files and directories in your current working
directory. Each item in the list contains seven columns, three of which display permission
information. The contents of the columns are described in the following table.

Linux LPIC-1 124


PERMISSION ATTRIBUTES
Permission attributes define exactly what a user is allowed to do with a particular file or
directory. The above table describes the three permission attributes. Note that these attributes
behave differently based on whether they apply to a file or a directory.

Linux LPIC-1 125


PERMISSION CONTEXTS
Permission attributes on files and folders are applied to one of several contexts, or the types of
users and entities that you can give permission to. These contexts are:
• Owner (u): The owner of the file or directory, also simply referred to as the user.
• Group (g): The file or directory's group and all users belonging to that group.
• Other (o): All other users (neither owner nor group member).

Linux LPIC-1 126


PERMISSION STRING
The output of the ls -l command shows the permission string for a file or directory. The
permission string contains 11 characters.

• The first character indicates the type of file; d for directory and hyphen ( - ) for file.
• Characters at the second, third, and fourth positions denote owner permissions.
• Characters at the fifth, sixth, and seventh positions denote group permissions.
• Characters at the eight, ninth, and tenth positions denote other permissions.
• The final character indicates the access method for the file; period (.) for SELinux security
context and plus (+) for any other combination of alternative access methods.

Linux LPIC-1 127


THE chmod COMMAND
The chmod command enables you to modify the permissions of a file or directory. Only the
owner of the file or directory or the system administrator can change the permissions of the
object.

SYNTAX
The syntax of the chmod command is chmod [options] {mode} {file/ directory name}

Linux LPIC-1 128


chmod COMMAND OPTIONS
The chmod command supports different options to modify permissions. One or more of these
options may be used at a time.

Option Used To

-c Report changes made to permissions.

-f Hide most error messages.

-v Display diagnostic entry for every object processed.

-R Modify permissions recursively.

Linux LPIC-1 129


chmod SYMBOLIC MODE
The chmod command supports two modes: symbolic mode and absolute mode. Symbolic
mode enables you to set permissions using three components, namely:
• Permission contexts: u/g/o/a (a applies the permissions to all three contexts).
• Permission operators: +/-/=
• Permission attributes: r/w/x

Permission operators determine whether a permission is to be granted or removed.

SYNTAX
In symbolic mode, the syntax of the chmod command is:
chmod {access context}{operators}{permission attributes} {file/directory names}

As an example, to add read and write permissions to myfile for the owner and the group:
chmod u+rw,g+rw myfile

Linux LPIC-1 130


Examples of setting permissions using symbolic mode.

Linux LPIC-1 131


chmod ABSOLUTE MODE
The other chmod mode, absolute mode, uses octal (base-8) numbers to specify permissions.
Each permission (r/w/x) has an associated number.

By adding the octal numbers for the permissions you want to grant, you get the overall
permission number to assign to a directory or file. For example, full permissions (read, write,
and execute) are equivalent to 4 + 2 + 1, or 7. Read and write permissions are equivalent to 4 +
2, or 6. Complete permissions are expressed as a three-digit number, where each digit
corresponds to the owner, the group, and others, respectively.

Linux LPIC-1 132


SYNTAX
In absolute mode, the syntax of the chmod command is chmod {number} {file/directory
name}

COMMON PERMISSIONS IN DIFFERENT MODES


The following table compares how the different chmod modes represent commonly assigned
permissions.

Absolute Mode Symbolic Mode


755 u=rwx, g=rx, o=rx
700 u=rwx, g=, o=
644 u=rw, g=r, o=r
600 u=rw, g=, o=
THREE-DIGIT AND FOUR-DIGIT MODES
When written in octal, numeric format, file permissions typically have three digits, each digit
corresponding to the user, group, and others permissions. However, file permissions may also
be written with four digits, with the new, leading digit signifying any advanced permissions to
be defined (or 0, for none). For example, the base permissions for non-executable files in Linux
are rw-rw-rw-, or 666. This is equivalent to the octal format of 0666.

Linux LPIC-1 133


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 134


DEFAULT PERMISSIONS
In Linux, default permissions are assigned to newly created files and directories based on user
privileges. For files created by the root user, the default permissions are 644, which means that
the root user has read and write permissions, while group users and others will have only read
permission. For directories created by the root user, the default permissions are 755, which
means that the root user has read, write, and execute permissions, while group users and
others will have only read and execute permissions. In the case of users with limited access
rights, Linux assigns permissions of 664 for newly created files and 775 for newly created
directories.
These default permissions are determined by the user file creation mask, or umask. However,
the default permissions may be altered by the root user.

Linux LPIC-1 135


THE umask COMMAND
The umask command alters the default permissions on newly created files and directories.
Changing default permissions can be useful if you'd like to automatically control how new
objects can be used, rather than changing these permissions manually on every new object.
With umask, you set default permissions using octal numeric format. However, instead of
specifying which permissions to set, you specify which permissions to mask, or clear, from the
default. For example, the default permissions for non-executable files in Linux are 666 (rw-rw-
rw-). If you want the owner to retain these permissions, but you want the group and others to
only have read access, you'll need to set the umask to 022. Each number is explained as
follows, in order:
• 0 means that the current owner permissions should not be masked at all, i.e., left as read
and write.
• 2 means that the group permissions should be masked by 2, i.e., subtract 2 from the default
(6) and you get 4. Group members now only have read access.
• 2 does the same thing as the previous number, but for other users.
You can use the umask command directly in the CLI to set the default permissions for that
session, or you can set the default permissions for each user in their .bashrc file.

SYNTAX
The syntax of the umask command is umask {number}

Linux LPIC-1 136


The order in which umask values are calculated.

Linux LPIC-1 137


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 138


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 139


Linux LPIC-1 140
Although you've restricted access to your data by assigning permissions, you may need to allow
users to modify those permissions for certain files and directories. This is where the concept of
ownership comes into play.

OWNERSHIP
As you've seen, the first permission context is the owner, or user. In Linux, ownership refers to
the property by which a user can apply and modify the permissions of a file or directory. By
default, the owner of a file or directory is the user who created that file or directory. Other than
the superuser, no other user can change the permissions of an object that is owned by
someone else.
While the most common application of ownership is the changing of read, write, and execute
permission attributes, owners can also alter advanced and special permissions of the objects
they own.

Linux LPIC-1 141


THE chown COMMAND
The chown command is used to change the owner, the group, or both for a file or directory. At
times, you may wish for someone else to manage an object's permissions other than the user
who created that object.

RECURSIVELY CHANGING OWNERSHIP


You can combine the chown command with the -R option to recursively change ownership
through a directory structure.

Linux LPIC-1 142


THE chgrp COMMAND
The chgrp command is used to change the group ownership of a file or directory. Changing the
group ownership of an object ensures that the group permissions are applied to the specific
group.

SYNTAX
The syntax of the chgrp command is chgrp {group name} {file/ directory name}

Linux LPIC-1 143


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 144


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 145


Linux LPIC-1 146
The standard read, write, and execute permissions are good enough in most circumstances.
However, there are additional permissions and attributes that you can use to restrict access in a
more specialized way.

SPECIAL PERMISSIONS
Special permissions are used when normal permissions become inadequate. With special
permissions, less privileged users are allowed to execute a file by assuming the privileges of the
file's owner or group This enables the user to temporarily take on these higher level privileges
in a limited context.

Linux LPIC-1 147


SUID AND SGID PERMISSIONS
In Linux, two main special permissions are set user ID (SUID) and set group ID (SGID). SUID, or
setuid, is the permission that allows a user to have similar permissions as the owner of the file.
Certain executable files and commands, like passwd, require access to additional resources that
the user may not have explicit permissions to. Instead of granting those permissions
individually, the passwd command is configured so that any user will execute it as root (the
owner), giving them permission to the additional resources.

SGID, or setgid, is the permission that allows a user to have similar permissions as the group
owner of the file. In addition to files, SGID can also be set on directories. Any subdirectories
created in this directory will automatically inherit the SGID permission. Likewise, all new files
and subdirectories created in this directory will inherit the directory's group ID, rather than the
group ID of the user who created the object. This inheritance is useful because users in a
shared environment don't need to change their group when they create objects in the
directory. Note that the SGID permission is not applied to existing objects in the directory, nor
is it applied to objects that are moved from other locations into the directory.

SUID and SGID are both set using the chmod command, and you can do so using either
symbolic mode or absolute mode. When using ls -al to see permissions, the execute permission
for the owner will appear as s for the SUID, and the execute permission for the group will
appear as s for the SGID.

Linux LPIC-1 148


SYNTAX
The following is the syntax for setting the SUID on a file, using symbolic and absolute mode,
respectively:
chmod u+s {file names}
chmod 4### {file names}

Note the last three bits in absolute mode are whatever standard permissions you choose.
The following is the syntax for setting the SGID on a directory, using symbolic and absolute
mode, respectively:
chmod g+s {directory names}
chmod 2### {directory names}

Removing the SUID and SGID is as simple as using the - (minus) operator in symbolic mode, or
setting the first permission bit to 0 in absolute mode.

Linux LPIC-1 149


STICKY BIT
A sticky bit is a special permission bit that provides protection for files in a directory. It ensures
that only the owner of a file or directory (or root) can delete the file or directory. Without the
sticky bit, any user with write and execute permissions on an object can delete that object. The
sticky bit ensures that these users do not have delete privileges, but still have the rest of the
privileges that come with writing and executing files and directories.
Like SUID/SGID, you set a sticky bit using the chmod command. Using ls -al you can see the
sticky bit in the execute position for other users (the last position) as the letter t, or the
capitalized letter T if the execute permission is not set for others.

SYNTAX
The syntax for setting the sticky bit is as follows, using symbolic mode and absolute mode,
respectively:
chmod +t {directory names}
chmod 1### {directory names}
As with SUID/SGID, use - or 0 to clear the sticky bit.

STICKY BIT ON FILES


In older versions of the kernel, a sticky bit could force a program or file to remain in memory so
that it wouldn't need to be reloaded when it was invoked again. A sticky bit on a file indicated
to the operating system that the file would be executed frequently. Modern versions of the
Linux kernel ignore the sticky bit on files; if you want to protect specific files, you need to apply
the sticky bit on the directory that contains them.

Linux LPIC-1 150


FILE ATTRIBUTES
Files can have one or more attributes set on them that define how the system interacts with
those files. These attributes go beyond typical permissions and enable you to more granularly
customize what the system is and is not allowed to do with a file. There are many such
attributes. Some examples include:
• Only allow the file to be open for writing in append mode; i.e., don't allow the file to be
overwritten.
• Set the file to be automatically compressed.
• Save the file if it is deleted, providing an opportunity for it to be recovered.
• Make the file immutable.

Linux LPIC-1 151


THE IMMUTABLE FLAG
The immutable flag is an attribute of a file or directory that prevents it from being modified,
even by the root user. In other words, no one can delete, rename, or write to an immutable file.
Setting the immutable flag is useful for files with a high degree of sensitivity and importance,
and which are also not likely to change any time soon. A careless user or an errant process will
be unable to delete the immutable file.
The immutable flag is not set on all files. A single directory can have a mix of mutable and
immutable files and subdirectories. Also, an immutable subdirectory can have mutable files.
When viewing file attributes, the lowercase i character indicates that the immutable flag is set.

Linux LPIC-1 152


THE lsattr COMMAND
The lsattr command is used to list the attributes of a file or directory.

The above table describes some of the options of the lsattr command.

SYNTAX
The syntax of the lsattr command is lsattr [options] {file/ directory names}

Linux LPIC-1 153


Listing the attributes of a file.

Linux LPIC-1 154


THE chattr COMMAND
The chattr command is used to change the attributes of a file or directory.

The above table describes some of the options of the chattr command.

SYNTAX
The syntax of the chattr command is chattr [-R] [-v {version}] [+-{attributes}] {file/directory
names}

Linux LPIC-1 155


ACCESS CONTROL LISTS
An access control list (ACL) is a list of permissions attached to an object. ACLs can be used for
situations where the traditional file permission concept does not suffice. ACLs enable you to
assign permissions to individual users or groups even if these do not correspond to the object's
owner or group.
For example, members of two department groups may need different levels of access to the
same resource. Group 1 might need r/w/x to a directory, whereas Group 2 only needs r/x
access. By using ACLs, you are able to grant different levels of access to different users, groups,
and even processes. ACLs enable a more granular level of control.

Linux LPIC-1 156


THE getfacl COMMAND
The getfacl command is used to retrieve the ACLs of files and directories.
The basic output format of the getfacl command shows metadata about the object including its
owner, its group, any SUID/SGID/sticky bit flags set, the standard permissions associated with
the object, and the individual permission entries for users and groups.

Linux LPIC-1 157


An ACL that sets permissions for a specific user.

Linux LPIC-1 158


THE setfacl COMMAND
The setfacl command is used to change the permissions associated with the ACL of a file or
directory.
The setfacl command has several options, some of the most common of which are described in
the above table.

SYNTAX
The syntax of the setfacl command is setfacl [-bR] [-mx {acl_spec}] {file/directory names}

ACL SPECIFICATION
The ACL specification can be formatted in one of several ways:
• When working with users, the format is u:{user name}:{permissions}
• When working with groups, the format is g:{group name}:{permissions}

EXAMPLE
The following is an example of modifying the ACL on a directory where the user http is given
read access:
setfacl -m u:http:r-- /home/directory

Linux LPIC-1 159


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 160


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 161


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 162


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 163


Linux LPIC-1 164
In any system, problems are inevitable. As a Linux professional, one of the most important skills
you'll need is the ability to troubleshoot these problems. So, in this topic, you'll follow a general
model for troubleshooting any type of operating system problem. You'll then put these
troubleshooting skills to use by diagnosing and solving issues related to permissions.

TROUBLESHOOTING
Troubleshooting is the recognition, diagnosis, and resolution of problems. Troubleshooting
begins with the identification of a problem, and it does not end until services have been
restored and the problem no longer adversely affects users. Troubleshooting can take many
forms, but all approaches have the same goal: to solve a problem efficiently with a minimal
interruption of service.

Linux LPIC-1 165


TROUBLESHOOTING MODELS
A troubleshooting strategy is a plan of action for identifying the causes and resolving the effects
of a system-related issue. You can implement a troubleshooting strategy through a step-by-step
approach, or a troubleshooting model. There are many such models, and they can vary in their
approach, but all models attempt to enable the troubleshooter to move in a methodical and
repeatable pattern during the troubleshooting process.
One example of a troubleshooting model divides the process into the following steps:
1. Identify the problem. This stage includes:
• Gathering information.
• Duplicating the problem, if possible.
• Questioning users to gain experiential information.
• Identifying the symptoms.
• Determining if anything has changed.
• Approaching multiple problems individually.
2. Establish a theory of probable cause. This stage includes:
• Questioning the obvious.
• Considering multiple approaches.
• Looking for not just a cause, but the root cause.
3. Test the theory to determine the cause.
• When the theory is confirmed, determine the next steps to resolve the problem.
• If the theory is not confirmed, establish a new theory or escalate the issue.
4. Establish a plan of action to resolve the problem, while identifying the potential effects of your plan.
5. Implement the solution, or escalate the issue.
6. Verify full system functionality and, if applicable, implement preventative measures.
7. Document your findings, actions, and the outcomes.

Linux LPIC-1 166


PERMISSIONS TROUBLESHOOTING
As a general guideline, whenever you are denied permissions when you expect to have them,
or vice versa, you should always verify the permissions of the relevant object by using the ls -al
command. That will often save you from a lot of guesswork, as many issues simply come down
to the wrong permission being applied.
The above table lists some common symptoms that relate to permissions issues, as well as
some potential causes and solutions. Note that these are examples, and that some of these
symptoms can have multiple causes and solutions.

Linux LPIC-1 167


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 168


OWNERSHIP TROUBLESHOOTING
Just like with permissions, you should use ls -al to verify the user and group ownership of a file
or directory whenever you are experiencing ownership-related issues. Beyond that, the above
table lists some potential issues you may come across, as well as suggested causes and
solutions.

Linux LPIC-1 169


GROUP MEMBERSHIP TROUBLESHOOTING
Some issues arise because, despite having configured permissions and ownership correctly, the
user may not be placed in the correct group. Use the groups {user name} command to discover
what groups a user is a member of. A related issue is that, when a user creates files, the default
owning group is not what is expected. Make sure the expected group is the user's primary
group, rather than a secondary group. In either case, use the usermod command to change
group membership when applicable.

It may also be beneficial to list all of the members of a group so you identify which accounts to
add or remove as necessary. However, there is not necessarily one simple command that is
universal to Linux distributions that can accomplish this. You can search the /etc/group file for
the desired group, but this only displays groups in the standard database (i.e., not other
authentication methods), and it doesn't show users whose primary group is the group you're
searching for. The lid and libuser-lid commands are pre-installed on some distributions and can
retrieve all members of a group, including members whose primary group is the group being
searched for. The getent command, available on some distributions, enables you to retrieve
group members of non-standard authentication methods.

Linux LPIC-1 170


GUIDELINES FOR TROUBLESHOOT PERMISSIONS ISSUES
Use the following guidelines when troubleshooting permissions issues:
• Follow an overall troubleshooting strategy for any kind of troubleshooting task.
• Follow a step-by-step troubleshooting model that can produce repeatable and demonstrable
results.
• Start by verifying an object's permissions and ownership using the ls -al command.
• Ensure users have the permissions to work with a file if they are being denied access.
• Ensure users do not have permissions that enable them to access files beyond what they
should have.
• Ensure objects don't have the immutable flag set if you expect to modify them.
• Set the SUID permission on an executable if you need to run it with root permissions for it to
function properly.
• Set the sticky bit when you only want the owner and root to be able to delete an object.
• Ensure objects have the proper owner and owning group set.
• Set the SGID permission on a directory when you want new files to take on that directory's
group ownership.
• Use the groups {user name} command to verify the groups a user is a member of.
• Modify group membership when necessary to ensure access or a lack thereof for specific
users.
• Acquire and use tools like lid and getent to view members of a specific group.

Linux LPIC-1 171


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 172


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 173


Aside from managing user access to your Linux® systems, one of the most foundational tasks is
the management of data storage. There are many ways to divide, format, and otherwise
organize how your data is stored, and Linux gives you many tools for doing so. Using these
tools, you will ultimately make it easier for authorized users to work with data.

Linux LPIC-1 174


In this topic, you will:

• Create drive partitions.


• Manage volumes using the Logical Volume Manager (LVM).
• Mount Linux file systems.
• Manage Linux file systems.
• Navigate the directory structure defined in the Filesystem Hierarchy Standard (FHS).
• Troubleshoot storage issues

Linux LPIC-1 175


Linux LPIC-1 176
STORAGE DEVICES
A storage device is a physical component that can record data and hold it persistently. There
are many types of storage devices that are supported by the Linux operating system. Common
types include:
• Hard disk drive (HDD): electromechanical devices that use magnetic storage technology to
store data, usually in large amounts.
• Solid-state drive (SSD): storage devices that use non-mechanical solid-state technology to
store data, usually in large amounts. They tend to support much quicker access times than
HDDs.
• USB thumb drive: portable storage devices that use flash memory technology to store data,
usually in small amounts compared to HDDs and SSDs. Their small size makes them easy to
move around.
• External storage drive: portable storage drives that can use one of several technology types.
They usually connect to a computer through a peripheral interface like USB, rather than
being an internal component.
Although the previous storage devices are most likely what you'll be working with, you might
also be responsible for working with legacy technology like floppy disk drives (FDD), tape
drives, etc.

BLOCK VS. CHARACTER DEVICES


Linux refers to devices as either block or character devices. Block devices are storage devices
(like those listed previously) that can be read from and written to in blocks of data. Character
devices are devices like keyboards, mice, serial ports, etc., that can be read from and written to
in streams of data.

Linux LPIC-1 177


FILE SYSTEMS
A file system is a data structure that is used by an operating system to store, retrieve, organize,
and manage files and directories on storage devices. A file system maintains information such
as the date of creation and modification of individual files, the size of files on the storage
device, the type of files, and permissions associated with files. It also provides a structured
form for data storage.

A file system by itself does not interpret the data contained in files because this task is handled
by specific applications. File systems vary depending on several parameters, such as the
purpose of the file systems, the information they store about individual files, the way they store
data, and the data security mechanisms they implement.

Linux LPIC-1 178


Linux supports many file system types. The most common are described in the above table.

NTFS
The New Technology File System (NTFS) is a proprietary file system created by Microsoft® as
the primary file system for Windows®. NTFS provides many enhanced features over FAT,
including file- and folder-level security, file encryption, drive compression, and scalability to
very large drives and files.
Linux does not support NTFS by default; however, a utility called NTFS-3G can enable support
for NTFS on Linux systems.

Linux LPIC-1 179


NETWORK FILE SYSTEMS
While the previous table lists general-purpose file systems, some file systems function as
network protocols that enable the sharing of data over a network. Common types include the
following.

Network File System Description


The SMB protocol provides users shared access to files and other
resources across a local area network (LAN). SMB clients make
requests for resources to SMB servers, which respond and provide
Server Message Block
the appropriate level of access. This protocol is primarily used with
(SMB)
Windows computers. However, SMB-compatible software called
Samba helps interface Linux and Windows hosts running network
shares.
CIFS is a specific implementation of SMB that is rarely in use.
Microsoft designed it as a successor to SMB version 1, but SMB
Common Internet File
versions 2 and 3 superseded it. However, Linux still uses the CIFS
System (CIFS)
name in some of its tools, though these tools support newer
versions of SMB.
NFS offers similar functionality to SMB, but the protocols are not
Network File System compatible. NFS is preferred in situations where Linux clients access
(NFS) Linux servers. In environments that are a mix of Windows and Linux,
the SMB protocol is the better choice.

Linux LPIC-1 180


INODES
An index node (inode) is an object that stores metadata about a file or directory on a file
system. This metadata can include time-based values like when a file was created and last
modified; permission and ownership information; the block locations of a file's data on a
storage device; and other miscellaneous information.

Each inode on a file system is identified by a unique integer called an inode number. Whenever
the system or an application tries to access a file, it searches for the appropriate inode number
in a data structure called an inode table. The inode table maps an inode number to its
corresponding file or directory name.

Some file systems set a maximum number of inodes when that file system is created, usually by
considering the overall size of the file system. The total number of files and directories cannot
exceed this inode maximum. However, some file system types, like XFS, use a dynamic inode
allocation system that scales as a percentage of the file system's capacity. In other words, these
file systems do not set a strict inode limit.

Linux LPIC-1 181


A specific file with its associated inode.

Linux LPIC-1 182


JOURNALING
Journaling is a method by which a file system records changes that have not yet been made to
the file system itself in an object called a journal. This enables the file system to quickly recover
after an unexpected interruption, such as a system crash, because the system can reference
pending changes in the journal to resume where it had left off.

The journaling process involves the following phases:


1. The journal describes all the changes that must be made to the drive.
2. A background process makes each change as and when it is entered in the journal.
3. If the system shuts down, pending changes are performed when it is rebooted.
4. Incomplete entries in the journal are discarded.

Linux LPIC-1 183


VIRTUAL FILE SYSTEM
A real file system refers to a discrete file system that the Linux kernel can normally work with
directly. The problem is, Linux supports many different file system types that aren't necessarily
compatible. The virtual file system (VFS) was created as a common software interface that sits
between the kernel and real file systems. In effect, the VFS translates a real file system's details
to the kernel so that the file system appears identical to any other file system.
With VFS, you can mount multiple different types of file systems on the same Linux installation,
and they will appear uniform to the user and to all other applications. Therefore, the user and
these applications can work with the file system without actually knowing its underlying
structure. This greatly increases interoperability between the system and running software.

EXAMPLES
Examples of real file systems on a Linux system can include xfs, ext4, and several other types.
Examples of virtual file systems can include proc, which contains system information during
runtime; devtmpfs, which contains device nodes loaded by the kernel during system
initialization; debugfs, which contains information useful in debugging the Linux kernel; and
many more.

Linux LPIC-1 184


FILE SYSTEM LABELS
File system labels are assigned to file systems for easy identification. The labels may be up to 16
characters long and can be displayed or changed using the e2label command for ext# file
systems and the xfs_admin command for XFS file systems.

SYNTAX
The syntax for setting ext# file system labels is e2label /dev/{device name}{partition number}
{label name}

The syntax for setting XFS file system labels is xfs_admin -L {label name} /dev/{device
name}{partition number}

Linux LPIC-1 185


PARTITIONS
A partition is a section of the storage drive that logically acts as a separate drive. Partitions
enable you to convert a large drive to smaller manageable chunks, leading to better
organization of information. A partition must be formatted and assigned a file system before
data can be stored on it.

Partitions are identified using a partition table, which is stored in one or more areas of the
drive. The size of each partition can vary but cannot exceed the total free space of the storage
drive.

Most operating systems, including Linux, use drive partitions. Data of different types can be
stored in separate locations on the drive, such as separating system files from user-accessible
files.

Linux LPIC-1 186


TYPES OF PARTITIONS
There are three types of partitions: primary, extended, and logical. The functionality of the
storage drive depends on the types of partitions on it.

Linux LPIC-1 187


Each partition has a set of specific features. The three types of partitions are described in the
table.

Partition Type Description


A partition that can contain one file system or logical drive and is
Primary sometimes referred to as a volume. The swap file system and the
boot partition are normally created in a primary partition.
An extended partition can contain several file systems, which are
referred to as logical drives. There can be only one extended
Extended
partition, which can be further subdivided. This partition type does
not contain any data and has a separate partition table.
A part of a physical drive that has been partitioned and allocated as
an independent unit and functions as a separate drive. A logical
partition is created within an extended partition, and is therefore a
Logical
subset of an extended partition. There is no restriction on the
number of logical partitions, but it is advisable to limit it to 12 logical
partitions per drive.

Linux LPIC-1 188


SWAP SPACE
Swap space is a partition on the storage device that is used when the system runs out of
physical memory. Linux pushes some of the unused files from RAM to the swap space to free
up memory. Usually, the swap space equals twice the RAM capacity.

Linux LPIC-1 189


THE fdisk UTILITY
The fdisk utility is a menu-driven program that is used to create, modify, or delete partitions on
a storage drive. Using fdisk, you can create a new partition table or modify existing entries on
the partition table. The fdisk utility understands the DOS and Linux type partition tables. The
fdisk utility also enables you to specify the size of partitions.

Linux LPIC-1 190


SYNTAX
The syntax of the fdisk utility is fdisk [options] {device name}

fdisk COMMAND OPTIONS


The fdisk utility supports a number of command-line options.

Option Used To
-b {sector size} Specify the number of drive sectors.

-H {heads} Specify the number of drive heads.

-S {sectors} Specify the number of sectors per track.

-s {partition} Print the partition size in blocks.

-l List partition tables for devices.

Linux LPIC-1 191


fdisk MENU OPTIONS
Aside from supplying command-line options, you can also choose various options when you are
working in the fdisk menu.

Option Used To

n Create a new partition.

d Remove a partition.

p List existing partitions.

w Write changes to drive and exit utility.

q Cancel changes made and exit utility.

Linux LPIC-1 192


Using fdisk to list a storage device's partitions.

Linux LPIC-1 193


GNU PARTED
The GNU Parted utility is also used to manage partitions. It is particularly useful when creating
partitions on new storage drives. It can be used to create, destroy, and resize partitions. The
parted command runs the GNU Parted utility. Like fdisk, parted includes a menu-driven
interactive mode where you can input various options.

SYNTAX
The syntax of the parted command is parted [options] {device name}

Linux LPIC-1 194


The GNU Parted utility.

Linux LPIC-1 195


GNU PARTED MENU OPTIONS
There are a number of options you can choose when working in GNU Parted's interactive
mode.

Linux LPIC-1 196


The above table lists some of the menu options available.

Linux LPIC-1 197


THE partprobe COMMAND
The partprobe command is used to update the kernel with changes in the partition table. The
command first checks the partition table, and if there are any changes, it automatically updates
the kernel with the changes.

After creating a partition with fdisk, you cannot add a file system to that partition unless the
kernel can read it from the partition table. You might receive an error like "Re-reading the
partition table failed" during the fdisk operation. Rebooting the machine updates the table, or
you can issue partprobe instead to update the table without a reboot.

The partprobe command comes packaged with the GNU parted utility.

SYNTAX
The syntax of the partprobe utility is partprobe [options] [device name]

Linux LPIC-1 198


Updating the kernel after creating a new partition.

Linux LPIC-1 199


THE mkfs COMMAND
The mkfs command is used to build a Linux file system on a device, which is usually a drive
partition. The above table lists some options of the mkfs command and their descriptions.

SYNTAX
One syntax option of the mkfs command is mkfs [options] {device name}

Another syntax option is mkfs.{file system type} [options] {device name}

Linux LPIC-1 200


Creating a file system on a partition.

Linux LPIC-1 201


THE fstab FILE
The fstab file is a configuration file that stores information about storage devices and partitions
and where and how the partitions should be mounted. The fstab file is located in the /etc
directory. It is read by the system at boot time and can be edited only by a root user. The fstab
file consists of a number of lines, one for each file system.

Field Description
Device/partition name Name of device/file system to mount.
Default mount point Where to mount file system.
File system type Type of file system used by device/partition.
Mount options Values activated when file system is mounted.
dump options Indicates if dump should back up file system.
fsck options Order in which fsck should check file system.

Linux LPIC-1 202


Each line in an fstab file has six fields that are separated by spaces or tabs.
Field Description
Device or partition
Specifies the name of the device or file system to mount.
name
Default mount point Indicates where the file system is to be mounted.

File system type Specifies the type of file system used by the device or partition.
Specifies a set of comma-separated options that will be activated
Mount options
when the file system is mounted.
Indicates if the dump utility should back up the file system. Usually,
dump options zero is specified as the dump option to indicate that dump can
ignore the file system.
fsck options Specifies the order in which the fsck utility should check file systems.

THE crypttab FILE


The /etc/crypttab file performs a similar function to the fstab file, but its purpose is to store
information about encrypted devices and partitions that must be unlocked and mounted on
system boot. Its format is similar to fstab, but includes an optional password field for unlocking
the encrypted device.

Linux LPIC-1 203


THE STORAGE DEVICE SETUP PROCESS
Putting several of the previous tools together, the overall process of setting up a storage device
for use on Linux is as follows:
1. Partition the storage device using a tool like fdisk or parted
2. Format the partition with a file system using the mkfs tool.
3. Add the formatted partition to the fstab file so that it is configured by the system on boot.

Linux LPIC-1 204


THE /dev/ DIRECTORY
The /dev/ directory contains files that represent and support devices attached to the system.
Linux uses naming conventions so that storage devices will be easily located by the system
when they are attached and when the system boots. For storage devices, the naming
convention is typically expressed in three parts. Take the device name /dev/sda1 as an
example:
• The sd portion refers to a specific type of controller that the device is using (in this
• case, SCSI/SATA, which is the most common).
• The a portion refers to the first whole drive. The second whole drive would be b, the third
would be c, and so on.
• The 1 refers to the first partition on this drive. The second partition would be 2, the third
would be 3, and so on.

When you manage partitions and other device information, for the most part, you'll use this
naming convention to refer to those devices.

THE /dev/disk/by- IDENTIFIERS


In addition to the previous naming convention, Linux also uses several different persistent
naming schemes to identify devices. Controller-based naming can become problematic in
systems with more than one of the same type of controller. So, the persistent naming schemes
were created to make identifying a device more predictable. Some of those schemes are:
• /dev/disk/by-id —This refers to an identifier based on the device's hardware serial number.

Linux LPIC-1 205


• /dev/disk/by-path —This refers to an identifier based on the shortest physical
path to the device (i.e., the path changes if you plug the device into a different port
on the controller). This is useful in configurations using DM-Multipath, a feature of
the kernel that supports multiple I/O paths to devices.
• /dev/disk/by-uuid —This refers to an identifier based on the universally unique
identifier (UUID) that was assigned to the device when a file system was created
on it.

Linux LPIC-1 205


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 206


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 207


Linux LPIC-1 208
Partitions are useful, but they are not the only method for logically dividing a storage device. In
this topic, you'll use logical volumes to create a more flexible structure for organizing data on
storage devices.

DEVICE MAPPING
Thus far, you've worked with physical storage devices, also called physical volumes. However,
there is a way to further abstract these devices into virtual storage devices— a process called
device mapping. In Linux, the device mapper creates the virtual device and passes data from
that virtual device to one or more physical devices.

Several Linux applications leverage the device mapper to perform various tasks. For example,
volume encryption and integrity checking services use device mapper to act upon data that is
transmitted between physical and virtual devices.

DM-MULTIPATH
DM-Multipath is a feature of the Linux kernel that provides redundancy and improved
performance for block storage devices. It leverages the device mapper to support multiple I/O
paths (connection interfaces) between the CPU and the storage devices. If one path fails, DM-
Multipath will switch to one of the other paths that remain, keeping the storage device
available for reading and writing. The multipath-tools package enables you to manage DM-
Multipath for storage devices, and the typical configuration file is located at
/etc/multipath.conf

Linux LPIC-1 209


THE mdadm COMMAND
The mdadm command is a tool used to manage software-based RAID arrays.
Redundant array of independent disks (RAID) is a set of vendor-independent
specifications that support redundancy and fault tolerance for configurations on
multiple-device storage systems. In a RAID array, data is stored across multiple
physical storage devices, and those devices are combined into a single virtual storage
device. This type of software-based RAID configuration is an alternative to using
device mapper and DM-Multipath. The mdadm tool enables you to create, manage,
and monitor RAID arrays.

Linux LPIC-1 209


LOGICAL VOLUME MANAGER
One major application of the device mapper is the Logical Volume Manager (LVM). LVM maps
whole physical devices and partitions (e.g., /dev/sda1, /dev/sdb2, etc.) into one or more
virtual containers called volume groups. Within these volume groups are one or more logical
volumes. Ultimately, the logical volumes become the storage devices that the system, user, and
applications work with.
Many distributions support LVM, and several actually place the root file system on logical
volumes during installation.

Linux LPIC-1 210


An LVM architecture example.

Linux LPIC-1 211


LVM ADVANTAGES
Compared to traditional physical partition management, LVM provides the following benefits:
• You can dynamically create, delete, and resize volumes without having to reboot the system.
• Day-to-day management of volumes is easier once everything is set up.
• You can map multiple logical volumes across multiple physical devices.
• A logical volume can exceed the size of any one physical device, as long as it doesn't exceed
the total size of devices in the volume group.
• You can create virtual snapshots of each logical volume so you can quickly and easily revert a
volume to a specific state.

One potential downside to LVM is that the initial setup can be somewhat complex.

Linux LPIC-1 212


THE /dev/mapper/ DIRECTORY
The /dev/mapper/ directory contains all of the logical volumes on the system that are
managed by LVM. Devices in this directory are typically formatted as:
/dev/mapper/<volume group name>-<logical volume name>

In some cases, this directory may just include links to the actual logical volume location.

Linux LPIC-1 213


LVM TOOLS
LVM divides its volume management tools into three categories based on the three different
components that make up LVM:
• Physical volume (PV) tools
• Volume group (VG) tools
• Logical volume (LV) tools

Linux LPIC-1 214


PV TOOLS
The following table lists some of LVM's physical volume (PV) tools

Tool Used To
pvscan Scan for all physical devices that are being used as physical volumes.

pvcreate Initialize a drive or partition to use as a physical volume.

pvdisplay List attributes of physical volumes.

pvchange Change attributes of a physical volume.

pvs Display information about physical volumes.


pvck Check the metadata of physical volumes.
pvremove Remove physical volumes.

Linux LPIC-1 215


VG TOOLS
The following table lists some of LVM's volume group (VG) tools.

Tool Used To

vgscan Scan all physical devices for volume groups.

vgcreate Create volume groups.

vgdisplay List attributes of volume groups.

vgchange Change attributes of volume groups.

vgs Display information about volume groups.


vgck Check the metadata of volume groups.

Linux LPIC-1 216


VG TOOLS
The following table lists some of LVM's volume group (VG) tools.

Tool Used To
vgrename Rename a volume group.
vgreduce Remove physical volumes from a volume group to reduce its size.
vgextend Add physical volumes to volume groups.
vgmerge Merge two volume groups.
vgsplit Split a volume group into two.
vgremove Remove volume groups.

Linux LPIC-1 217


LV TOOLS
The following table lists some of LVM's logical volume (LV) tools.

Tool Used To
lvscan Scan all physical devices for logical volumes.
lvcreate Create logical volumes in a volume group.
lvdisplay List attributes of logical volumes.
lvchange Change attributes of logical volumes.
lvs Display information about logical volumes.

Linux LPIC-1 218


LV TOOLS
The following table lists some of LVM's logical volume (LV) tools.

Tool Used To
lvrename Rename logical volumes.
lvreduce Reduce the size of logical volumes.
lvextend Extend the size of logical volumes.
lvresize Resize logical volumes.
lvremove Remove logical volumes.

Linux LPIC-1 219


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 220


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 221


Linux LPIC-1 222
After formatting your partitions and logical volumes with file systems, you need to actually
make it possible for users and the system to work with the file systems. So, in this topic, you'll
make these file systems available by mounting them.

MOUNT POINTS
A mount point is an access point to information stored on a local or remote storage device. The
mount point is typically an empty directory on which a file system is loaded, or mounted, to
make the file system accessible to users. If the directory already has content, the content
becomes invisible to the users until the mounted file system is unmounted.

Linux LPIC-1 223


THE mount COMMAND
The mount command loads a file system to a specified directory so that it can be accessible to
users and applications. You must specify the device to mount as well as the desired mount
point.

SYNTAX
The syntax of the mount command is mount [options] {device name} {mount point}

Linux LPIC-1 224


Mounting partitions on a storage device to specific directories.

Linux LPIC-1 225


mount OPTIONS
You can specify various mount options for a file system. These options are typically included in
the fstab file rather than as command-line arguments.

Option Used To
auto Specify that the device has to be mounted automatically.
noauto Specify that the device should not be mounted automatically
nouser Specify that only the root user can mount a device or a file system.
user Specify that all users can mount a device or a file system.
exec Allow binaries in a file system to be executed.

Linux LPIC-1 226


mount OPTIONS
You can specify various mount options for a file system. These options are typically included in
the fstab file rather than as command-line arguments.

Option Used To
noexec Prevent binaries in a file system from being executed.
ro Mount a file system as read-only.
rw Mount a file system with read and write permissions.
Specify that input and output operations in a file system should be
sync
done synchronously.
Specify that input and output operations in a file system should be
async
done asynchronously.

Linux LPIC-1 227


THE umount COMMAND
After using the mounted file system, it can be disassociated from the directory by unloading, or
unmounting, the file system using the umount command. In order to unmount a file system, it
must not be in use—for example, if a file on that file system is currently open in some
application.

SYNTAX
The syntax of the umount command is umount [options] {mount point}

umount COMMAND OPTIONS


Some common command options for umount are described in the following table.
Option Used To
-f Force a file system to be unmounted despite any detected issues.
Perform a "lazy" unmount, in which the file system is detached from
-l the hierarchy, but references to that file system are not cleaned up
until the file system is no longer being used.
-R Recursively unmount the specified directory mount points.
-t {fs type} Unmount only the file system types specified.
Unmount only the file systems that are mounted with the specified
-O {mount options}
options in the /etc/fstab file.
--fake Test the unmounting procedure without actually performing it.

Linux LPIC-1 228


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 229


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 230


Linux LPIC-1 231
Linux provides you with many tools for modifying file systems after applying them to storage
devices. In this topic, you'll perform various tasks to ensure your file systems are fulfilling your
business needs.

THE /proc/mounts FILE


The /proc/mounts file lists the status of all currently mounted file systems in a format similar
to fstab: the system's name, mount point, file system type, etc. It is actually not a real file, but
part of the virtual file system that represents the status of mounted objects as reported by the
Linux kernel. Typically, you'd read this "file" using a command like cat in order to get the details
you're looking for.
Note that /proc/mounts lists all file systems, not just those on storage drives and partitions. It
may not be the most readable tool to use in case you're only looking for drive information.

THE mtab FILE


The /etc/mtab file is very similar to the /proc/mounts file in that it reports the status of
currently mounted file systems. However, /proc/mounts is typically more accurate and includes
more up-to-date information about the file systems.

Linux LPIC-1 232


THE /proc/partitions FILE
The /proc/partitions file contains information about each partition that is currently attached to
the system. Like /proc/mounts, it is not a real file but part of the virtual file system. The format
of /proc/partitions contains columns, and each column is as follows:
• major — Represents the class of device so that it can be mapped to an appropriate driver.
• minor — Separates partitions into physical devices. This corresponds to the number at the
end of the partition's name.
• #blocks — How many physical blocks the partition takes up.
• name — The name of the partition.

Linux LPIC-1 233


The /proc/partitions file.

Linux LPIC-1 234


THE lsblk COMMAND
The lsblk command displays information about all block storage devices that are currently
available on the system. The output is displayed in a tree-like format with each physical device
at the top of the tree and each partition or logical volume branching off from that device. The
information displayed includes names, major and minor numbers, size, device type, and mount
point.

SYNTAX
The syntax of the lsblk command is lsblk [options] [device name]

lsblk COMMAND OPTIONS


The following table lists some of the options available with the lsblk command.
Option Used To
-a List empty devices as well.
Exclude devices from output that you provide as a list of comma-
-e {device list}
separated major device numbers.
-f Output additional file system information.
-l Output results in list format.
-m Output permissions information for devices.

Linux LPIC-1 235


Listing block storage devices in a tree-like hierarchy.

Linux LPIC-1 236


THE blkid COMMAND
The blkid command offers similar functionality to lsblk, but it simply prints each block device in
a flat format and includes some additional information like device/ partition UUID and file
system type. However, it is preferable to use lsblk -f if you want this additional information.

SYNTAX
The syntax of the blkid command is blkid [options] [device name]

Linux LPIC-1 237


ext TOOLS
When it comes to managing file systems and partitions, some tools are designed to only work
with specific file system types. Some can work with multiple types, but are much better suited
to one or a few specific types. When it comes to ext file systems, there are several tools that
you can use on essentially any generation of the ext type (i.e., ext2/3/4).
Some of the most common and useful tools for managing ext file systems include:
• e2fsck
• resize2fs
• tune2fs
• dumpe2fs

Linux LPIC-1 238


THE fsck COMMAND
The fsck command is used to check the integrity of a file system. File system integrity refers to
the correctness and validity of a file system. Most systems automatically run the fsck command
at boot time so that errors, if any, are detected and corrected before the system is used. File
system errors are usually caused by power failures, hardware failures, or improper shutdown of
the system.
You should unmount the file system before scanning it with fsck to prevent damage to the file
system.

SYNTAX
The syntax of the fsck command is fsck [options] {device/file system name}

REPAIR FILE SYSTEMS


You can use the fsck -r {device/file system name} command to repair a file system. The
command will prompt you to confirm your actions. If you are simultaneously checking multiple
file systems, you should not use this option because it allows you to repair only a single file
system at a time.

Linux LPIC-1 239


Checking the integrity of a file system.

Linux LPIC-1 240


THE resize2fs COMMAND
The resize2fs command is used to enlarge or shrink an ext2/3/4 file system on a device. You
can enlarge a mounted file system, but you must unmount the file system before you can shrink
it. You can specify the desired size of the file system in order to either enlarge or shrink it. If you
don't specify a size, the file system will be resized to the same size as the partition.
It's important to note that resize2fs does not resize partitions, only the file system. You must
use a command like fdisk or an LVM tool to expand the size of the partition/ volume first in
order to then enlarge the file system.

SYNTAX
The syntax of the resize2fs command is resize2fs [options] {device/file system name} [desired
size]

Linux LPIC-1 241


THE tune2fs COMMAND
The tune2fs command helps you configure various "tunable" parameters associated with an
ext2/3/4 file system. Tunable parameters enable you to remove reserved blocks, alter reserved
block count, specify the number of mounts between checks, specify the time interval between
checks, and more.
You can also use tune2fs to add a journal to an existing ext2 or ext3 file system (neither of
which include journaling by default). If the file system is already mounted, the journal will be
visible in the root directory of the file system. If the file system is not mounted, the journal is
hidden.

SYNTAX
The syntax of the tune2fs command is tune2fs [options] {device/ file system name}

Linux LPIC-1 242


tune2fs COMMAND OPTIONS
The tune2fs command has various options.
Option Used To
-j Add an ext3 journal to the existing file system.
Specify the maximum time interval between file system checks in
-i {d|m|w}
days, months, or weeks.
-c {maximum mounts Specify the maximum number of mounts between file system
count} checks.
-C {mount count} Specify the number of times the file system can be mounted.
-r {reserved blocks
Specify the number of reserved file system blocks.
count}
Specify the behavior of the kernel code, whether the file system
-e {continue|remount-
should continue with normal execution, remount the file system in
ro|panic}
read-only mode, or cause a kernel panic, when errors are detected.
List the contents within the superblock (metadata) of the file
-l
system.
-U {UUID} Set the specified UUID for the file system.

Linux LPIC-1 243


SUPERBLOCK
A file system's superblock contains metadata about that file system, including its size,
type, and status. The superblock is critical to the function of the file system, and if it
becomes corrupt, you may be unable to mount and work with the file system. You
can use a tool like fsck to repair the superblock, if necessary.

Linux LPIC-1 243


THE dumpe2fs COMMAND
The dumpe2fs command is used to dump ext2, ext3, and ext4 file system information. It prints
the superblock and block group information for the selected device. This can be useful when
troubleshooting a faulty file system.

Linux LPIC-1 244


SYNTAX
The syntax of the dumpe2fs command is dumpe2fs [options] {device/ file system name}

dumpe2fs COMMAND OPTIONS


The dumpe2fs command has various options.

Option Used To
-x Print a detailed report about block numbers in the file system.

-b Print the bad blocks in the file system.

Force the utility to display the file system status irrespective of the
-f
file system flags.
Display file system data from an image file created using the
-i
e2image command.

Linux LPIC-1 245


XFS TOOLS
There are many tools that enable you to work with the XFS file system. The following table lists
some of those tools

Tool Used To
Display details about the XFS file system, including its block
xfs_info
information.
Change the parameters of an XFS file system, including its label and
xfs_admin
UUID.

xfs_metadump Copy the superblock metadata of the XFS file system to a file.

xfs_growfs Expand the XFS file system to fill the drive size.

xfs_copy Copy the contents of the XFS file system to another location.

xfs_repair Repair and recover a corrupt XFS file system.

xfs_db Debug the XFS file system.

Linux LPIC-1 246


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 247


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 248


Linux LPIC-1 249
Now that you've managed storage at a lower level, you can begin to explore the standard file
system structure that applies to most Linux distributions. You'll be navigating this file structure
all throughout this course, as well as in your daily duties when you're on the job.

TYPES OF FILES
Linux contains regular files that include text files, executable files or programs, input for
programs, and output from programs. Besides these, the Linux file system consists of other
types of files, as described in the following table.

THE file COMMAND


The file command is used to determine the type of file. The syntax of the command is file
[options] {file names}

Linux LPIC-1 250


FILE NAMING CONVENTIONS
A file name is a string of characters that identify a file. By using the right combination of
characters in file names, you can ensure that the files are unique and easy to recognize.
On an ext4 file system, a file name may be up to 255 bytes long and contain any byte except
NULL (\0) and the forward slash (/). File names of user files may not be . and .. as these are
special reserved file names. Various file systems may enforce different requirements for file
names.
Although file names may contain a space, convention on Linux systems dictates that words in a
file name are more frequently demarcated by a hyphen or an underscore, as these are easier to
manage on the command-line.

For example: audit- file.txt or audit_file.txt are acceptable.

Linux LPIC-1 251


THE FILESYSTEM HIERARCHY STANDARD
The Filesystem Hierarchy Standard (FHS) is a collaborative document that specifies a set of
guidelines for the names of files and directories and their locations on Linux systems. Most
Linux distributions are FHS-compliant, and therefore support compatibility with other systems.
The FHS also creates a naming convention that helps administrators, users, and applications
consistently find the files they are looking for, as well as store files where other entities can
easily find them.

Linux LPIC-1 252


STANDARD DIRECTORIES
As defined in the FHS, the top-most directory in a Linux file system is the root directory,
indicated by a single forward slash (/). Below the root directory are various subdirectories that
are standardized as part of the FHS. The above table describes these directories in alphabetical
order.

Linux LPIC-1 253


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 254


/usr SUBDIRECTORIES
The /usr directory contains some important subdirectories.

Subirectory Description
/usr/bin Includes executable programs that can be executed by all users.

/usr/local Includes custom build applications that are stored here by default.

Includes object libraries and internal binaries that are needed by the
/usr/lib
executable programs.
Serves the same purpose as /usr/lib, except that it is meant only for 64-bit
/usr/lib64
systems.
Includes read-only architecture independent files. These files can be shared
/usr/share
among different architectures of an operating system.

Linux LPIC-1 255


THE HOME DIRECTORY
The home directory contains a user's personal files or files that are otherwise specific to that
user. The home directory is where you are placed when you log in to the system. In Linux, by
default, every user except the root user is assigned a subdirectory in /home that corresponds
to their user name. A user can create subdirectories and files within this directory.

The home directory of the root user is /root. This is not to be confused with the root directory
(/), which is the top-most part of the file system hierarchy.

In many shells, including KornShell, C shell, and Bash, the Plde character ( )̃ represents your
home directory.

Linux LPIC-1 256


The contents of the root user's home directory.

Linux LPIC-1 257


THE CURRENT WORKING DIRECTORY
The current working directory (CWD) is the location on the system that you are accessing at
any point in time. For example, when you log in to a system, you are placed in your home
directory. So, your current working directory is your home directory. The current working
directory is represented in shorthand as a single period (.).

Remember, you can enter pwd to identify your current working directory.

Linux LPIC-1 258


THE PARENT DIRECTORY
The parent directory is one level above your current working directory. All directories, except
the root directory, have a parent directory. You can use the double period notation (..) to switch
to the parent directory.

Linux LPIC-1 259


PATHS
A path specifies a location in the file system. It begins with the root directory, the directory at
the top of the directory tree, and ends with the directory or file you want to access. Thus far,
you've worked with paths in order to access various files and directories.

You can refer to a particular file by providing a path to the specific directory that contains the
file.

For example, the home directory jsmith contains a subdirectory, work, which contains a file
named mywork. To refer to that file, use the following path name:
/home/jsmith/work/mywork. Notice that the forward slash (/) character is used to separate
items in the path. The slash that precedes home represents the root directory, from which the
path to the file mywork begins.

Linux LPIC-1 260


ABSOLUTE VS. RELATIVE PATHS
Paths are of two types—absolute and relaPve. An absolute path refers to the specific locaPon
irrespecPve of the current working directory or combined paths. These paths are usually
wriUen with reference to the root directory, and, therefore, start with a forward slash. Paths
that do not begin with a forward slash are called relaPve paths. A relaTve path is the path
relaPve to the current working directory; therefore, the full absolute path need not be
included. These paths can contain the period (.) and double period (..), which are indicaPons for
the current and parent directories.

EXAMPLES
The following examples show accessing the same locaPon using absolute and relaPve paths,
respecPvely.

Using an absolute path:


cd /usr/bin

Using a relaPve path when the CWD is /usr/:


cd bin

Linux LPIC-1 261


FILE SYSTEM NAVIGATION COMMANDS
The following table is a review of file navigation commands you've seen thus far.

Command Used To
Traverse the directory structure using absolute or relative paths to
cd
change your current working directory.
List the files and directories in the current working directory or the
ls relative/absolute path you specify. In long listing format (-l), the first
bit indicates the type of file.

pwd Print the current working directory to the console.

Linux LPIC-1 262


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 263


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 264


Linux LPIC-1 265
COMMON STORAGE ISSUES
Administrators can face a variety of issues with local storage devices. A key aspect of server
management includes ensuring that storage devices are recognized by the system and available
to the user.
Symptom Causes and Solutions
One of your first steps in troubleshooting is to verify the physical connectivity of devices. In
the case of storage devices, ensure the data and power cables are connected. For external
Missing devices storage devices, verify that the USB, FireWire, or other data cables are connected, as well as
the power cord. Linux will detect devices and dynamically create a device file in the /dev
directory. You can check the /dev directory to verify whether Linux has detected the storage
device.
After confirming the physical device is connected, then verify the volumes created on the
storage devices are recognized. Both the parted and the fdisk utilities can be used to verify
Missing
that the partitions exist. In addition, the / proc/partitions file can be checked for basic
volumes
information about the volumes. These tools can also be used to check whether a file system
has been installed on the volume. The two common file systems will be ext4 or XFS.
During the Linux startup process, the /etc/fstab file is checked to see what partitions should
Missing mount be automatically mounted. Mistakes in the /etc/fstab file will result in the volumes not being
points properly mounted or available to the users. The mount command can be used to manually
attach storage volumes on the file system.

THE ulimit COMMAND


The syntax of the ulimit command is ulimit [opTons] [limit]
For example, to set a limit for the maximum number of open file descriptors: ulimit -n 512
You can display all of the current limits by issuing ulimit -a

Linux LPIC-1 266


Symptom Causes and Solutions
Degraded storage refers to a situation where a storage drive in a RAID array has failed.
Degraded Depending on the RAID type, the system may still be able to read from and write to the array,
storage even with a failed drive. Typically, however, the overall performance of the system will be
reduced by the failed drive. The array can be rebuilt with a replacement storage drive to
return to optimal performance.
Investigating storage performance issues begins with considering the technology being used
on the system. On workstations, SATA hard drives may be sufficient, though solid-state drives
(SSDs) are also quite common. Servers typically require a much more efficient I/O system and
Performance a great deal more storage capacity. SCSI, SAS, and SSDs are a common choice for server
issues storage due to their efficiency. These drives are usually part of a RAID array when deployed
on servers. Even when a suitably high performance storage technology is chosen, a failing
disk, controller, or other hardware component of the storage device can lead to performance
issues.
Each file that is opened in Linux is assigned a file descriptor that keeps track of the file when it
is open. It is possible, on a very busy server where a great many files may be opened
Resource simultaneously, that the descriptors could all be consumed. One significant effect of this
exhaustion resource exhaustion is that most Linux commands will not run. You can resolve the issue by
rebooting the server. The ulimit command can then be used to adjust the available number of
file descriptors.
Traditional magnetic hard disk drives may degrade over time. One common symptom of this
Storage aging is bad blocks, or sections of the hard disk drive that cannot be written to or read from.
integrity/bad The file system will automatically mark these blocks and not attempt to use them to store
blocks data. If there are too many bad blocks, performance and storage capacity may be diminished.
Too many bad blocks is also an indication of a failing hard disk drive. You should consider
replacing the hard disk drive immediately.

Linux LPIC-1 267


STORAGE SPACE TRACKING
The df and du commands facilitate storage space tracking. The df command ("disk free")
enables you to view the device's free space, file system, total size, space used, percentage
value of space used, and mount point. The du command ("disk usage") displays how a device is
used, including the size of directory trees and files within it. It also enables you to track space
hogs, which are directories and files that consume large amounts of space on the storage drive.
These are your go-to commands to confirm excessive storage space consumption that might be
causing system issues.

SYNTAX
The syntax of the du and df commands is du/df [options] [object names]

Linux LPIC-1 268


Checking storage space on a device using both the du and df commands

Linux LPIC-1 269


I/O SCHEDULING
I/O scheduling is the process by which the operating system determines the order of input and
output operations as they pertain to block storage devices. Scheduling is important because,
compared to CPU and memory operations, block storage operations are relatively slow—
especially in disk-based technology like hard disk drives. The Linux kernel, therefore, doesn't
just begin writing or reading to a drive in the order that such requests are submitted; instead, it
prioritizes certain requests over others in order to minimize performance issues that can come
with I/O tasks.

Although the kernel handles scheduling, you can actually configure the scheduler with different
behavior types. Some behaviors are more appropriate than others in certain situations, and you
may find that setting a new type increases read/write speeds. Changing the scheduler is
typically done during the troubleshooting process in order to finely tune storage performance
when every bit of that performance matters.

Linux LPIC-1 270


SCHEDULER TYPES
The above table describes some of the different schedulers that are available to modern Linux
kernel versions.

SETTING THE SCHEDULER


You can set the scheduler to use on a particular device by modifying the scheduler file located
at /sys/block/<device name>/queue/scheduler
Setting the scheduler is as simple as echoing the desired option to this file, as in:
echo noop > /sys/block/sda/queue/scheduler

Note that this sets the scheduler for runtime only; the setting will revert upon reboot. To
persist your changes, you must modify the system's boot loader configuration.

Linux LPIC-1 271


THE iostat COMMAND
The iostat utility generates reports on CPU and device usage. For storage, it provides input and
output statistics for block devices and partitions. Using the -d option to specify device
information only, the iostat command lists the following statistics for each storage device:
• Transfers (I/O requests) per second (tps).
• Number of blocks read per second (kB_read/s).
• Number of blocks written per second (kB_wrtn/s).
• The total number of blocks read (kB_read).
• The total number of blocks written (kB_wrtn).

You can use this report to monitor how a storage drive is being used and to identify any
potential bottlenecks. For example, a faulty drive might have lower reads and/or writes per
second than expected. You can also use the report to help you decide how to best distribute
I/O load between the available devices.

SYNTAX
The syntax of the iostat command is iostat [options] [device names]

Linux LPIC-1 272


Displaying storage device usage statistics.

Linux LPIC-1 273


THE ioping COMMAND
The ioping command generates a report of device I/O latency in real-time. It will continuously
"ping" the specified device with requests and print information about each request at the
command-line. By default, this information tracks how long it took an I/O request to finish.
Aside from specifying a device to test, you can also specify a path name to test whatever device
is associated with that path.

Consider using ioping to troubleshoot latency issues with a storage devices, especially if you
believe your read and/or write speeds are slower than they should be.

Linux LPIC-1 274


SYNTAX
The syntax of the ioping command is ioping [options] {file/ directory/device name}

ioping COMMAND OPTIONS


The following table lists some options you can use with the ioping command.

Option Used To
-c {count} Specify the number of I/O requests to perform before stopping.

-i {time} Set the time (interval) between I/O requests.

Set the minimum valid request time. Requests faster than this are
-t {time}
ignored.
Set the maximum valid request time. Requests slower than this are
-T {time}
ignored.

-s {size} Set the size of requests.

Linux LPIC-1 275


STORAGE QUOTAS
A storage quota is the storage space that is allotted to a user for file storage on a computer.
Storage quotas are configured on a per-user basis. File systems that implement storage quotas
can have a soft limit, a grace period, and a hard limit. Once a user exceeds the soft limit, they
are placed in the grace period for a default of seven days. The user is allowed to exceed this
soft limit within this grace period, but cannot exceed the hard limit maximum. If the user goes
below the soft limit, the timer resets. If the user still exceeds the soft limit when the timer
expires, the soft limit is automatically imposed as a hard limit, and the user will be unable to
use any additional storage.
Storage quotas are a good measure to prevent or respond to issues that arise due to excessive
storage use. You can use these quotas to ensure that users are not consuming all of a drive's
space and leaving none for other users or the system.

Linux LPIC-1 276


QUOTA MANAGEMENT COMMANDS
Quota management is the effective allotment and monitoring of quotas for all users. Linux has
various commands that help ease the job of quota management for the system administrator.

QUOTA ACTIVATION
Before you can use these commands, you must actually activate user and/or group quotas on
the file system. You can do this by editing the fstab file to add the options usrquota and
grpquota to the relevant file system.

XFS QUOTAS
You can use the xfs_admin utility to configure quotas on XFS file systems. This utility can run in
both interactive and non-interactive mode. When run noninteractively, use the -c option to
specify which commands to run, and the -x option to enable expert mode, which is required for
most administrative tasks. Tasks include setting limits on writing blocks and inodes, setting
warning limits, generating quota reports, and more.

Linux LPIC-1 277


QUOTA REPORTS
Quota reports are created by the system so you can view storage space usage by each user.
These reports enable you to check which user is taking up maximum disk space. They can also
help you troubleshoot issues with quotas themselves—for example, quotas that are either too
restrictive or too permissive.
A quota report contains the following details:
• The name of the user/group.
• The total number of blocks (in kilobytes) that are being used by the user/group on a file
system.
• The user's/group's storage soft limit.
• The user's/group's storage hard limit.
• The grace period.
• The total number of inodes that have been used on a file system by the user/group.
• The soft limit on inodes.
• The hard limit on inodes.

Linux LPIC-1 278


REPORT GENERATION COMMANDS
Several commands are available for the generation of effective quota reports.
Command Used To
Display the reports for all file systems indicated as read-write
repquota -a
with quotas in the mtab file.

repquota -u {user name} Display the quota report for a particular user.

Display the quota report for a particular user with verbose


quota -uv {user name}
output.

warnquota -u Check if users are not exceeding the allotted quota limit.

warnquota -g Check if groups are not exceeding the allotted quota limit.

Linux LPIC-1 279


ADDITIONAL STORAGE TROUBLESHOOTING TECHNIQUES
Troubleshooting storage issues should start with the simple and work toward the more
complex. Here are a few examples:

If a user claims they cannot create a file, verify that they have the appropriate permissions for
the directory. From there, you might check to ensure the storage area is available (mounted
partitions, both local and network), and that there is free space on the destination storage
location. After those more simple steps, verify that the inode pool has not been exhausted by
using the df -i command. If the inode pool has been exhausted, you'll need investigate the
affected file system to see if it contains many unnecessary files, like temporary files, and delete
them with the rm command.

In the event that a storage location appears to be unavailable, start your troubleshooting by
verifying the physical connection for the storage device. From there, you would verify whether
the storage device is recognized by the system—see the /dev/ and /proc/ directories for that
information. You should also check configuration files for errors, including the /etc/fstab file.
This is also true if you're mounting drives from network servers, such as NFS or Samba. Finally,
you can consider using tools like fsck, the XFS toolset, or the ext4 toolset.

Linux LPIC-1 280


GUIDELINES FOR TROUBLESHOOTING STORAGE ISSUES
Use the following guidelines when troubleshooting storage issues.

TROUBLESHOOT STORAGE ISSUES


• When troubleshooting storage issues:
• Ensure the devices are physically connected to the system.
• Ensure the devices are powered.
• Ensure the devices are turned on, if applicable.
• Verify the device is recognized by the system by checking the /proc/ directory.
• Confirm that the configuration files do not contain any typographical errors.
• Ensure the configuration files have been reloaded if you have made changes to them.
• Confirm that there is enough storage capacity.
• Confirm that the I/O workload is not overwhelming the device.
• Use the partprobe command to cause the system to scan for new storage devices and
partitions.

Linux LPIC-1 281


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 282


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 283


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 284


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 285


In the previous topic, you created a foundation for your Linux® system by managing how the
system and its data is stored. Now, you'll take a more high-level approach to managing the data
itself. By managing files and directories, you'll be able to quickly create, retrieve, and otherwise
process data so that it provides the most benefit to your organization and your day-to-day
administrative tasks.

Linux LPIC-1 286


In this lesson, you will:

• Create and edit text files.


• Search for files.
• Perform various operations on files and directories, including viewing, copying, and
removing them.
• Process text files for easier analysis and use.
• Manipulate file output through redirection, piping, etc.

Linux LPIC-1 287


Linux LPIC-1 288
Although you did some basic file creation and editing tasks earlier, it's time for you to become
more familiar with text-based tools like Vim and GNU nano. Being able to create and edit files is
a critical skill in Linux, as so much of what you configure on the system is done through text
files.

TEXT EDITORS
A text editor is an application that enables you to view, create, or modify the contents of text
files. Text editors were originally created to write programs in source code, but are now used to
edit a wide variety of text-based files. Various types of text editors are compatible with Linux.
However, text editors do not always support the formatting options that word processors
provide. Text editors may work either in the CLI or GUI, and may have different modes of
operation.
Text editors are important because, in Linux, most configuration components are text files:
system configuration, network configuration, kernel configuration, shell environment
configuration, etc. In the CLI, you'll be configuring most of these components by opening the
relevant files in a text editor and adjusting some lines of text. So, being comfortable with a text
editor is essential.

Linux LPIC-1 289


COMMON EDITORS
Many text editors are compatible with Linux. The following table lists some of the most
common ones.

Text Editor Description

A visual text editor that was originally created for Unix®, and was
vi
later cloned into FOSS versions.

Vim The default text editor in most Linux distributions.

Emacs A flexible, powerful, and popular text editor used in Linux and Unix.

gVim The graphical version of the Vim editor.

A simple yet powerful GUI-based text editor used in the GNOME


gedit
desktop environment.

GNU nano A small, user-friendly text editor.

Linux LPIC-1 290


Vim
Vim, a contraction of Vi IMproved, is an extended version of the vi editor. Vim implements a
text-based user interface to advanced text editing, and is favored by many system
administrators and software engineers for its efficiency and ability to be extensively
customized. Vim also includes useful features such as text completion, syntax highlighting, spell
checking, and many more.

Linux LPIC-1 291


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 292


THE vim COMMAND
The vim command invokes the Vim editor. However, the vi command may also be used for this
purpose because it automatically redirects the user to Vim. When entered without a file name
as an argument, the vim command opens a welcome screen by default. Use the syntax vim {file
name} to open a file. If the file does not exist, Vim creates a file by the name specified and
opens the file for editing. Vim supports multiple files being opened simultaneously.

WORKING WITH MULTIPLE WINDOWS


You can choose to display multiple files horizontally or vertically. Press Ctrl+W+V to create a
vertical split, or press Ctrl+W+S to split the screen horizontally.

Linux LPIC-1 293


Vim MODES
Vim is a modal editor, and its different modes decide the functionality of various keys.

Mode Enables Users To

Insert Insert text by typing.

Execute Execute commands within the editor.

Command Perform different editing actions using single keystrokes.

Visual Highlight or select text for copying, deleting, etc.

Linux LPIC-1 294


SWITCH MODES
Command mode is the default mode of Vim, but you can switch from command mode to any
other mode by using a single keystroke.
Some of the keys to switch modes are listed here.

Key Function
i Switches to insert mode and inserts text to left of cursor.
A Switches to insert mode and adds text at end of line.
I Switches to insert mode and inserts text at beginning of line.
o Switches to insert mode and inserts text on new line below cursor.
O Switches to insert mode and inserts text on new line above cursor.
v Switches to visual mode to enable selection, one character at a time.
V Switches to visual mode to enable selection, one line at a time.
: Switches to execute mode to enable users to enter commands.
Esc Returns to command mode.

Linux LPIC-1 295


Switching between modes in Vim.

Linux LPIC-1 296


EXECUTE MODE COMMANDS
In command mode, when you enter the colon (:) operator, a small command prompt section
appears at the bottom-left of the editor. This indicates that you are in execute mode and can
run commands supported by Vim.
Some commands supported by Vim are listed in the following table.
Command Function
:w {file name} Saves file with specified name.
:q Quits when no changes have been made after last save.
:q! Quits, ignoring changes made.
:qa Quits multiple files.
:wq Saves current file and quits.
:e! Reverts to last saved format without closing file.

:!{any Linux command} Executes command and displays results in Vim.

:help Opens Vim's built-in help documentation.

Linux LPIC-1 297


MOTIONS
Motions are single-key shortcuts that are used to navigate through files in command mode.
These keys position the cursor anywhere within a document. They can be used for moving the
cursor through characters, words, lines, or even huge blocks of text.

Linux LPIC-1 298


NAVIGATION USING THE ARROW KEYS
In addition to using the h, j, k, and l keys to navigate through the editor, you can also use the
Up, Down, Left, and Right Arrow keys. The conventional navigation keys such as Home, End,
Page Up, and Page Down also work in Vim.

Navigation Key Used To


$ Move to the end of the current line.
w Move to the next word.
b Move to the previous word.
e Move to the end of the current word or to the end of the next word.
Shift+L Move the cursor to the bottom of the screen.
Shift+H Move the cursor to the first line of the screen.
(Line #) Shift+G Move the cursor to the specified line number.
gg Move the cursor to the first line of the file.
Shift+G Move the cursor to the last line of the file.

Linux LPIC-1 299


EDITING OPERATORS
Editing operators in command mode are powerful tools that can be used to manipulate text
with simple keystrokes. They can also be used in combination with motions to edit multiple
characters.

Editing Operator Used To


x Delete character selected by cursor.
d Delete text.
dd Delete current line.
p Paste text on line below cursor.
P Paste text on line above cursor.
/{text string} Search through document for specified text.
?{text string} Search backward through document for specified text.

Linux LPIC-1 300


COUNTS
A count is a number that multiplies the effect of keystrokes in Vim. It can be used in
combination with motions, operators, or both. When used with a motion, cursor movement is
multiplied according to the count specified. When used with editing operators, the action gets
repeated the number of times specified.
The syntax for using a count with an operator and a motion is operator [count] {motion}

Editing Operator Used To


y Copy text.
yy Copy line above cursor.
c{range of lines}c Begin a change in specified range.
u Undo latest change.
U Undo all changes on current line.
ZZ Write file only if changes were made, then quit Vim.

Linux LPIC-1 301


GNU nano
GNU nano is a small, user-friendly text editor that evolved from the Pico text editor created for
Unix-like systems. It was added to the GNU Project shortly after its initial release. While Vim is a
powerful text editor, it is not the most user-friendly, as evidenced by its multiple modes, bare
interface, and many keystroke commands— some of which are unintuitive. The nano editor, on
the other hand, is more visually helpful in that it displays its command shortcuts at the bottom
of every open file. Likewise, nano has fewer commands than Vim, and most command
keystrokes share Ctrl as a common prefix. It also does not have different modes that you need
to switch between.

Despite these advantages, nano lacks many of the features that make Vim so powerful, like
split screen, text completion, syntax coloring, and more.

Linux LPIC-1 302


The GNU nano interface.

Linux LPIC-1 303


THE nano COMMAND
The nano command invokes the GNU nano editor. Without any arguments, the command will
open a new file for editing, and you can later save this file with a specific name. Use the syntax
nano {file name} to open an existing file. If the file does not exist, nano creates a file by the
name specified and opens the file for editing. Like Vim, nano supports multiple files being
opened simultaneously. These files are opened into different "buffers" that you can switch
between.

Linux LPIC-1 304


nano SHORTCUTS
In GNU nano, the functions you use to work with text files and the editor itself are referred to
as shortcuts. You activate most shortcuts by pressing the Ctrl key (represented as ^ in the
editor) and then pressing the key that corresponds to the function you're trying to perform.
The above table lists some of the common nano shortcuts.

NAVIGATION

Like other text editors, you can navigate in nano using the arrow keys, Page Up, Page Down,
Home, etc. If you are missing these keys, nano also provides shortcuts for them, e.g., Ctrl+V to
navigate to the next page and Ctrl+Y to navigate to the previous page.

COPYING TEXT
Copying parts of text on a line requires you to "mark" the text you want to copy with the Ctrl+^
shortcut. You then navigate your cursor to highlight the text you want to copy. Pressing Alt+^
copies the marked/highlighted text, and Ctrl+U pastes it.

Linux LPIC-1 305


THE gedit TEXT EDITOR
The gedit text editor is the default text editor used in GNOME desktop environments and is a
member of the GNU Project. Unlike Vim and nano, gedit has a GUI with a typical menu-based
design that makes it easy to work with. It also has features like syntax highlighting and spell
checking, and can be customized through plugins. While not as powerful as Vim, gedit may still
be useful in systems that have a desktop environment installed.
Although you can launch gedit from the desktop, you can also use the CLI with the gedit
command. The syntax is similar to vim and nano—no argument opens a new file, whereas
providing a file name as an argument either opens an existing file or creates a new one with
that name.

Linux LPIC-1 306


The gedit interface.

Linux LPIC-1 307


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 308


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 309


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 310


Linux LPIC-1 311
There will be times that you create a file and forget where in the directory structure you put it.
There will also be times when you don't know the exact location of files created by the system,
applications, or other users. In Linux, you have several powerful tools for finding the files you're
looking for.

THE locate COMMAND


The locate command performs a quick search for any specified string in file names and paths
stored in the mlocate database. This database must be updated regularly for the search to be
effective. The results displayed may be restricted to files that users have permissions to access
or execute.

Linux LPIC-1 312


SYNTAX
The syntax of the locate command is locate [options] {string}

locate COMMAND OPTIONS


The locate command supports different options that enable you to make your search more
effective. Some of the options are described in the table.
Option Used To
-r Search for file names using regular expressions.
Display only the number of matching entries found, rather than the
-c
file names.
-e Return only files that exist at the time of search.
-i Ignore the casing in file names or paths.
-n {number of entries} Return only the first few matches up to the specified number.

THE updatedb COMMAND


The updatedb command is used to build a database of files based on the /etc/ updatedb.conf
file. This command is used to update the /var/lib/mlocate/mlocate.db database. The
/etc/updatedb.conf file consists of the paths that should be excluded while building the
database. To add a path that needs to be excluded while building the database, open the /etc/

Linux LPIC-1 313


updatedb.conf file and, in the PRUNEPATH variable, specify the path that need not be
included while building the database. For example, PRUNEPATH="/etc" will exclude
the /etc directory while building the database.
Though this is the default database searched by the locate command, there may be
more databases containing file paths. If the database is not updated before
performing a search, all files created after the last update will be excluded from the
search.

Linux LPIC-1 313


THE find COMMAND
The find command enables you to search a specific location for files and directories that adhere
to some search criteria. It recursively searches the directory structure, including any
subdirectories and their contents, beginning with the search location you enter. You can
perform one or more actions on the files found.

The -type option enables you to specify the type of object you're looking for, such as d for
directory or f for file. The -name option is where you specify the name of the object you're
looking for. The following example searches a user's home directory (and all subdirectories) for
all files named 2019_report:

find /home/user -type f -name 2019_report

SYNTAX
The syntax of the find command is find [options] {search locations} {search criteria} [actions]

Linux LPIC-1 314


find VS. locate COMMANDS
The locate command searches a database and retrieves information on files present on your
system. However, failure to keep this database updated may produce outdated results. The find
command, on the other hand, performs a live search of the file system and may concentrate on
a specific location. The find command may take more time to complete a search than the
locate command.

OPTIONS FOR FILES FOUND


When the system finds a listing that meets your criteria, there are several actions you can
perform on the results. Several of these options are outlined in the following table.

Option Used To
-print Displays the location of the files found.
-exec Executes the command that follows.
-ok Executes the command that follows interactively.
-delete Deletes files found.
-fprint Stores results in the target file.

Linux LPIC-1 315


THE which COMMAND
The which command displays the complete path of a specified command by searching the
directories assigned to the PATH variable. For example, upon entering which cat, the following
output is displayed: /bin/cat

The which command can therefore help you locate where a program has been installed in case
you need to modify this. It can also help you identify which version of a command you're using
if there are multiple binaries of the command stored in different locations, one of which may
be more ideal. By identifying where a command is running from, you can troubleshoot
unexpected behavior from that command.

SYNTAX
The syntax of the which command is which [options] {program names}

Linux LPIC-1 316


Displaying the complete path of a command.

Linux LPIC-1 317


THE whereis COMMAND
The whereis command is used to display various details associated with a command.
For example, when entering whereis ls the following output is displayed: ls: /bin/ls
/usr/share/man/man1/ls.1.gz /usr/ share/man/man1p/ls.1p.gz

Where /bin/ls indicates the location of the ls command and /usr/ share/man/man1/ls.1.gz
/usr/share/man/man1p/ls.1p.gz indicates the location of the man pages for the ls command.

Linux LPIC-1 318


SYNTAX
The syntax of the whereis command is whereis [options] [directory name] {file name}

whereis COMMAND OPTIONS


The whereis command has several options, as described in the following table.

Option Used To
-b Search only for binaries.
-m Search only for manual sections.
-s Search only for sources.
-u Search for unusual entries.

Linux LPIC-1 319


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 320


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 321


Linux LPIC-1 322
There are many ways you can manage a file once you've created and edited it to your liking.
Using various tools, you'll ensure that your files are in the state you expect them to be in.

THE cat COMMAND


The cat command, short for concatenate, can display, combine, and create text files. It is most
frequently used to display the contents of small text files, as it does not have a screen scrolling
capability.
Some of the cat command options are described in the above table.

SYNTAX
The syntax of the cat command is cat [options] {file names}

Linux LPIC-1 323


THE head AND tail COMMANDS
The head command displays the first 10 lines of each file. The tail command displays the last 10
lines of each file. These commands are useful when you only need to see the beginning or the
end of a file. For example, you can check recent log entries by viewing the last 10 lines of a log
file.

Linux LPIC-1 324


SYNTAX
The syntax of the head and tail commands is head/tail [options] {file names}

tail COMMAND OPTIONS


The following are some common options used with the tail command:
• -f — dynamically watch a file (the output will automatically update when the file changes).
• -n {number} — show the specified number of lines, rather than the default of 10. Can also
be used with the head command

Linux LPIC-1 325


THE less AND more COMMANDS
Both the less and more commands are similar in that they enable you to display the contents of
a file and page through those contents if they extend beyond the screen. The less command
typically has additional features that more doesn't, but newer versions of more have added
some of those features. While you're free to use either command, the less command is
generally preferred.

Linux LPIC-1 326


SYNTAX
The syntax of the less and more commands is less/more [options] {file names}

less COMMAND OPTIONS


The following table lists some of the options for the less command.

Option Used To
-e Exit the program the second time it reaches the end of the file.
-E Exit the program the first time it reaches the end of the file.
-i Ignore case in searches.
-n Suppress line numbers.

NAVIGATION
Navigation in less uses many of the same commands you've seen before, like the arrow keys to
scroll line-by-line and Page Up and Page Down to scroll by page. You can also use / to search a
file for a particular text string, and press n and N to move to the next or previous instance of
the searched string, respectively. Press q to quit the program.

Linux LPIC-1 327


THE cp COMMAND
The cp command enables you to copy and then paste a file or directory. The initial object is left
where it is, but an exact duplicate of that object is created at the destination you specify. When
you copy directories, you must specify the -R option to copy the specified directory recursively.

SYNTAX
The syntax of the cp command is cp [options] {file/directory name to copy} {file/directory
name destination}

For example, to copy the ~/myfiles directory and its contents to /opt/myfiles:
cp -R ~/myfiles /opt/myfiles

Linux LPIC-1 328


THE mv COMMAND
The mv command moves files and directories to other locations. It is similar to the cp
command, but does not leave the initial object in place. Therefore, mv is more like a cut and
paste operation.
The Bash shell does not have a dedicated rename command, but instead uses mv to accomplish
that function. The act of "moving" a file or directory and supplying a new name as the
destination essentially renames that object.

SYNTAX
The syntax of the mv command is mv [options] {file/directory name to move} {file/directory
name destination}

For example, to move ~/file1 to /opt/file1: mv ~/file1 /opt/mylist

For renaming purposes, the syntax is mv [options] {old file/ directory name} {new
file/directory name}

Linux LPIC-1 329


THE touch COMMAND
The touch command changes the time of access or modification time of a file to the current
time, or to the time specified in an argument. It is also used to create an empty file with the
specified file name, assuming the file does not exist. This is often useful in testing permissions
or in simply creating files that will later be processed by some application.

SYNTAX
The syntax of the touch command is touch {file names}

Linux LPIC-1 330


THE rm COMMAND
The rm command removes files and directories. You must use the -R option to recursively
remove files, subdirectories, and the parent directory itself.

SYNTAX
The syntax of the rm command is rm [options] {file/directory names}
For example, to remove the ~/myfiles directory and its contents: rm -R ~/myfiles

THE unlink COMMAND


The unlink command is similar to the rm command, but can only remove one file at a time and
cannot remove directories.

Linux LPIC-1 331


THE ls COMMAND
At this point, you've seen much of the power of the ls command to list the contents of
directories, as well as the permissions information of directories and files. The above table
summarizes some of the most useful options that are available with the ls command.

SYNTAX
The syntax of the ls command is ls [options] [file/directory names]

ls COLORS
In the Bash shell, when you execute the ls command, you may have noticed that the results
sometimes appear in different colors. These colors distinguish different types of files. By
default, some of the colors are:
• Default color: Normal/text file
• Blue: Directory
• Sky blue: Symbolic link or audio file
• Green: Executable file
• Yellow with black background: Device
• Pink: Image file
• Red: Archive file
• Red with black background: Broken link

Linux LPIC-1 332


THE mkdir AND rmdir COMMANDS
The mkdir command is used to create (or make) a directory. You supply the name of the
directory as an argument. The rmdir directory is used to remove directories, but only those that
are empty (i.e., contain no files or subdirectories). In order to delete a directory with actual
contents, you must use the rm -R command.

SYNTAX
The syntax of the mkdir and rmdir commands is mkdir/rmdir {directory names}

Linux LPIC-1 333


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 334


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 335


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 336


Linux LPIC-1 337
Beyond performing basic file operations like reading, moving, and copying, you can also
manipulate files so that they are more useful to you. In this topic, you'll process files so that
they're easier to work with based on certain business needs.

THE echo COMMAND


The echo command is used to display a line of text on the terminal. You can also use the echo
command to write text to a file by providing the string after the echo command and redirecting
to the file.

Linux LPIC-1 338


SYNTAX
The syntax of the echo command is echo {string}

THE printf COMMAND


The printf command is similar to echo, but provides the user with much more control over how
the output is formatted. You can supply various format characters within the text you want to
output, using a backslash (\) to indicate when they are being used.

For example: printf "Hello.\n What's your name?" will print:


Hello.
What's your name?
This is because \n is the newline format character, and automatically adds a new line wherever
it is placed.

The printf command also supports conversion characters, which use a percent sign (%) to
indicate when they are being used. Conversion characters are typically used in scripts to change
the output of a variable, like dictating the number of decimal places to print after a precise
calculation.

Linux LPIC-1 339


THE tr COMMAND
The tr command is used to translate a string of characters. It is predominantly used to change
the case of letters in a file. This command acts only on a stream of characters and does not
accept file names as arguments. You must use redirection to actually change a file.

SYNTAX
The syntax of the tr command is tr {character 1} {character 2} where {character 1} is the
character to be replaced.

Linux LPIC-1 340


THE wc COMMAND
The word count (wc) command is used to count the number of lines, words, and characters in a
text file. If multiple files are specified, then the command displays the counts for each file and
the total count for all files.

Linux LPIC-1 341


SYNTAX
The syntax of the wc command is wc [options] {file names}

wc COMMAND OPTIONS
The wc command provides various options that enable you to specify the nature of the output.

Option Used To
-c Display the byte count.
-m Display the character count.
-l Display the newline count.
-w Display the word count.

Linux LPIC-1 342


THE sort COMMAND
The sort command arranges the lines in a file. Common sort command options are provided in
the table.

Option Used To
-k{column numbers} Specify field values. For example, -k2 indicates the second field.
-n Compare and sort lines based on the string numerical value.
Sort fields in descending order. By default, the fields are sorted in
-r
ascending order.
-t{delimiter} Separate one field from another.

SYNTAX
The syntax of the sort command is sort [options] {file names}

Linux LPIC-1 343


Sorting a text file.

Linux LPIC-1 344


THE cut COMMAND
The cut command extracts the specified lines of text from a file. Common cut command
options and their uses are given in the following table.

Option Used To
-c Specify the number of the character to cut from each line.
-d{delimiter} Separate one field from another.
Specify the field numbers to cut on as separated by the delimiter.
-f{field numbers} For example, -f2 indicates the field between the first and second
instances of the delimiter.
-s Suppress a line if the delimiter is not found

SYNTAX
The syntax of the cut command is cut [options] {file names}

Linux LPIC-1 345


Extracting a portion of a log.

Linux LPIC-1 346


THE paste COMMAND
The paste command is used to merge lines from text files horizontally. Each line of an initial file
is a row in the first column; using paste, you specify a second file, and every line of the second
file becomes a row in a new, second column.
By default, the paste command uses a tab space delimiter to separate each column. You can
use the -d option to specify a different delimiter.

For example, you have a file named cities:


New York
Tokyo
London
Lima

You also have a second file named countries:


United States
Japan
England
Peru

Linux LPIC-1 347


The output of paste -d , cities countries is as follows:
New York,United States
Tokyo,Japan
London,England
Lima,Peru

Linux LPIC-1 348


THE diff COMMAND
The diff command is used to compare text files. The command displays the two files and the
differences between them. Using various symbols, the output suggests how you can change
one file to make it identical to the other. Each symbol has a special meaning.

The less than symbol (<) with a line after it means that line should be removed from the first
file because it doesn't appear in the second. The greater than symbol (>) with a line after it
means that line should be added from the second file. In addition, the diff command also
denotes the line numbers for each file that would be affected by deletion, addition, and change
operations.

Linux LPIC-1 349


SYNTAX
The syntax of the diff command is diff {file name 1} {file name 2}

diff COMMAND OPTIONS


The diff command has various options that enable you to specify the nature of the output.

Option Used To
-b Ignore spacing differences.
-i Ignore case differences.
-t Expand tab characters in output lines.
-w Ignore spacing differences and tabs.
-c Display a list of differences with three lines of context.
Output results in unified mode, which presents a more streamlined
-u
format.

Linux LPIC-1 350


THE grep COMMAND
The grep command, in its most basic form, is a search tool. Unlike find or locate, it is not
limited to finding file names; it is most often used to search the contents of a file for a
particular string of text. As output, grep displays each full line of the file that your search
pattern was found in. In this way, you can use grep to both process a text file and read the
contents that are most pertinent to you. For example, you may want to audit a user's login
events by looking at an access log. Instead of reading the entire log or stepping through a
search term in a text editor, you can simply print all of the relevant lines to the screen with the
grep command.

Linux LPIC-1 351


SYNTAX
The syntax of the grep command is grep [options] {search pattern} {file names}

grep COMMAND OPTIONS


The grep command has many options. Several common ones are described in the following
table.
Option Used To
-E {pattern} Match a pattern as an extended regular expression (ERE).
-F {pattern} Match a pattern as a list of fixed strings.
-f {file name} Match patterns contained in the specified file.
-i Ignore casing.
-v Output only lines that don't match the provided pattern.
-c Only print the number of matching lines, not the lines themselves.
Only print the file(s) that have matching lines, not the lines
-l
themselves.
-o Only print the matching part of a line, not the entire line.

Linux LPIC-1 352


USING grep TO FIND FILES
In addition to searching the contents of files, you can use grep to search a directory in
order to locate a certain file. The ls -l | grep audit command returns a long listing of
any files in the current directory whose name contains "audit".
THE egrep COMMAND
The egrep command is essentially the same as the grep -E command. However, egrep
is deprecated, as grep -E is the preferred syntax.

Linux LPIC-1 352


THE awk COMMAND
The awk command performs pattern matching on files. It is based on the AWK programming
language. The awk keyword is followed by the pattern, the action to be performed, and the file
name. The action to be performed is given within curly braces. The pattern and the action to be
performed should be specified within single quotes. If the pattern is not specified, the action is
performed on all input data; however, if the action is not specified, the entire line is printed.
The awk command can be executed from the command-line or from within an awk script file.

The awk command can be used to process text files in a variety of ways, such as extracting text
matching a certain pattern; deleting text matching a certain pattern; adding text matching a
certain pattern; and much more.

SYNTAX
The syntax of the awk command is awk [options] ['patterns {actions}'] {file names}

Linux LPIC-1 353


Searching a log for all entries recorded in January.

Linux LPIC-1 354


PATTERNS
In awk scripts, you can provide patterns along with blocks of code. If a pattern matches any line
in the input file, the code blocks in the script will be executed. Th above table lists the types of
patterns used.

Linux LPIC-1 355


THE sed COMMAND
The sed or stream editor command is a program that you can use to modify text files according
to various parameters. The sed command can also be used for global search and replace
actions.

Linux LPIC-1 356


Deleting lines in a file that contain the term "Apache”.

Linux LPIC-1 357


SYNTAX
The general syntax of the sed command is sed {'option/address/ action'} {file names}

Addresses tell sed to act only on certain lines or to act only on text that matches a given regular
expression pattern. They are optional. Addresses are followed by the action to be performed
when a match is found. The last argument is the name of the input file. The option, address,
and action parameters are typically enclosed within single quotation marks.

Some of the common command options and their uses are given in the following table.

Option Used To
d Delete the lines that match a specific pattern or line number.
-n, p Print only the lines that contain the pattern.
s Substitute the first occurrence of the string in the file.
Globally substitute the original string with the replacement string for
s, g
each occurrence in the file.

Linux LPIC-1 358


THE ln COMMAND
The ln command is used to create a link to a file. Linking enables a file name in one directory
(the link) to point to a file in another directory (the target). A link does not contain data of its
own, only a reference to the target file. Any changes to the link will reflect in the target file. If
you don't specify the link name, the ln command will create the link in your current working
directory.

SYNTAX
The syntax of the ln command is ln [options] {target name} [link name]

ln COMMAND OPTIONS
The ln command has various options. Some of the frequently used options are given in the
following table.

Option Used To
--backup Back up existing destination files.
-f Remove existing destination files.
-s Make symbolic links instead of hard links.
-i Prompt to remove destination files.
-v Print the name of a file before linking.

Linux LPIC-1 359


TYPES OF LINKS
Using the ln command, you can create two types of links: hard and symbolic (soft). Hard and
symbolic links are a feature of the file system and are common in most file systems supported
by Linux. The ext2, ext3, ext4, and XFS file systems all support hard and symbolic links.
A hard link is a reference to another file; it enables the file's data to have more than one name
in different locations in the same file system. Applications treat a hard link as a real file. If the
original file is deleted after a hard link is created, all its contents will still be available in the
linked file. This is because the inode of a hard link is the same as its target; in other words, it
points to the same object on the file system. Hard links cannot be created between two
directories, nor can they be created between two files in different file systems.
A symbolic link is a reference to a file or directory that can span multiple file systems. If the
original file or directory is deleted after a symbolic link is created, then the original content is
lost. This is because the inode of a symbolic link is different than its target; in other words, it
points to a different object on the file system. A symbolic link is also known as a soft link.

EXAMPLES
The following is an example of creating a hard link using the ln command, where /
backup/backup-report is the target of the link, and ~/backup-report is the link itself:
ln /backup/backup-report ~/backup-report

The following is an example of the same, but creating a symbolic link instead of a hard link:
ln -s /backup/backup-report ~/backup-report

Linux LPIC-1 360


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 361


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 362


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 363


Linux LPIC-1 364
All of this management and manipulation of files is useful for more than just looking at the
results in a terminal. When you continue to use the terminal, or log out entirely, you'll want to
ensure that some crucial information is stored in a file for later retrieval and analysis. You'll also
benefit from using multiple commands in conjunction, making your administrative duties more
efficient and powerful.

TEXT STREAMS
A text stream is a sequence of one or more lines of text that applications can leverage to read
from or write to a particular device or system component. This enables the application to
interface with components like the CLI, files, network sockets, and more, while hiding those
components' details from the application.
In most Linux shells, there are three types of streams: standard input, standard output, and
standard error.

Linux LPIC-1 365


STANDARD INPUT
Standard input, or stdin, is a text stream that acts as the source for command input. Standard
input for the Linux command-line is usually generated from the keyboard. In the case of the
GUI, the standard input can also come from the mouse.

Linux LPIC-1 366


STANDARD OUTPUT
Standard output, or stdout, is a text stream that acts as the destination for command output.
By default, standard output from a Linux command is directed to the CLI.

Linux LPIC-1 367


STANDARD ERROR
Standard error, or stderr, is a text stream that is used as the destination for error messages. By
default, the standard error stream prints error messages at the CLI.

Linux LPIC-1 368


INPUT/OUTPUT REDIRECTION
Redirection is the process of accepting input data from a source other than the keyboard and
sending output data to a destination other than the display device. In other words, you can use
redirection to bypass the default devices when working with input/output (I/O). Redirection is
commonly used to accept input from files or send output to files using the stdin, stdout, and
stderr streams.

Linux LPIC-1 369


REDIRECTION OPERATORS
There are several operators that are used to redirect input or output. These operators are
described in the above table.

Example: ls > file1.txt


The output of the ls command will be redirected to a file named file1.txt.

Linux LPIC-1 370


PIPING
Piping is the process of combining the standard I/O streams of commands. It uses the standard
output of one command as the standard input for another command. The output format of the
first command should be compatible with the format that the second command works with.
The pipe operator (|) can be used with most commands in Linux.

PIPING EXAMPLE
The ls -l | grep audit command mentioned earlier that searches for files named "audit" is an
example of using a pipe. The standard output of the ls -l command is fed as standard input into
the grep audit command, so that grep searches for the term within the directory listing.

Linux LPIC-1 371


THE xargs COMMAND
The xargs command reads from standard input and executes a command for each argument
provided. Each argument must be separated by blanks. The pipe operator is used to make the
output of the first command the input for the second command. The xargs command is
commonly used with the find command to operate on each result that is found within the file
or directory search.

SYNTAX
The general syntax of the xargs command is command [options] [arguments] | xargs [options]
{command}

Linux LPIC-1 372


EXAMPLE OF THE xargs COMMAND
Let's say you want to delete all of the files in the /foo directory that have a .pdf extension. You
can use xargs to automate the process:
find /foo -type f -name "*.pdf" | xargs rm

The find command searches for all files in /foo that have a .pdf extension, then pipes the result
to the xargs command. Because the results are delimited by a space, the xargs command will
execute the rm command for each file in the results— removing all PDF files in the directory.

xargs COMMAND OPTIONS


The xargs command has various options
Option Used To
-I {replacement string} Consider each line in the standard input as a single argument.
Read a specified number of lines from the standard input and concatenate them
-L {number of lines}
into one long string.
-p Prompt the user before each command.
Read the maximum number of arguments from the standard input and insert them
-n {number of arguments}
at the end of the command template.
-E {end of string} Represent the end of the standard input.
-t Write each command to the standard error output before executing the command.

Set the maximum allowable size of an argument list to a specified number of


-s {max size}
characters.

Linux LPIC-1 373


THE tee COMMAND
The tee command reads the standard input, sends the output to the default output device (the
CLI), and also copies the output to each specified file. This command enables you to verify the
output of a command immediately as well as store that output in a file for later reference. Like
xargs, tee typically accepts input from another command using the pipe operator.

When used with the -a option, tee appends the output to each output file instead of
overwriting it.

SYNTAX
The general syntax of the tee command is command [options] [arguments] | tee [options]
{file names}

EXAMPLE OF THE tee COMMAND


Let's say you want to check the contents of a directory and also output those contents to a file
to process later. You could issue separate commands to do this, or you can use the tee
command like so:

ls -l | tee listing.txt

Linux LPIC-1 374


THE /dev/null FILE
The /dev/null file, also known as the null device, is a file that discards all data written to it.
Typically, you'd redirect an output stream to this file in order to confirm that the write
operation was successful without actually writing to anything. This makes the file useful in
testing commands, scripts, and other software. It is also useful in suppressing error information
in commands by redirecting error output (2>) to the /dev/null file.

Linux LPIC-1 375


TERMINAL REDIRECTION
A running process in Linux can be controlled by a terminal (CLI), and multiple terminals can run
at once. Each controlling terminal is assigned an identifier. This identifier usually takes the
format /dev/tty# where # is a number unique to that terminal. You can redirect standard input
and output to another controlling terminal by referencing its /dev/tty number. This can be
useful when you need to redirect text streams between different running processes.

Linux LPIC-1 376


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 377


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 378


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 379


One of the defining features of Linux® is that it is modular, enabling you to adjust low-level
system configurations at boot and during operation. This provides you with a great deal of
flexibility as far as adjusting how your system runs and what types of devices it can leverage. In
this topic, you'll explore more about the Linux kernel and some of its features, and then you'll
customize the kernel to meet your unique business needs.

Linux LPIC-1 380


In this topic, you will:

• Identify the role and functions of the Linux kernel.


• Install and configure kernel modules.
• Monitor kernel modules.

Linux LPIC-1 381


Linux LPIC-1 382
You'll begin by identifying some of the key concepts and components that make up the Linux
kernel. This will give you a better sense of what services the kernel provides and how you might
go about customizing those services.

KERNEL
The kernel is the core of an operating system. All other components rely on it. The kernel
manages file system access, memory, processes, devices, and resource allocation on a system.
The kernel also controls all the hardware devices plugged into the system. It is one of the first
elements to be loaded on startup and remains in the main memory during the computer's
operation. The kernel also contains system-level commands and other functions that are
normally hidden from users.

Linux LPIC-1 383


The elements managed by a kernel.

Linux LPIC-1 384


KERNEL SPACE AND USER SPACE
Kernels tend to divide software running in memory into two spaces: kernel space and user
space. The kernel space is simply where the kernel executes the services that it provides. The
user space is the area of memory that includes everything outside of kernel space. This can
include everything from high-level applications that the user interacts with directly, to
processes that run in the background, to various low-level system libraries.

Software running in user space is able to access resources provided by kernel space through the
use of system calls. These calls provide a user space application with the resources it needs to
perform a task. For example, an application might issue a system call to the kernel so that it can
leverage input/output (I/O) services that write data to a storage device.

The split between these two memory regions is useful because it promotes greater stability and
security. Software in one space cannot necessarily interfere with software in the other.

Linux LPIC-1 385


The different kernel spaces.

Linux LPIC-1 386


TYPES OF KERNELS
Kernels can be classified as monolithic or microkernel. In a monolithic kernel, all system
modules, such as device drivers or file systems, run in kernel space. As a result, a monolithic
kernel can interact quickly with devices. However, its main disadvantage is its size, which leads
to higher consumption of RAM. In addition, a failure in a device driver can lead to system
instability in a monolithic kernel.
In a microkernel architecture, the kernel itself runs the minimum amount of resources
necessary to actually implement a fully functional operating system. Compared to monolithic
kernels, microkernels have smaller kernel spaces and instead have larger user spaces. This
means microkernels are smaller in overall size and consume less memory. In addition, they are
typically more stable. However, microkernels tend to offer worse performance than monolithic
kernels.

DEVICE DRIVERS
A device driver is a software program that enables a computer's operating system to identify
the characteristics and functions of a hardware device, communicate with it, and control its
operations. It acts as an interface between the operating system and hardware devices such as
storage drives, printers, scanners, monitors, and keyboards. Device drivers can be included in
the operating system or installed on demand.

Linux LPIC-1 387


THE LINUX KERNEL
The Linux kernel is a free and open source monolithic kernel that manages all other resources
on the operating system. As a monolithic kernel, device drivers run within kernel space and
have full access to hardware. The architecture of the Linux kernel provides many useful
features, including virtual memory management, support for TCP/IP networking, shared
libraries, and many more.

One important quality of the Linux kernel is its modularity. This enables users to configure and
extend kernel functionality to meet their needs.

The Linux kernel is continually updated by creator Linus Torvalds and many other volunteers.
Each new version of the kernel is given a kernel version number to distinguish it from past and
future versions. The current naming convention for kernel versions is major.minor where major
is the major version number and minor is the minor version number. For example, version 4.19
was released in October 2018.

Linux LPIC-1 388


KERNEL VERSION HISTORY
For versions 2.6.39 and prior, the kernel number format was w.x.y.z where w is the major
version number, x is the major revision number, y is the minor revision number, and z is the
patch number
After 2.6.39, Torvalds decided to shorten the version number format, and the next version
number was 3.0. After 3.19, rather than proceed to 3.20, Torvalds decided to jump to 4.0. This
was for readability purposes, not due to any technical advances. Newer versions of the kernel
will continue this trend of avoiding large minor numbers.

Linux LPIC-1 389


THE uname COMMAND
By default, uname prints the name of the kernel—Linux. You can view the kernel version
number of your current system by using the uname -r command. You can also enter uname -i
to view the hardware platform. To print all information, enter the uname –a command.

Linux LPIC-1 390


Viewing kernel information.

Linux LPIC-1 391


Kernel Layer Function

Handles system calls sent from user applications to the kernel. This enables user space
System Call applications to request services from the kernel space, like processing time and memory
Interface allocation.
(SCI) This layer also enables the kernel to schedule and process system calls and manage multiple
system calls simultaneously.
Handles different processes by allocating separate execution space on the processor and
Process ensuring that the running of one process does not interfere with other processes.
management Through scheduling, the kernel implements sharing of processor time for executing multiple
processes.
Manages the computer's memory, which is one of the complex tasks performed by the kernel.
Like processor sharing, the system's memory also needs to be shared among different user space
Memory resources.
management The kernel maps or allocates the available memory to applications or programs on request and
frees the memory automatically when the execution of the programs is complete, so that it can
be allocated to other programs.
Manages the filesystem, which involves storing, organizing, and tracking files and data on a
computer.
File system
The kernel also supports a virtual file system (VFS) that provides an abstract view of the
management
underlying data that is organized under complex structures, so that it appears to be a single
structure.
Manages devices by controlling device access and interfacing between user applications and
Device hardware devices of the computer.
management When a user space application sends a system call, the kernel reads the request and passes it on
to the drivers that manage the activities of that particular device.

Linux LPIC-1 392


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 393


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 394


Linux LPIC-1 395
KERNEL MODULES
A kernel module is a system-level object that extends the functionality of the kernel. It can be
dynamically loaded into the kernel or unloaded from the kernel when required. It enables the
kernel to update or recompile itself without requiring the system to reboot.

The advantages of kernel modules are:


• They reduce the burden on the kernel because otherwise all of the modules' functionality
would have to be added directly to the kernel.
• Dynamic loading of kernel modules facilitates lower memory consumption.
• They avoid having to rebuild and reboot the system when new functionality is required.

Kernel module file consists of a .ko extension. Modules built for a specific kernel version may
not be compatible with another version of the kernel.

Linux LPIC-1 396


THE /usr/lib/ DIRECTORY
The /usr/lib/ directory contains shared libraries and binaries for general programs and
software packages. The files in this directory are not meant to be executed by the user or
custom shell scripts. More specifically, the /usr/lib/modules/ directory contains the modules
of different kernel versions that are installed. It holds a directory named after the kernel's
version number. Inside this directory, modules are stored across various subdirectories based
on the categories they belong to. For example, a Bluetooth® driver may be stored in:
/usr/lib/modules/<kernel version>/kernel/drivers/bluetooth/

KERNEL MODULE SUBDIRECTORIES


Inside /usr/lib/modules/<kernel version>/kernel/ are several subdirectories, some of which
are described in the following table.
Directory Contains Modules For
arch Architecture-specific support.
crypto Encryption and other cryptographic functions.
drivers Various types of hardware.
fs Various types of file systems.
net Networking components such as firewalls and protocols.

Linux LPIC-1 397


KERNEL MODULE MANAGEMENT COMMANDS
Kernel module management commands enable you to view, load, unload, or modify kernel
modules.

Command Used To
Display the currently loaded kernel modules, their sizes, usage
lsmod
details, and their dependent modules.
Display information about a particular kernel module, such as the
file name of the module, license, description, author's name,
modinfo module version number, dependent modules, and other parameters
or attributes. The syntax of this command is modinfo [options]
{module name}
Install a module into the currently running kernel. This command
insmod inserts only the specified module and does not insert any dependent
modules. The syntax of this command is insmod {module name}
Remove a module from the currently running kernel. The syntax of
rmmod
this command is rmmod {module name}

Linux LPIC-1 398


THE modprobe COMMAND
The modprobe command is used to add or remove modules from a kernel. This command is
capable of loading all the dependent modules before inserting the specified module. It is
therefore preferred over using the insmod and rmmod commands.
To add modules using modprobe, use the -a option and specify the modules you want to add.
To unload a module, use the -r option and specify the modules you want to remove.

SYNTAX
The syntax of the modprobe command is modprobe [options] [module names]

modprobe COMMAND OPTIONS


In addition to options for adding and removing modules, the modprobe command has more
options.

Option Used To
-f Force the module to be inserted or removed.
Conduct a dry run, i.e., output results without actually executing
-n
operations.
-s Print errors to the system log (syslog) rather than stderr.
-v Enable verbose mode.

Linux LPIC-1 399


THE depmod COMMAND
In order for modprobe to accurately install dependent modules, it reads the modules.dep file
to identify how modules are linked to one another. The depmod command is used to update
this database of dependencies so that modprobe can function properly.
The depmod command searches the contents of /lib/modules/<kernel version>/ for each
module. A module may export a "symbol", indicating that it can provide a service to other
modules. Other modules may call these exported symbols in their own code to leverage their
capabilities. So, depmod builds the modules.dep file by aggregating all instances of symbols
being exported and used.

SYNTAX
The syntax of the depmod command is depmod [options]

MORE ON SYMBOLS
Symbols provide a way for modules to call upon the functions or other programming objects of
other modules. For example, module1 has a C function named foo() that performs some useful
task. Another module, module2, wants to use foo() when it is linked to the kernel, rather than
incorporate that routine in its own code. This is only possible if module1 explicitly exports foo()
for external use. It does this by using EXPORT_SYMBOL() or one of its variants on the function.
The foo() function then becomes available as a symbol for any other module in the kernel to
leverage.

Linux LPIC-1 400


KERNEL MODULE CONFIGURATION
The /etc/modprobe.conf file is a configuration file that contains settings that apply persistently
to all the modules loaded on the system. It is used to configure modules and their
dependencies and also specify module aliases. An alias is just an alternative name to use for a
module.
In newer Linux distros, this file is deprecated. The /etc/modprobe.d/ directory is used instead,
and contains various .conf files. Other than creating aliases, these files can tell modprobe to
run additional modules with specific options when your chosen module is loaded into the
kernel. This enables the chosen module to leverage another module's functionality without
actually loading it into the kernel. You might do this when your module doesn't directly depend
on a second module, but does run better if that second module is installed.

Linux LPIC-1 401


CONFIGURATION FILE COMMANDS
Files ending in .conf in the /etc/modprobe.d/ directory can use one of several commands.

Command Used To
Specify an alternative name for a module with a
alias {alternative name} {module name}
long name.
Ignore internal aliases, which occur when modules
blacklist {module name}
define their own aliases.
Run the specified command without inserting the
install {module name} {command}
module into the kernel.

Linux LPIC-1 402


KERNEL PARAMETERS
In addition to loading modules into the kernel at runtime, you can also change some of the
kernel's parameters while it is running. You can use these parameters to improve system
performance, harden security, configure networking limitations, change virtual memory
settings, and more.

The /proc/sys/ directory lists the parameters that you can configure on your system. Like the
directories containing kernel modules, this /proc/sys/ directory is divided into several
categories, including the following.
Directory Includes Parameters Related To
crypto Encryption and other cryptographic services.
debug Debugging the kernel.
dev Specific hardware devices.
fs File system data.
kernel Miscellaneous kernel functionality.
net Networking functionality.
user User space limitations.
vm Virtual memory management.

Linux LPIC-1 403


THE sysctl COMMAND
The sysctl command is used to view or set kernel parameters at runtime. It has various options,
as defined in the following table.

Option Used To
-a Display all parameters and their current values.
-w {parameter}={value} Set a parameter value.
Load sysctl settings from the specified file, or /etc/sysctl.conf if no
-p[file name]
file name is provided.
-e Ignore errors about unknown keys.
Apply a command to parameters matching a given pattern, using
-r {pattern}
extended regular expressions.

Linux LPIC-1 404


SYNTAX
The syntax of the sysctl command is sysctl [options]

THE /etc/sysctl.conf FILE


The /etc/sysctl.conf file enables configuration changes to a running Linux kernel. These
changes might include improvements to networking, security configurations, or logging of
information.

Linux LPIC-1 405


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 406


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 407


Linux LPIC-1 408
THE /proc/ DIRECTORY
The /proc/ directory is a virtual file system (VFS) that provides significant information about the
kernel's running process. Some of the files in the /proc/ directory are listed in the following
table.

Option Used To
Options passed to the kernel by the boot loader at boot time,
/proc/cmdline
such as mounting the kernel as read-only.
CPU information, such as its architecture, name, clock speed,
/proc/cpuinfo
cache size, and more.
A list of character and block device drivers loaded into the
/proc/devices
currently running kernel.
A list of file systems types that are supported by the kernel, as
/proc/filesystems
well as if any are currently mounted.
Information about RAM usage, including total memory, free
/proc/meminfo
memory, and much more.
Information about modules currently installed on the system. An
/proc/modules
alternative to the lsmod command.
/proc/stat Various statistics about the system since it was last rebooted.

Linux LPIC-1 409


THE /proc/version FILE
The /proc/version file specifies several points of information about the Linux kernel:
• The version of the Linux kernel currently running.
• The version of the GNU Compiler Collection (GCC) used to compile the kernel.
• The user name of the kernel compiler.
• The time the kernel was compiled.
The version of the kernel may impact system functionality, so you can use this file to validate
that version.

Linux LPIC-1 410


The /proc/version file.

Linux LPIC-1 411


THE dmesg COMMAND
The dmesg ("display message" or "driver message") command is used to print any messages
that have been sent to the kernel's message buffer during and after system boot. Device drivers
send messages to the kernel indicating the status of modules and parameters that the drivers
interface with. These drivers can also send diagnostic messages to the kernel in case they
encounter errors. Other kernel components can also send messages to the buffer.

In addition to using the dmesg command, you can also access the message buffer from the
/var/log/dmesg file. In either case, you can leverage dmesg to look for potential issues with
kernel components or to validate that certain modules are being loaded.

Linux LPIC-1 412


SYNTAX
The syntax of the dmesg command is dmesg [options]

dmesg COMMAND OPTIONS


You can use various options with the dmesg command.
Option Used To
-c Clear the kernel buffer after printing its contents.
Restrict output to the specified comma-separated list of facilities. A facility
-f {facility list} is a component category that is producing messages, such as user for user-
level messages.
Restrict output to the specified comma-separated list of levels. A level
-l {level list} defines a message's nature and priority, such as notice for messages that
aren't considered critical.
Display a human-readable version of the time of each message as well as its
-e
delta, or the difference in time between subsequent messages.
-L Color-code messages for easier readability.
Output in a human-friendly format, combining both -e and -L options and
-H
using a text pager.
-h List the available options, as well as the available facilities and levels.

Linux LPIC-1 413


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 414


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 415


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 416


Now that you've configured the kernel, you can learn more about how the kernel is loaded into
memory and how the operating system actually starts. You'll also configure this boot process to
your liking, ensuring that the Linux® workspace operates as intended from the very beginning.

Linux LPIC-1 417


In this topic, you will:

• Configure components that make up the Linux boot process.


• Configure the GNU GRUB 2 boot loader.

Linux LPIC-1 418


Linux LPIC-1 419
To begin with, you must become familiar with how exactly Linux boots, as well as identify
various components that make up the boot process. In addition, you'll configure some of these
components to alter the boot process to fit your needs.

BOOTING
Booting is the process of starting or restarting a computer and loading an operating system for
the user to access. In the boot process, a booting environment reads a small program that is
stored in read-only memory (ROM). This program then executes various operations in RAM that
bootstrap the operating system and make it available for use.

Linux, like other operating systems, must be booted for it to function. There are various options
associated with the boot process that you can configure, if necessary.

Linux LPIC-1 420


BOOT LOADER
A boot loader is the small program stored in ROM that loads the kernel from a storage device,
and then starts the operating system. A boot environment like BIOS reads the boot loader from
ROM so that the boot loader can execute the necessary operations to start the process.

Boot loaders are able to protect the boot process with a password to prevent unauthorized
booting of the system. In addition, boot loaders can load more than one operating system into
the computer's memory, but the user needs to select the desired operating system to use
during boot.

Linux LPIC-1 421


BOOT LOADER COMPONENTS
The boot loader uses three main components that work together to systematically load the
operating system in stages.

Component Description

The first component of the boot loader. It is loaded by a boot


environment on startup and has a fixed size of 512 bytes. Its main
Boot sector program
function is to load the second stage boot loader; however, it can
also load another sector or a kernel.
Second stage boot
Loads the operating system and contains a kernel loader.
loader
Controls the installation of drive sectors and can be run only when
Boot loader installer booting from a drive. It coordinates the activities of the boot sector
and the boot loader.

Linux LPIC-1 422


BIOS
The Basic Input/Output System (BIOS) is a standard for firmware interfaces and is stored on a
computer motherboard's ROM chip. When a computer with BIOS is powered on, the BIOS
firmware is the first to run; this enables it to test the various hardware components in a
computer, as well as run a boot loader so that an operating system can start. The BIOS has
access to the ports used by basic hardware input devices like a mouse and keyboard. Users can
also load up a BIOS interface instead of an operating system to make various hardware-level
changes. For several decades, BIOS was the dominant standard in the home and enterprise
computer industry.

Linux LPIC-1 423


A BIOS interface.

Linux LPIC-1 424


UEFI
Unified Extensible Firmware Interface (UEFI) is newer firmware technology that has largely
replaced BIOS by bringing with it several key advantages. UEFI runs faster than BIOS, can
operate within a greater amount of memory, can access storage drives of currently
unattainable sizes, can access more hardware types, and has improved security protections.
Most modern motherboards, as well as the pre-assembled PCs that use them, ship with UEFI.
Like BIOS, UEFI provides an environment with which to execute a boot loader, and ultimately
start up the operating system for the user to work with.

PASSWORD PROTECTION
One security feature that both BIOS and UEFI include is the ability to set a password. If this
password is not provided at boot time, the system will not boot. Since BIOS/UEFI firmware
differs between hardware manufacturer, the process of setting this password is not consistent.
However, most firmware places this password protection option in a "Security" or "Password"
section.

Linux LPIC-1 425


ADDITIONAL BOOT OPTIONS
BIOS and UEFI are not the only environments you can boot Linux from. The following table
describes some additional boot options.
Boot Option Description
An ISO image is a system image, originally that of an optical disc. Today, it is commonly used
as a file format for packaging and distributing images of operating systems that users can
boot from, as well as use to install the OS. Typically, you'd write the ISO image to an optical
Boot from ISO
disc or USB thumb drive, then insert the media into the computer and instruct a boot
environment like UEFI to boot from that media. ISOs are also commonly used to construct
virtual machines.
Preboot Execution Environment (PXE) is a part of the UEFI standard that enables a client to
retrieve the necessary boot loader and system files from a server over the network. The
client configures UEFI to boot from PXE, and during the startup process, it will search for
PXE
Dynamic Host Configuration Protocol (DHCP) servers that also act as PXE servers. Once the
proper server is found, the server transfers the necessary boot files to the client over the
Trivial File Transfer Protocol (TFTP).
Clients can also acquire boot data over a network from content delivery protocols like
Boot from Hypertext Transfer Protocol (HTTP) and File Transfer Protocol (FTP). These are typically
HTTP/FTP faster, more reliable, and more secure than the standard TFTP protocol used in PXE. Open
source implementations of PXE, like iPXE, extend PXE support to include these protocols.
This is another network boot option. Rather than store system files on a local storage drive, a
client will mount an NFS share as its root file system. The share must be prepared ahead of
Boot from NFS time and stored on an NFS server that the client can retrieve the files from. Therefore, the
client does not store data locally, but on the NFS server. DHCP, TFTP, and other network
protocols can be used to communicate the necessary boot data in such an environment.

Linux LPIC-1 426


SECTORS
A sector is the smallest unit of storage read from or written to a drive. A sector stores 512 bytes
of data by default. On hard disk drives, a collection of sectors is called a track. The number of
sectors in a track may vary, and so does their capacity to hold data. The size of a sector can be
altered when formatting the drive.

Linux LPIC-1 427


Working with sectors while partitioning a drive.

Linux LPIC-1 428


MBR
The master boot record (MBR) is the first physical sector on a storage drive and a type of
partition structure. The MBR boot sector contains the boot loader that loads the operating
system into memory. It also contains the partition table of the storage drive. MBR determines
what sectors are available to each partition, as well as which partition is considered bootable
and which partitions are not.

For many years, MBR was the dominant partition structure used in Linux and other operating
systems. However, it has three major disadvantages:
• The maximum storage space of an MBR-partitioned drive is two terabytes.
• MBR-partitioned drives can have a maximum of four primary partitions.
• The boot data is stored in one sector, which increases the risk of corruption

Linux LPIC-1 429


GPT
The GUID Partition Table (GPT) is a successor to MBR that makes up for the latter's
shortcomings. Like MBR, it is a partition structure, but it employs a more modern design and is
part of the UEFI standard. Every partition on a drive is assigned a globally unique identifier—a
GUID—to distinguish it from every other partition on (theoretically) every drive.

The storage space and partition number maximums are so large that they are not currently
achievable, and any limitations are going to be imposed by the file system type or operating
system kernel, rather than GPT itself. GPT also has the advantage of storing its boot data in
multiple locations on a drive to enhance redundancy. If the primary location is corrupted, GPT
can leverage one of the other copies to restore the boot data.

Whenever possible, partitioning a drive with GPT is preferable to MBR.

RAW PARTITION
Other than formatting a partition as MBR or GPT, you can also format a partition as raw. A raw
partition enables users and applications to read from and write to a block storage device
directly, without using the system cache. This is useful in situations where software like a
database management system (DBMS) has its own caching mechanism. The DBMS has greater
control over I/O caching in a raw partition and can bypass the caching normally done by the
kernel.

Linux LPIC-1 430


Initrd
The initial ramdisk (initrd) refers to the root file system that is temporarily loaded into memory
upon system boot. The initrd loads along with the kernel, which controls its functionality. The
initrd enables the system to be started in two phases. In the first phase, the system is booted
with the minimal set of modules required to load the main or the permanent root file system.
In the second phase, when the main root file system is mounted, the previously mounted initrd
file system is removed and the user space boot process continues.

The initrd is useful because there are many potential variables that can complicate the boot
process. For example, the kernel needs to find and load the necessary device driver modules,
as well as the actual root file system itself. There's also the possibility that the root file system
uses one of several advanced storage methods, like LVM or NFS, which have different mount
requirements than a standard partition. Rather than hardcode all of this behavior in the kernel
and introduce bloat, the initrd's temporary root file system can handle these tasks.

Linux LPIC-1 431


THE initrd IMAGE
The Linux initrd image is an archive file containing all the essential files that are required for
booting the operating system. It can be built or customized to include additional modules,
remove unnecessary modules, or update existing modules. Typically, this image is stored in the
/boot directory.

Linux LPIC-1 432


THE mkinitrd COMMAND
The mkinitrd command is used to create the initrd image for preloading the kernel modules.

Linux LPIC-1 433


Various options of the mkinitrd command are given in the following table.

Option Used To

Load a module in the initrd image before the loading of other


--preload={module name}
modules.
Load a module in the initrd image after the loading of other
--with={module name}
modules.

-f Overwrite an existing initrd image file.

--nocompress Disable the compression of the initrd image.

SYNTAX
The syntax of the mkinitrd command is mkinitrd [options] {initrd image name} {kernel
version}

The following example creates an initrd image from the current kernel version and names the
image initrd-<kernel version>.img:
mkinitrd /boot/initrd-$(uname -r).img $(uname -r)

Linux LPIC-1 434


THE /boot/ DIRECTORY
As defined by the Filesystem Hierarchy Standard (FHS), the /boot/ directory contains files that
are used to facilitate the Linux boot process. The following table describes some of the files and
subdirectories in /boot/ that are of note.
Option Description
• Contains config files for GRUB boot loader.
/boot/grub/
• /boot/grub2/ is for GRUB version 2.
• Contains boot files for EFI system partition (ESP).
/boot/efi/ • Boot loader, device driver, system app files executed by UEFI.
• Boot loader files named with .efi extension.
• initramfs image; alternative to initrd.
/boot/initramfs • Doesn't require special driver to be compiled with kernel.
• Dynamically sizable archive.
• Compressed executable of Linux kernel.
/boot/vmlinuz • Boot loader loads file into memory during boot.
• vmlinux is non-compressed version used for debugging.

THE dracut COMMAND


The dracut command is used to generate an initramfs image, similar to how mkinitrd is used to
generate an initrd image. In fact, on some distributions, mkinitrd is a compatibility wrapper
that calls the dracut command.
An example of using the dracut command to create an initramfs image is as follows:
dracut /boot/initramfs-$(uname -r).img $(uname -r)

Linux LPIC-1 435


THE BOOT PROCESS
The boot process is repeated each time your computer is started by loading the operating
system from a storage device. It involves a series of sequential steps that can be divided into
BIOS/UEFI initialization, boot loader, kernel and initrd/initramfs initialization, and boot scripts.

Linux LPIC-1 436


The following is an example boot process that uses an initrd image:
1. The processor checks for the BIOS/UEFI firmware and executes it. This is also where the power-on
self-test (POST) occurs.
2. BIOS/UEFI checks for bootable media from internal storage devices or peripherals like USB thumb
drives and DVD-ROMs. It locates a valid device to boot the system.
3. BIOS/UEFI loads the primary boot loader from the MBR/GPT partition into memory. It also loads the
partition table along with it.
4. The user is prompted by GRUB 2 to select the operating system they want to boot. If the user does
not respond, then the default operating system will be booted.
5. The boot loader determines the kernel and locates the corresponding kernel binary. It then uploads
the respective initrd image into memory and transfers control of the boot process to the kernel.
6. The kernel configures the available hardware drivers, including processors, I/O subsystems, and
storage devices. It decompresses the initrd image and mounts it to load the necessary drivers. If the
system implemented any virtual devices, such as LVM or software RAID, then they are initialized.
7. The kernel mounts the main root partition and releases unused memory. To set up the user
environment, the systemd program is run. It becomes process ID 1.
8. The systemd program searches for the default.target file, which contains details about the services
to be started. It mounts the file system based on the /etc/fstab file and begins the process of
starting services. On most systems, the target will either be multi-user.target or graphical.target.
9. If graphical mode is selected, then a display manager like XDM or KDM is started and the login
window is displayed on the screen.
10. The user enters a user name and password to log in to the system.
11. The system authenticates the user. If the user is valid, then various profile files are executed.
12. The shell is started and the system is ready for the user to work on.

Linux LPIC-1 437


KERNEL PANIC
Kernel panic is a mechanism by which the system detects there has been a fatal error and
responds to it. A fatal error typically results in the system becoming unstable or totally
unusable. Software that handles kernel panics will display an error message to the user and
dump the current state of kernel memory to a storage device for later debugging. Depending
on how the system is configured, the panic handler will either reboot the system automatically,
or wait for the user to do so.
In Linux, kernel panic can happen for a number of reasons and at any point during operation,
but it is usually experienced during the boot process. Common causes include the following:
• The kernel itself is corrupted or otherwise improperly configured.
• The systemd program is not executed during boot, leaving the system unusable.
• The kernel cannot find or otherwise cannot mount the main root file system.
• Malfunctioning or incompatible hardware is loaded into the kernel on boot.

Linux LPIC-1 438


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 439


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 440


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 441


Linux LPIC-1 442
GNU GRUB
The GNU GRand Unified Bootloader (GNU GRUB) is a boot loader developed by the GNU
Project that became popular on Unix-like systems. It enables users to choose which operating
system or kernel version to boot in a multi-platform environment. Although the original version
of GRUB was the primary boot loader for Linux distributions, it had several limitations and was
eventually phased out in favor of a newer version of GRUB. This original version is sometimes
referred to as GRUB legacy.

Linux LPIC-1 443


GRUB 2 IMPROVEMENTS
GRUB 2 is more than simply a newer version of GRUB; it is a complete redesign and rewrite of
the GRUB system. GRUB 2 offers administrators more control over the boot process, boot
devices, and boot behavior. In addition, it comes with several improvements, including:
• Support for non-x86 architecture platforms.
• Support for live booting (booting an OS from storage media and running the OS
• entirely in memory, without installation).
• Support for partition UUIDs.
• Support for dynamically loading modules that extend GRUB's functionality.
• Ability to configure the boot loader through scripts.
• Rescue mode, which attempts to fix boot issues like corrupted or missing
• configurations.
• Support for custom graphical boot menus and themes.

Because of these improvements, GRUB 2 has become the default boot loader on almost all
modern Linux distributions.

Linux LPIC-1 444


GRUB 2 INSTALLATION
The grub2-install command is used to install the GRUB 2 boot loader on a storage device. It
copies GRUB 2 files into the /boot/grub2 directory and, on some platforms, installs GRUB 2
into the boot sector. However, grub2-install applies to BIOS systems, not UEFI. To install GRUB
2 on a UEFI system, use a package manager to install the grub2-efi package. Installing this
package will copy GRUB 2 files onto the EFI system partition (ESP) in the /boot/efi directory.
SYNTAX
The syntax of the grub2-install command is grub2-install [options] [device name]
grub2-install COMMAND OPTIONS
The following are some options you can use with the grub2-install command:
Option Used To
Preload the specified kernel modules with the GRUB 2 boot
--modules {module names}
loader.
--install-modules {module Install only the specified modules and their dependencies,
names} rather than the default of installing all available modules.
--directory {directory name} Install files from the specified directory, rather than the default.
Specify the target platform to install GRUB 2 for, rather than the
--target {target platform}
platform that is currently running
--boot-directory {directory Specify the boot directory to install GRUB 2 files to, rather than
name} the default /boot/ directory.
--force Install GRUB 2 regardless of detected issues.

Linux LPIC-1 445


THE grub.cfg FILE
The grub.cfg file is the main configuration file for the GRUB 2 boot loader. On BIOS systems, it is
located in the /boot/grub2/ directory. On UEFI systems, it is located
in the /boot/efi/EFI/<distro>/ directory. For example, on CentOS 7, the path is:
/boot/efi/EFI/centos/grub.cfg

Linux LPIC-1 446


This file is an executable shell script. Don't edit this file directly, as it is generated using a
specific command that leverages configuration scripts stored elsewhere on the file system.

Linux LPIC-1 447


THE /etc/grub.d/ DIRECTORY
The /etc/grub.d/ directory contains scripts that are used to build the main grub.cfg file. Each
script provides various functions to GRUB 2 and is numbered so that the scripts can execute in
a sequence. It's usually not a good idea to edit the existing scripts in this directory. If you want
to add a custom script, then you can place it in this directory with a ##_ file name prefix,
depending on what order you want the script to be executed in. You can also add your script to
the existing 40_custom file so that it executes last by default.

Linux LPIC-1 448


GRUB 2 BOOT MENU CUSTOMIZATION
The /etc/grub.d/40_custom file enables the customization of the menu presented to the user
during the boot process. GRUB 2 will offer the user a menu of installed operating systems to
choose from. This choice is useful for multi-boot scenarios (more than one operating system
available on the computer), booting to different Linux kernels, or for booting into a rescue
mode. The menu contents may be customized by editing the /etc/grub.d/40_custom file,
enabling an administrator to specify the order of the menu choices, provide user-friendly
names, and to password protect menu entries.

Linux LPIC-1 449


GRUB 2 PASSWORD GENERATION
You can generate a password hash to protect the boot menu by using the grub2- mkpasswd-
pbkdf2 command.

Linux LPIC-1 450


THE /etc/default/grub FILE
The /etc/default/grub file contains GRUB 2 display menu settings that are read by the
/etc/grub.d/ scripts and built into the grub.cfg file. It enables you to change options such as
how many seconds GRUB 2 will wait before automatically selecting the default boot option;
whether or not GRUB 2 will order kernel versions in a sub-menu; whether or not GRUB 2 will
display the menu in a graphical terminal; and more.

Linux LPIC-1 451


The /etc/default/grub file.

Linux LPIC-1 452


THE grub2-mkconfig COMMAND
The grub2-mkconfig command generates a new grub.cfg configuration file, and is used to
update an existing grub.cfg file. The grub2-mkconfig command combines the configuration file
templates in the /etc/grub.d/ directory with the settings in /etc/default/grub to generate the
grub.cfg configuration file.

Linux LPIC-1 453


The process of editing GRUB 2 configuration files.
On some distributions, this command is simply grub-mkconfig

SYNTAX
The syntax of the grub2-mkconfig command is grub2-mkconfig [-o {file name}]

Linux LPIC-1 454


The process of configuring GRUB 2 from the boot menu.

Linux LPIC-1 455


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 456


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 457


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 458


So far, you've managed several elements of Linux® that are fundamental to its operation. This
will help you get your systems up-and-running. You're not done, however; there are still specific
components and features that you can fine-tune to meet your needs. In this topic, you'll start
by managing components that contribute to the overall system environment.

Linux LPIC-1 459


In this lesson, you will:

• Configure localization options such as character sets and environment variables.


• Configure graphical user interfaces (GUIs).
• Manage services.
• Troubleshoot process issues.
• Troubleshoot system performance issues by analyzing the CPU and memory.

Linux LPIC-1 460


Linux LPIC-1 461
LOCALIZATION
In the world of operating systems, localization is the process of adapting system components
for use within a distinct culture, other than the culture that the system was originally designed
for. In a practical sense, this usually means translating interface components into specific
languages; converting measurements into the system used in a specific region; configuring the
keyboard layout that the user works with; setting the date and time attributes of a specific
location; and more.

Localizing a Linux system is important for organizations that provide Linux services to personnel
and customers all over the world. An administrator in Japan will likely be more comfortable
working on a Linux server if that server is localized to use the Japanese language, rather than
English. Working with the local time and with a compatible keyboard will also enhance the user
experience for international users.

Linux LPIC-1 462


THE /usr/share/zoneinfo/ DIRECTORY
The /usr/share/zoneinfo/ directory is a container for all of the regional time zones that you can
configure the system to use. Subdirectories in this container usually organize languages by
region; for example, the Africa subdirectory includes time zone files for specific countries or
cities within the continent.

The individual files are not raw text files, but are special files used by the system. One way to
change the system's time zone is by creating a symbolic link to one of these individual time
zone files to the /etc/localtime file.

Linux LPIC-1 463


The /usr/share/zoneinfo directory.

Linux LPIC-1 464


THE /etc/timezone FILE
In some Debian-based distros, /etc/timezone can be used to view the time zone. This text file
lists the time zone by the region structure you'd see in the /usr/share/zoneinfo directory. For
example, the file might include the text Europe/Berlin to indicate that the system is using the
zone that this city is in.

Linux LPIC-1 465


THE date COMMAND
The date command is used to print the date in a specified format. The date command will print
the date based on the /etc/localtime file. By default, it will print the date in the following
format:
<day of week> <month> <day> <24 hour time ##:##:##> <time zone> <year>
Wed Oct 31 15:03:16 GMT 2018

You can also format the time using a number of different formatting options. You initialize the
formatting options with a plus sign (+), and each option is prefaced with a percent sign (%). For
example, to retrieve the week number (out of 52 weeks a year), you'd enter date +%V

You can also use the date command to change the system's date by including the -s option with
a provided argument.

Linux LPIC-1 466


SYNTAX
The syntax of the date command is date [options] [format]

FORMATTING OPTIONS
The following table lists some of the formatting options available.
Formatting Option Prints
%A The full weekday name.
%B The full month name.
%F The date in YYYY-MM-DD format.
%H The hour in 24-hour format.
%I The hour in 12-hour format.
%j The day of the year.
%S Seconds.
%V The week of the year.
%x The date representation based on the locale.
%X The time representation based on the locale.
%Y The year.

Linux LPIC-1 467


THE timedatectl COMMAND
The timedatectl command is used to set system date and time information. It can take one of
several subcommands, as detailed in the following table.

Subcommand Used To
Show the current date and time information, including local time,
status universal time, RTC time, time zone, and more. This is the same as
issuing timedatectl by itself.
Set the system's time to the time provided. The format should be as
set-time
follows: 2018-10-31 15:03:16
Set the system's time zone to the time zone provided. The zone is in
set-timezone
the format specified by the /usr/share/ zoneinfo structure.
List all available time zones in the format specified by the
list-timezones
/usr/share/zoneinfo structure.
Enable or disable synchronization with a Network Time Protocol
set-ntp {0|1}
(NTP) server.

Linux LPIC-1 468


SYNTAX
The syntax of the timedatectl command is timedatectl [options] [subcommand]

timedatectl COMMAND OPTIONS


The following table lists some of the options for the timedatectl command.

Option Used To
Execute the operation on the remote host specified by IP address or
-H {remote host}
hostname.
Execute the operation on the remote host specified by IP address or
--no-ask-password
hostname.
Synchronize the local (system) clock based on the hardware clock
--adjust-system-clock
when setting the hardware clock.
-M {local container} Execute the operation on a local container.
CLOCK TYPES
The timedatectl command exposes three different clocks that the system can use:
• The local clock. This clock reflects the current time in the system's locale (i.e., the time
zone).
• The universal time. This clock reflects the time irrespective of the local time zone. It uses the
international standard Coordinated Universal Time (UTC), which is the same as Greenwich
Mean Time (GMT).

Linux LPIC-1 469


• The hardware clock. As the name implies, this clock functions at the hardware
level and keeps time even when the computer is powered off. An OS will derive the
current time from this hardware clock. Any OS can also adjust the hardware clock,
but it's usually a good idea to keep it at UTC. The hardware clock is also known as
the real-time clock (RTC).

SETTING THE HARDWARE CLOCK


Using timedatectl it is possible to set the hardware clock to be equal to the local
time. However, this is not advisable because the RTC is not automatically updated. It
is only updated by external facilities like other installed operating systems. Multiple
OSs can adjust the RTC for daylight savings time (DST), causing an over-correction.

Linux LPIC-1 469


THE hwclock COMMAND
The hwclock command enables you to view and set the hardware clock. As mentioned before,
it is strongly recommended that you keep the hardware clock aligned with UTC to prevent over-
correction by other operating systems.
You can also use the hwclock command to adjust the systematic drift. The systematic drift is
the predictable amount of time that the hardware clock gains or loses each day, making it
inaccurate and throwing it out of alignment with the system clock. The /etc/adjtime file records
information about when and by how much the hardware clock is changed. The hwclock
command can then consult this file to identify the drift value, which it can use to correct the
clock's time.

SYNTAX
The syntax of the hwclock command is hwclock [options]

hwclock COMMAND OPTIONS


The following are some of the command options used with the hwclock command.
Option Used To
--set Set the hardware clock to the provided date and time.
-u Set the hardware clock to UTC.
-s Set the system time from the hardware clock.
--adjust Add or subtract time from the hardware clock to account for systematic drift.

Linux LPIC-1 470


THE localectl COMMAND
The localectl command is used to view and configure the system locale and keyboard layout
settings. A system's locale determines how it will represent various culture-specific elements,
the most prominent of which is the language used in the interface. However, a locale can also
determine factors such as how date and time are formatted, how monetary values are
formatted, and more. Keyboard layouts can be configured independently of the locale and will
determine how each physical key press is interpreted by the operating system. There are many
keyboards with different physical layouts, so the system needs to be configured with the
correct one or else the wrong character may be entered.

Like the timedatectl command, the localectl command offers various subcommands for
managing the system locale and keyboard layout.

Subcommand Used To
Show the current locale and keyboard layout. This is the same as issuing
status
localectl by itself.
set-locale Set the system locale to the locale provided.
list-locales List all available locales on the system.
set-keymap Set the keyboard layout to the provided layout.
list-keymaps List all available keyboard layouts on the system.

Linux LPIC-1 471


SYNTAX
The syntax of the localectl command is localectl [options] [subcommand]

localectl COMMAND OPTIONS


The following table lists some of the options for the localectl command.

Option Used To
Execute the operation on the remote host specified by IP address or
-H {remote host}
hostname.
Prevent the user from being asked to authenticate when performing a
--no-ask-password
privileged task.
--no-pager Prevent the output from being piped into a paging utility.
Prevent a keymap change for the console from also being applied to the
--no-convert
X display server, and vice versa.

Linux LPIC-1 472


CHARACTER SETS AND ENCODING
Character encoding is the process of converting text into bytes, and decoding is the process of
converting bytes into text. Both of these concepts are important because text is much easier
for humans to interact with, whereas computers process data in bytes. Therefore, there needs
to be an intermediary process that enables both entities to interface with the same
information.

In many systems, the default encoding is UTF-8 using the Unicode character set. For example,
the capital letter C is associated with the positional number U+0043 in Unicode. UTF-8 encodes
this number (43) in binary as 01000011. However, not all software uses this encoding. For
example, some software might default to an older encoding standard like ASCII. If you've ever
opened a text file and seen garbled and unreadable characters and symbols, then the text
editor is probably assuming the wrong encoding.

In Linux, the locale settings determine what encoding scheme the system will use. The same
general locale may have different encoding options. For example, de_DE.utf8 and
de_DE.iso88591 both set Germany and the German language as the locale, but the former sets
the encoding as UTF-8 and the latter sets an ASCII encoding standard.

Linux LPIC-1 473


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 474


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 475


Linux LPIC-1 476
The CLI is not the only interface that Linux is capable of providing to the user. In some cases,
users will want to work with a graphical user interface (GUI) for a more visual experience. So, in
this topic, you'll configure multiple GUIs to help certain users be more productive and access
features that aren't available in a non-visual CLI.

GUIs
A graphical user interface (GUI) enables users to interact with a system or application through
visual design elements rather than pure text as in a command-line interface (CLI). In Linux, a
GUI provides similar functionality to the GUIs of other operating systems like Windows® and
macOS®. Users can select icons that represent files, folders, and programs to open or modify
them; configure settings through menus; interact with applications through a windowed
interface; and work from a desktop environment.

Linux LPIC-1 477


As you've seen, GUIs in Linux are optional and are commonly used in workstation or other non-
server roles. GUIs add an extra layer of performance overhead, especially since drawing visual
elements consumes much more processing power and memory than simple text. So, they are
less commonly used on servers where performance is paramount. Still, this is not universally
true, as many administrators prefer to work in a GUI environment, or at least have access to
one even if they spend most of their time entering commands. GUIs can emulate a CLI that you
enter commands into, so you're not limited to using the visual interface.

Linux LPIC-1 478


DISPLAY SERVERS
A display server is the component of a GUI that constructs and manages the windowing system
and other visual elements that can be drawn on the screen. Display servers accept client input
requests and send them to appropriate kernel modules for processing. Likewise, they also
manage the process of receiving requests from an application to display output to the client.

As the name implies, display servers manage communications over a specific network- aware
protocol. This enables remote clients to access GUI elements of a Linux system, like specific
windows. However, the server can still provide its services to local clients.

Linux supports several different display servers. Two of the most prominent are implemented in
the X Window System and Wayland.

Linux LPIC-1 479


THE X WINDOW SYSTEM
The X Window System, also known as X11 or X, is a platform-independent display server and
windowing system that was developed by the Massachusetts Institute of Technology (MIT) in
1984.

Like all display servers, the X server coordinates client input and application output to
determine how to draw elements on the screen. The X server also communicates with a
separate compositor. The compositor reads a memory buffer that each application writes to,
then uses the information in this buffer to combine each individual application window on the
screen so that multiple windows can appear at once. Whenever the X server receives an event
(e.g., a button was clicked and must now be highlighted), it must inform the compositor so that
it can re-composite the portion of the screen that is affected by the event.

Linux LPIC-1 480


The X Window System architecture.

Linux LPIC-1 481


X.ORG SERVER
X.Org Server is the free and open source reference implementation of the X Window System
for Linux and other Unix-like operating systems. Released in 2004, it quickly became the de
facto display server on many Linux distributions. Prior to X.Org Server, the main
implementation of X in Linux was XFree86, which eventually changed to a custom license that
the free software community found GPL-incompatible. Thus, XFree86 was forked into X.Org
Server.

Linux LPIC-1 482


WAYLAND
Wayland is both a display server and its reference implementation in Unix-like operating
systems that is meant to improve upon and replace the X Window System. The primary
difference between Wayland and X is that, in Wayland, the compositor is the server rather than
a separate component. This enables clients to exchange events directly with the compositor,
cutting out the X server as a middle man.

Wayland was first released in 2008, and although X.Org Server still dominates in Linux
distributions, adoption of Wayland has been slowly increasing. For example, Fedora® started
using Wayland as its default display server starting with version 25, released in November of
2016.

Linux LPIC-1 483


The Wayland architecture.

Linux LPIC-1 484


X VS. WAYLAND
Wayland offers several improvements over X, including:
• In X, the X server must determine which window an event applies to. It can't always do this
correctly, because the separate compositor controls how the window is redrawn through
actions like resizing and rotation—information that the X server doesn't necessarily
understand. Because the compositor and server are one in Wayland, this is not an issue.
• In X, the compositor must fetch event data from the server, which can introduce latency. In
Wayland, the compositor receives events directly from the client, mitigating latency issues.
• Wayland simplifies the graphical rendering process by enabling the client to perform its own
rendering.
• Although Wayland is not network-aware in the same way as X, it can still leverage remote
desktop protocols for controlling a GUI environment over a network.
• Older implementations of X do not isolate the data I/O of each window, whereas Wayland
does. This helps ensure the security of data.
DISADVANTAGES TO WAYLAND
Although Wayland improves upon X in almost every way, there are still some issues with
Wayland. For example, Canonical® made Wayland the default display server for Ubuntu® 17.10
in October 2017. In April 2018, for the release of Ubuntu 18.04, Canonical announced that it
was switching back to X.Org Server for three primary reasons:
• Screen sharing software tends to work better under X.Org Server than Wayland.
• Remote desktop software tends to work better under X.Org Server than Wayland.
• It's easier to recover from crashes under X.Org Server than Wayland.
However, Canonical still expressed its commitment to Wayland in the future.

Linux LPIC-1 485


DESKTOP ENVIRONMENT
A desktop environment, also known as a window manager, is a client to a display server that
tells the server how to draw graphical elements on the screen. In other words, the desktop
environment controls the look and feel of the GUI for the entire operating system, providing a
common graphical interface for applications running in the environment.

Desktop environments implement the desktop metaphor, in which the user's monitor is treated
as if it were the top of a physical desk, where various objects are placed and accessible to the
person sitting at the desk. The primary structural element of a desktop metaphor is the
application window, and within each window there can exist various graphical elements like
buttons, icons, menus, toolbars, and more.

Linux LPIC-1 486


Desktop environments also provide a graphical login screen and can be customized to run every
time the system boots. In most cases, the desktop environment will also come packaged with a
variety of different GUI applications, like a file browser, web browser, text editor, and more.

Linux LPIC-1 487


SPECIFIC DESKTOP ENVIRONMENTS
There are many desktop environments available for Linux, the most common of which are
described in the above table.

CHOOSING THE RIGHT DESKTOP ENVIRONMENT


None of these desktop environments is an objectively "right" choice. Which environment you
choose will ultimately come down to personal preference and your comfort level with each.
You need to try each environment in order to know which is best for you.

Linux LPIC-1 488


REMOTE DESKTOP
Remote desktop is a concept in which a client connects to a remote system over a network,
and is able to sign in to and use the desktop environment of that system. Remote desktop
sessions are useful in situations where you must configure a server that has a GUI, but you
aren't physically located at that system. In addition, remote desktop sessions are used in an
environment where the user connects to and works with their remote computer as if it were
located in front of them—in other words, the remote session becomes their primary desktop.

The client computer typically constructs the remote session in its own window, and, when that
window has focus, any input on the local client (e.g., a keystroke) gets translated and sent to
the remote desktop as if the keystroke were being performed on that system directly.

Linux LPIC-1 489


REMOTE DESKTOP SOFTWARE
There are many software packages available for Linux that enable remote desktop sessions.
Software typically comes in two forms: a client application that you install on the computer
you're physically located at, and a companion server application that you install on the remote
system you're trying to connect to.

Linux LPIC-1 490


VNC and xrdp.

Linux LPIC-1 491


CONSOLE REDIRECTION
Console redirection is the process of forwarding input and output through a serial connection
rather than through any I/O peripherals that are directly attached to the system. This enables
the system with console redirection to send display output data along a serial cable and
eventually to a remote client. Likewise, the remote client can redirect its keyboard input along a
serial connection so that it gets sent to the remote server.

Ultimately, console redirection enables administrators to remotely configure systems in a pre-


boot environment like BIOS/UEFI. Without an operating system like Linux loaded, typical
methods of remote access like SSH and remote desktop will not be available. Using console
redirection, administrators can change the BIOS/UEFI settings of multiple machines over a
network, even when those machines have no I/O devices directly attached.

Linux LPIC-1 492


SSH PORT FORWARDING
Secure Shell (SSH) is a remote access protocol that encrypts transmissions over a network. It is
the most commonly used protocol for accessing the command-line interface of a Linux server.
You can use SSH to issue commands to the server as if you were typing into its CLI directly. It
can be used as a tunnel to carry other kinds of network communications securely, including
remote desktop traffic.
The process of tunneling an application through SSH to secure it in transmission is called SSH
port forwarding. There are two main types: local and remote forwarding. In local forwarding,
the local client listens for connections on a port, and then tunnels any active connection to a
remote server using SSH. One use case for local forwarding is to remotely access a system over
the Internet using a protocol like VNC. When you connect to the VNC server with your local
VNC client, that traffic (usually over a port like 5900) will be forwarded through SSH, securing it.
In remote forwarding, the SSH server forwards inbound client traffic to another system on a
different port. One use case for remote forwarding is setting up a VNC server on a local system
and forwarding all VNC traffic to a port on a remote client. Whenever the remote client
connects to this port using localhost (their own network address), they can establish a remote
desktop connection with the local server.

X FORWARDING
As you know, X (X11) is network-aware and can enable clients to access GUI elements over a
network. You can forward X traffic through an SSH tunnel in order to encrypt these
communications.

Linux LPIC-1 493


ACCESSIBILITY OPTIONS
Each desktop environment has its own accessibility options for accommodating people with
disabilities.

Linux LPIC-1 494


Some common options include:
• A screen reader that reads all of the highlighted screen elements.
• A magnifier that zooms in on specific sections of the screen.
• Increasing the size of specific elements like text and the mouse pointer.
• An on-screen keyboard that enables users to click to type text using the mouse, instead of
using a physical keyboard.
• Keyboard accessibility options, including:
v Sticky keys, enabling users to press one key at a time instead of holding down
multiple keys at once in order to activate a keyboard shortcut.
v Repeat keys, enabling the user to hold down a key in order to repeatedly enter it.
v Toggle keys, enabling the system to beep when keys like Caps Lock and Num Lock are
pressed.
• Visual themes like high contrast that make the screen easier to read for certain people with
visual impairments.

Linux LPIC-1 495


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 496


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 497


Linux LPIC-1 498
Services are how the operating system provides functionality to users and applications, and as
such, can be managed just as any other part of Linux. In this topic, you'll start and stop services
to control available system functionality.

SERVICES AND DAEMONS


A Linux service is software that responds to requests from other programs to provide some sort
of specialized functionality. Services can be broadly classified as critical services and non-critical
services. Critical services are the core services that are vital for the functioning of the Linux
system. Non-critical services are services that are initiated by applications installed on the
system.
Most services are implemented in the form of daemons, which are running programs (i.e.,
processes) that operate in the background without the need for human intervention. Daemons
lie dormant until an event triggers them into activity. Some daemons operate at regular
intervals. Most daemons are started when the system boots. Daemons can be started by the
operating system, by applications, or manually by the user.

Linux LPIC-1 499


SERVICE MANAGEMENT
Service management is the lifecycle process of starting services, modifying their running state,
and stopping them. The system can manage services itself, or users can manage services
manually depending on their needs. Service management is important in operating systems like
Linux because it enables administrators to configure the functionality that their servers provide.
It can also help administrators diagnose and troubleshoot issues that affect or are caused by
running programs.

Linux LPIC-1 500


SYSTEM INITIALIZATION
System initialization is the process that begins when the kernel first loads. It involves the
loading of the operating system and its various components, including the boot process. System
initialization is carried out by an init daemon in Linux—the "parent of all processes." The init
daemon refers to a configuration file and initiates the processes listed in it. This prepares the
system to run the required software. The init daemon runs continuously until the system is
powered off, and programs on the system will not run without it.

On Linux, there are two main methods that initialize a system: SysVinit and systemd. The
method that is active on your Linux system will affect how you manage services on that system.

Linux LPIC-1 501


THE systemd SUITE
The systemd software suite provides an init method for initializing a system. It also provides
tools for managing services on the system that derive from the init daemon. The systemd suite
was designed as a replacement for other methods like SysVinit, and is now the dominant init
method in modern Linux distributions.

The systemd suite offers several improvements over older methods. For example, it supports
parallelization (starting programs at the same time for quicker boot) and reduces shell
overhead. In systemd, Control Groups (cgroups) are used to track processes instead of process
IDs (PIDs), which provides better isolation and categorization for processes.

Linux LPIC-1 502


systemd UNIT FILES
Unit files are configuration files that systemd uses to determine how it will handle units, which
are system resources that systemd can manage. Resources can include network services, block
storage devices, peripheral devices, file systems, and much more. Daemons access and manage
these resources. Resources are defined in one of several categories of unit files, making them
easier to manage. A unit file's extension defines its category; e.g., a .automount file includes
instructions for automatically mounting a mount point defined in a .mount unit file. Unit files
are written in a declarative language using directives that tell systemd what to do.

Linux LPIC-1 503


Unit files can exist in multiple locations. The standard location that is used by software to install
unit files is the /lib/systemd/system/ directory. However, you shouldn't edit the unit files in this
directory. If you want to modify a unit file's functionality, you should use the
/etc/systemd/system/ directory. Because unit files in this directory take precedence over files
elsewhere, you can replace them here. If you want to modify only a portion of the unit file, you
can create a directory named after the unit file with .d appended to it, then create a file within
this directory that has a .conf extension. You can use this .conf file to extend or override
specific functionality within the unit file.

ENVIRONMENT VARIABLES
Unit files can also be used to set system environment variables/parameters, which are values
that are passed from a parent process to any child process it creates. By adding directives for an
environment variable, you can make it easier for a service or other unit to work with custom
values.
As an example, the rescue.service unit file sets the following Environment directive:
[Service]
Environment=HOME=/root

The HOME environment variable is therefore set to the root user's home directory, enabling
the rescue mode daemon to log in to the shell with that path as its home directory. When
configuring your own unit files, you could use a similar directive, perhaps supplying a different
path. You can also set any variable you want—not just HOME.

Linux LPIC-1 504


systemd TARGETS
In systemd, targets are a method of grouping unit configuration files together, typically to
represent specific modes of operation. Each .target file is used to determine one of several
ways in which the system can operate, such as running with just a CLI; running with a graphical
desktop environment; initiating a system shut down; and more. Therefore, you can activate a
target in order to boot into the desired environment.

Target files include dependency information that enables these different modes of operation.
For example, graphical.target will boot the system into a GUI environment. It does this by
referencing other unit files like gdm.service (the GNOME Display Manager) that are required in
order to initialize the GUI and its related components.

Linux LPIC-1 505


An example of how a target file interacts with other systemd components.

Linux LPIC-1 506


THE systemctl COMMAND
The systemctl command enables you to control the systemd init daemon. You can view running
services, manage (enable/disable) services to run at boot or in the current session, determine
the status of these services, and manage the system target.

SYNTAX
The syntax of the systemctl command is systemctl [options] [subcommand] [arguments]

systemctl COMMAND OPTIONS


The systemctl command has many options, some of which are described in the following table.
Option Used To
-t {unit file type} Specify the unit file types to perform the operation on.
-a List all unit files or properties, regardless of state.
Prevent the reloading of configuration changes when enabling or
--no-reload
disabling a service.
Prevent users from being asked to authenticate when performing
--no-ask-password
privileged operations.
--runtime Make changes temporary so that they will not be present after a reboot.
Execute the operation on the remote host specified by IP address or
-H {remote host}
hostname.
--no-pager Prevent the output from being piped into a paging utility.

Linux LPIC-1 507


You can do all this through various subcommands issued along with the systemctl command, as
detailed in the following table.

Subcommand Used To
status {service} Retrieve service status.
enable {service} Enable service to start on boot.
disable {service} Disable service so it doesn't start on boot.
start {service} Activate service immediately.
stop {service} Deactivate service immediately.
restart {service} Restart service immediately.
set-default {target} Set default target for system to use on boot.
isolate {target} Force system to immediately change to target.
mask {unit file} Prevent unit file from being enabled or activated.
daemon-reload Reload daemon and all unit files.

Linux LPIC-1 508


EXAMPLE OF SWITCHING TARGETS
One example of using the systemctl command to change targets is when an administrator
needs to work in a GUI for a short period of time. It's common to configure a Linux server to
boot by default to the CLI (multi-user.target). An administrator might switch to the GUI
(graphical.target) for a particular task, and then switch the server back to multi-user.target
when the task is complete. The administrator would then leave the server in the more efficient
CLI configuration after the task.
The process can be stepped out as follows:
1. The server is started to the multi-user.target by default.
2. The administrator logs on to the server at the CLI and enters the following command to
start the GUI: systemctl isolate graphical.target
3. The administrator completes their administrative tasks.
4. The administrator enters the following command to return the server to the more efficient
CLI configuration: systemctl isolate multi-user.target

THE hostnamectl COMMAND


In most cases, systemctl is used to control services, but there are some additional systemd
commands that you can use. For example, hostnamectl enables you to
view the system's network hostname and other information about the system's hardware and
the Linux kernel it is running. You can also use this command to change the system's hostname.
The syntax of the hostnamectl command is hostnamectl [options] [subcommand] [arguments]

For example, to set the hostname to server01: hostnamectl set-hostname server01

Linux LPIC-1 509


SysVinit AND RUNLEVELS
SysVinit is an older init method that has been largely replaced by systemd. However, some
distributions still support SysVinit. Like systemd, SysVinit provides you with various tools to
manage services and the state of the system.

Aside from systemd's improvements, one major difference between it and SysVinit is that
SysVinit has runlevels. Runlevels control the state of the operating system in much the same
way that systemd targets do; they determine what types of daemons should be running in
order to create a specific type of environment. In fact, systemd targets were created to map to
existing runlevels. Like with systemd targets, you can change a system's runlevel and set a
default.

Linux LPIC-1 510


RUNLEVELS VS. TARGETS
The following table compares SysVinit runlevels with their equivalent systemd targets.

SysVinit
systemd Target Description
Runlevel
0 poweroff.target Shuts down system.

1 rescue.target Starts single-user mode.


Starts multi-user mode without remote
2 multi-user.target
networking.
3 multi-user.target Starts multi-user mode with networking.

4 multi-user.target Not used.


Starts multi-user mode with networking and
5 graphical.target
GUI.
6 reboot.target Reboots system.

SINGLE-USER MODE
Single-user mode boots the operating system into an environment where the superuser must

Linux LPIC-1 511


log in. Networking is also disabled in single-user mode, and most partitions are not
mounted. It is typically used to troubleshoot issues with networking or issues that
prevent you from booting into the normal multi-user environment.
On some systems, particularly those using the original GRUB bootloader, it is possible
to reset the root password from single-user mode in case it is lost. However, with
GRUB 2, you must edit the bootloader configuration at the boot menu so that it
initializes a privileged shell that doesn't require a password. From this shell, you can
reset the root user's password.

Linux LPIC-1 511


THE telinit AND runlevel COMMANDS
The telinit command enables you to switch the current runlevel of the system. On systemd
environments, the telinit command will be translated into the appropriate target request. The
runlevel command prints the previous and current runlevel of the system, each separated by a
space.

SYNTAX
The syntax of the telinit command is telinit [options] {runlevel}

Linux LPIC-1 512


THE /etc/inittab FILE
The /etc/inittab file stores details of various processes related to system initialization on a
SysVinit system. It also stores details of the runlevels in use. The init daemon reads from this
file to determine what runlevel to boot into, what daemons to start, and what to do if the
runlevel changes. Each entry in the /etc/inittab file takes the format:

id:rstate:action:process

The id is just a unique identifier for the entry; rstate defines what runlevels the entry applies
to; and action specifies one of several tasks that determine how SysVinit handles the command
defined in the process field.

Linux LPIC-1 513


THE /etc/init.d/ DIRECTORY
The /etc/init.d/ directory stores initialization scripts for services. These scripts control the
initiation of services in a particular runlevel. The scripts are invoked from the /etc/inittab file
when the system initialization begins, using the symbolic links found in the file. SysVinit scripts
are highly flexible and can be configured according to the needs of the user.

Depending on the distribution, SysVinit scripts may instead be stored in /etc/rc.d/ or this
directory may contain symbolic links to the /etc/init.d/ directory.

THE /etc/rc.local FILE


The /etc/rc.local file is executed at the end of the init boot process, typically used to start
custom services. However, this file is rarely used and is not even supported in some
distributions that still use SysVinit.

Linux LPIC-1 514


THE chkconfig COMMAND
The chkconfig command can be used to control services in each runlevel. It can also be used to
start or stop services during system startup.

SYNTAX
The syntax of the chkconfig command is chkconfig [options] [service] [subcommand]

The following are some subcommands and options that can be used with chkconfig to control
services.

Option Used To
{service} on Enable a service to be started on boot.
{service} off Disable a service so that it is no longer started on boot.
{service} reset Reset the status of a service.
--level {runlevel} Specify the runlevel in which to enable or disable a service.

Linux LPIC-1 515


THE service COMMAND
The service command is another way to control SysVinit services through SysVinit scripts. It
supports the following subcommands.

Subcommand Used To

{service} status Print current state of service.

{service} start Activate service immediately.

{service} stop Deactivate service immediately.

{service} restart Restart service immediately.

{service} reload Re-read config files while service runs.

SYNTAX
The syntax of the service command is service [options] [service] [subcommand]

Linux LPIC-1 516


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 517


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 518


Linux LPIC-1 519
During operation of the system, you may encounter various issues that degrade performance or
otherwise make the system unusable. In many cases, these issues impact services, daemons,
and other instances of running software. So, in this topic, you'll switch from managing running
software to troubleshooting problems that are caused by or affect that software.

COMMON PROCESS ISSUES


There are many possible issues that could affect or be caused by a process, a running instance
of software. These issues may include:
• A process hangs, causing instability in that process.
• A process hangs, consuming resources that should be allocated to other processes.
• A process hangs, causing general system sluggishness and instability.
• A process terminates before it can perform its intended tasks.
• A process fails to terminate when it is no longer needed.
• A process should be allocated most CPU resources but other processes are instead.
• A process is causing the system to take a long time to boot.
• A process has a file open, preventing you from modifying that file.
• A process has spawned multiple child processes that are hard to keep track of.
• A process is unidentifiable or potentially malicious.

Linux LPIC-1 520


PROCESS STATES
Processes go through a lifecycle from creation until eventual termination. There are five
different states that a process can be in during this lifecycle, each one defining how the system
or other apps can interact with that process. Knowing a process's state can help you determine
what to do with that process or help you diagnose problems concerning that process.
The five states are:
• Running—The process is currently executing in user space or kernel space. In this state, the
process can perform its assigned tasks.
• Interruptible sleep—The process relinquishes access to the CPU and waits to be reactivated
by the scheduler. A process typically enters this state when it requests currently unavailable
resources. "Interruptible" implies that the process will wake from its sleep if a scheduler
finds a time slot for it.
• Uninterruptible sleep—In this sleep state, the process will only wake when the resource it's
waiting for is made available to it. Otherwise, it will stay in its sleep state. This state is
common for processes that perform storage or network I/O.
• Zombie—This state indicates that a process was terminated, but that it has not yet been
released by its parent process. It is in a "zombie-like" state where it cannot accept a kill
signal because the process isn't available anymore.
• Stopped—This state indicates that the process was stopped by a debugger or through a kill
signal.

Linux LPIC-1 521


PROCESS IDs
Every process is assigned a unique process ID (PID) when it is started so that the system and
users can identify the process. This PID is a non-negative integer that increases for each new
process that is started. The init daemon always has a PID of 1 because it is the first process to
start and is the parent of all other processes on the system. Processes started after this,
whether by the system or by the user, are assigned a higher available number.

Linux LPIC-1 522


When it comes to troubleshooting, you'll need to know a process's PID in order to terminate it,
change its priority, and perform other management tasks on it.

Linux LPIC-1 523


THE pgrep COMMAND
The pgrep command displays the PID of processes that match any given pattern, similar to how
grep is used to match patterns in a text file. Patterns can include: the name or user ID (UID) of
the user who invoked it; the start time; the parent PID; and more.

You can use pgrep to help you identify a process based on multiple factors when you don't
know its exact PID. Identifying the PID is typically the first step in managing the process.

SYNTAX
The syntax of the pgrep command is pgrep [options] {pattern}

Linux LPIC-1 524


Searching for the PID of a specific process.

Linux LPIC-1 525


THE ps COMMAND
The ps command invokes the process table, a record that summarizes the current running
processes on a system. When the command is run without any option, it displays the processes
run by the current shell with details such as the PID, the terminal associated with the process,
the accumulated CPU time, and the command that started the process. However, different
options may be used along with the command to filter the displayed fields or processes.

SYNTAX
The syntax of the ps command is ps [options]

COMMAND OPTION SYNTAX STYLES


The ps command supports three different styles of command option syntax: Unix- style
(preceded by a hyphen), GNU-style (preceded by two hyphens), and BSD-style (no hyphen).
Mixing these styles will not always produce the same results. For example, the ps a command
(BSD-style) will print all processes with a controlling terminal, including session leaders (the first
member of a group of processes). It will also print the status of each process, as well as the full
command (including options) of each process. The ps -a command (Unix-style) also prints all
processes with a controlling terminal, but does not include session leaders, the status of each
process, nor the full command of each process.

Linux LPIC-1 526


Listing all processes on the system. Note that a question mark indicates that a process has no
controlling terminal.
ps COMMAND OPTIONS
The ps command supports several options. Some of the more prominent options are listed
here.
Option Used To
a List all user-triggered processes.
-e List all processes.
-l List processes using a long listing format.
u List processes along with the user name and start time.
r Exclude processes that are not running currently.
x Include processes without a terminal.
Exclude processes that were started by any terminal other than
T
the current one.
-U {user name} Display the processes based on the specified user.
-p {PID} Display only the process associated with the specified PID.
-C {command} Display all processes by command name.
--tty {terminal number} Display all processes running on the specified terminal.

Linux LPIC-1 527


THE top COMMAND
Like ps, the top command lists all processes running on a Linux system. It acts as a process
management tool by enabling you to prioritize, sort, or terminate processes interactively. It
displays a dynamic process status, reflecting real-time changes.

SYNTAX
The syntax of the top command is top [options]

Linux LPIC-1 528


Listing the state of running processes.

Linux LPIC-1 529


Different keystrokes within this tool execute various process management actions. Some of the
frequently used command keys include the following.

Key Used To
Enter Refresh the status of all processes.
Shift+N Sort processes in the decreasing order of their PID.
M Sort processes by memory usage.
P Sort processes by CPU usage.
u Display processes belonging to the user specified at the prompt.
k Terminate the process for which you specify the PID.
r Renice the process for which you specify the PID.
q Exit the process list.

Linux LPIC-1 530


THE systemd-analyze COMMAND
The systemd-analyze command is used to retrieve performance statistics for boot operations.
The command takes one or more subcommands that determine what type of information to
print, and how. For process management and troubleshooting, blame is the most relevant
subcommand. This will print a list of all systemd units that were executed at boot, along with
the time it took each unit to execute. You can use systemd-analyze blame to identify services
and other units that make the system slow to boot.

SYNTAX
The syntax of the systemd-analyze command is systemd-analyze [options] [subcommand]

Linux LPIC-1 531


Analyzing how long it took services to execute on boot.

Linux LPIC-1 532


THE lsof COMMAND
The lsof command prints a list of all files that are currently opened to all active processes. This
can include everything from a text file to a device file—any object that the system can parse as
a file. You may be prevented from modifying a file if it is opened in another process. By using
lsof you can identify the offending process for termination. You can also use lsof to analyze how
a process uses files, which can be helpful in identifying malicious processes or processes that
have unwanted side effects.
The lsof command prints each file opened by a process on its own line. It prints information
such as:
• The name of the command/process.
• The PID.
• The invoking user.
• The file descriptor (FD), including what permissions the file is open with.
• The type of file.
• The name of the file.

SYNTAX
The syntax of the lsof command is lsof [options]

Linux LPIC-1 533


Listing all processes that have the home directory open.

Linux LPIC-1 534


PROCESS PRIORITIES
The OS provides a scheduler that determines what processes to give CPU time to. The
scheduler is usually effective at assigning CPU time, but not every decision it makes is optimal.
In some cases, you may need to manually tell the CPU to prioritize certain processes over
others. It may be more crucial for one process to get done quickly over another, less-crucial
process; you may want to de-prioritize processes started by unprivileged users; a process may
be consuming too many resources and causing system sluggishness; etc.

Processes are prioritized based on a number from -20 to 19, called a nice value or niceness
value. The lower the number, the higher the priority. A process with a nice value of -18 will be
more likely to be given CPU time than a process with a nice value of 15. A processes inherits a
nice value from its parent, and by default, that value is 0.

Linux LPIC-1 535


THE nice COMMAND
The nice command enables you to run a command with a different nice value than the default.
The -n option increments the nice value by the given integer; if you don't provide an integer,
then the command will assume an increment of 10. By running nice without any options, you'll
see the default nice value. You must have the root user authority to run a command at a higher
priority. Once lowered, the priority for any process cannot be increased by normal users, even if
they own the process.

SYNTAX
The syntax of the nice command is nice [-n {nice value increment}] [command]

Linux LPIC-1 536


THE renice COMMAND
Whereas nice is used to start a new process, the renice command enables you to alter the
scheduling priority of an already running process. You use the -n option to specify the new nice
value that you want the process to have.

When you renice a process group with the -g option, it causes all processes in the process
group to have their nice value altered. When you renice a user with the -u option, it alters the
nice value of all processes owned by the user. By default, the processes affected are specified
by their PIDs.

SYNTAX
The syntax of the renice command is renice [-n {nice value}] [options] {identifier}

Linux LPIC-1 537


FOREGROUND AND BACKGROUND PROCESSES
In Bash, most commands will be executed in the foreground. The effect of this is that the
command prompt will be "consumed" until the command finishes processing. For simple
commands, like the date command, this isn't a problem. For longer commands or for scripts,
this can be an issue. For example, if you execute a backup script that you know will take 45
minutes to complete, you will not be able to enter a command in that shell until the script has
finished.

It is possible to run commands in the background, where they still execute but do not consume
the shell. You can use the fg (foreground) and the bg (background) commands to move the
process into view.

Linux LPIC-1 538


MANAGEMENT OF FOREGROUND AND BACKGROUND PROCESSES
The following is an example of how to manage a long-running script:
1. First, you would execute the script in the background by entering backup- script.sh &
2. Next, you would use the jobs command to discover the job ID number of the script. This
command would also show you the current status of the job (running, for example).
3. You could move the script's execution into the foreground by entering the fg %<job ID>
command. This might be useful if the script includes interactive prompts.
4. You then press Ctrl+Z to temporarily pause the job, freeing the command prompt.
5. You move the script back into the background by entering bg %<job ID>

COMMAND SUMMARY
The following table summarizes the purpose of each command used in the previous example.

Option Used To
fg %{job ID} Bring a job to the foreground.
Ctrl+Z Halt a job temporarily so you can use the bg command.
bg %{job ID} Push a job to the background.
Start a command running in the background when added to the end
&
of a command.

Linux LPIC-1 539


THE nohup COMMAND
The nohup ("no hangup") command prevents a process from ending when the user logs off. For
example, if an administrator launches a backup script, and then logs off the system, the script
would stop running. By placing the nohup command in front of the normal command, the
script would continue even after the administrator logged off.

SYNTAX
The syntax of the nohup command is nohup {command/script}

Linux LPIC-1 540


KILL COMMANDS
Different commands are used to send signals to processes to terminate or "kill" them. This is
necessary when a process becomes unresponsive (hangs), causes system instability, or fails to
relinquish control over a file you're trying to modify.

USING THE PID NUMBER TO TERMINATE PROCESSES


You can use the kill command with the process table to end processes. By entering kill followed
by the PID, you can terminate specific processes. However, the process table may display
processes that do not belong to you. As a user, you can use the kill command only with
processes that you own. As root, you can kill any processes.

Linux LPIC-1 541


KILL SIGNALS
There are many ways to kill a process, each one mapped to a signal. This signal determines how
to kill the process. Some signals are more appropriate than others in certain situations. For
example, you may wish to terminate a process gracefully, giving it time to clean up any last
activities. However, some processes will ignore this signal or simply fail to terminate in a
reasonable amount of time. For that, you may have to issue a more aggressive signal.

There are many different kill signals. Each signal has a name and one or more corresponding
number values; you can use either with the kill command. Some of the most common signals
are described in the above table.

EXAMPLES
The following are some examples of implementing kill signals. To terminate a process with ID
921 gracefully:
kill 15 921

Failing that, to kill the process immediately:


kill 9 921

Alternatively, to pause rather than remove the process entirely:


kill 17 921

Linux LPIC-1 542


GUIDELINES FOR TROUBLESHOOTING PROCESS ISSUES
Use the following guidelines when troubleshooting process issues.

TROUBLESHOOT PROCESS ISSUES


When troubleshooting process issues:
• Gather information about a process, including its process ID (PID) and state.
• Use ps to print information on all running processes, including CPU usage. For example, a
process consuming over 50% of the CPU may cause performance issues, and is worth
investigating further.
• Use top to retrieve a dynamic and interactive list of all running processes.
• Use systemd-analyze blame to determine what startup processes are slowing down boot
operations.
• Use lsof to identify which processes have open files.
• Use nice and renice to prioritize certain processes over others.
• Use fg and bg to manage foreground and background processes.
• Use nohup to keep a command running even after logging off.
• Use kill and its associated commands to terminate problem processes.

Linux LPIC-1 543


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 544


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 545


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 546


Linux LPIC-1 547
The system needs to access certain hardware resources—particularly, the processor and
memory—in order to provide functionality. Problems that affect these resources will cause
major disruption to the system. So, in this topic, you'll use various Linux commands to identify
and solve issues related to the CPU and RAM.

COMMON CPU ISSUES


There are many possible issues that could affect or be caused by the CPU. These issues may
include:
• The CPU is under-performing for the desired level of speed and responsiveness.
• The CPU is being overloaded by too many requests and can't respond in time.
• One or more CPU cores are non-functional and/or exhibiting reduced performance.
• Processes are unable to access enough CPU time to run effectively.
• Processes are consuming too much CPU time, leaving other processes without resources.
• The CPU is spending too much time idle instead of processing.
• The CPU doesn't support features like virtualization or hyperthreading.

Linux LPIC-1 548


THE /proc/cpuinfo FILE
The /proc/cpuinfo file contains information about the system's processor. You can use this
information to identify characteristics about your CPU that might indicate issues related to
performance or lack of support for features.

Each logical processor core has its own entry. A CPU might support multithreading, which
performs multiple operations simultaneously on a single physical core. Logical cores represent
each possible thread. So, a CPU marketed as being a quad-core processor might have eight
logical cores.
Some useful fields in the /proc/cpuinfo file include:
processor —The number of the logical core, starting with 0.
vendor_id —The CPU manufacturer.
model name —The specific model of CPU.
cpu MHz —The logical core's clock speed, measured out to the thousandths decimal place.
cache size —The CPU's cache size.
flags —Characteristics about the CPU as well as supported features.

CPU-BASED KERNEL PARAMETERS


As you've seen, the sysctl command enables you to view kernel parameters at runtime.

Linux LPIC-1 549


Viewing CPU information.

Linux LPIC-1 550


THE uptime COMMAND
The uptime command displays the time from when a system started running. The output of the
uptime command gives information about the current time, how long the system is running,
and how many users are currently logged in.

Most relevant to CPU troubleshooting, however, is the load average field. A CPU's load is
expressed as the number of processes that are either using or waiting to use the CPU. It can
also include the number of processes in the queue for storage I/O. Using uptime you can find
the average load over three different periods of time, from left to right in the output: the last 1
minute, the last 5 minutes, and the last 15 minutes.

You can use these values to determine when your CPU becomes overloaded, which may lead to
performance issues. For example, if you have 4 logical cores, and the load average in the last 15
minutes is 4.0, then your CPU was being used fully. If your load average were 8.0, then your
CPU would be 100% overloaded.

Linux LPIC-1 551


Viewing system uptime and average CPU load.

Linux LPIC-1 552


THE sar COMMAND
The sar command displays system usage reports based on data collected from system activity.
These reports consist of various sections, each of which consists of the type of data and the
time at which the data was collected. The default mode of the sar command displays CPU
usage in various time increments for each category of resource that accessed the CPU, such as
users, the system, I/O scheduling, etc. It also displays the percentage of the CPU that was idle
at a given time. At the bottom of the report is an average of each data point across the listed
time periods. By default, sar reports the data collected every 10 minutes, though you can use
various options to filter and shape these reports.

Like the uptime command, you can use sar to identify excessive load on the CPU. You're given
more details about when excessive usage occurs, as well as what might be causing that
excessive usage.

SYNTAX
The syntax of the sar command is sar [options]

Linux LPIC-1 553


Viewing CPU time usage

CPU-BASED KERNEL PARAMETERS


You can also use the sysctl command to troubleshoot CPU issues by retrieving CPU-based
kernel parameters at runtime. One useful set of parameters concerns scheduling domains, a
method by which the kernel groups logical cores that share scheduling policies and other
properties. These parameters typically take the format:
kernel.sched_domain.cpu#.domain#.param

Linux LPIC-1 554


COMMON MEMORY ISSUES
There are many possible issues that could affect or be caused by memory. These issues may
include:
• Not enough total memory to service all processes at once.
• Not enough free memory to service new processes.
• Processes are unable to access memory despite being available.
• Processes are accessing too much memory, leaving other processes without memory.
• The system cannot quickly access files from a cache or buffer.
• The system is killing critical processes when it is low on memory.
• Swap partitions are taking up too much or not enough storage space.

Linux LPIC-1 555


THE /proc/meminfo FILE
The /proc/meminfo file contains a great deal of information about the system's memory usage.
You can use this information to ensure that the system's RAM modules are performing to
specification; that the OS is consuming memory at the expected rate; and that the system has
enough available memory to perform intensive tasks.

Some useful fields in the /proc/meminfo file include:


• MemTotal —The total amount of physical memory on the system.
• MemFree —The total amount of physical memory that is currently unused.
• Cached —The total amount of physical memory that is being used as cache memory.
• SwapTotal —The total amount of swap space on the system.
• SwapFree —The total amount of swap space that is currently unused.
• Dirty —The total amount of memory that is waiting to be written to storage.
• Writeback —The total amount of memory currently being written to storage

Linux LPIC-1 556


Viewing memory information.

Linux LPIC-1 557


THE free COMMAND
The free command parses the /proc/meminfo file for easier analysis of memory usage
statistics. Its default behavior is to display the following information about system memory and
swap space:
• The total memory.
• The total used.
• The total free.
• The total shared.
• The total buffered and cached.
• The total available for starting new apps (estimated).

SYNTAX
The syntax of the free command is free [options]

BUFFER/CACHE OUTPUT
Memory can be cached, meaning that it is stored temporarily so that the data it contains can be
accessed much quicker in the future. The Buffers field in /proc/meminfo indicates memory
that is assigned to a specific block device. This memory is used to cache file system metadata,
like directory contents, permissions, etc. The Cached memory is similar, but instead of storing
file metadata, it stores the actual contents of files. The free command combines these two
values together upon output.

Linux LPIC-1 558


Parsing memory and swap space usage information.

free OPTIONS
There are several command options available for the free command.

Option Used To
Display memory in bytes, kilobytes, megabytes, gigabytes, and
-b, -k, -m, -g, -tera
terabytes, respectively.
-s {seconds} Update memory statistics at a delay of the specified seconds.
-o Disable the display of the buffered/cached information.
-t Display a total line that combines physical RAM with swap space.
-h Make the output more human-readable.

Linux LPIC-1 559


THE vmstat COMMAND
The vmstat command displays various statistics about virtual memory, as well as process, CPU,
and I/O statistics. By default, the report will provide averages of each statistic since the last
system boot, though you can also specify a delay value to sample from a period of time.

Some memory-based statistics include:


• The total virtual memory available.
• The total virtual memory that is free for use.
• The total memory used in buffers and cache.
• The total memory used in swap space.

Some CPU-based statistics include:


• Time spent running user space.
• Time spent running in kernel space.
• Time spent idle.
• Time spent waiting for I/O.

SYNTAX
The syntax of the vmstat command is vmstat [options] [delay [count]]

OUTPUT DELAY
It's recommended to supply vmstat with a delay for a more accurate report. For example,
vmstat 5 5 will run the command on a five-second delay for five intervals.

Linux LPIC-1 560


Viewing various memory, CPU, and other system statistics.

Linux LPIC-1 561


OOM KILLER
The out-of-memory (OOM) killer is a feature of the Linux kernel that determines what
process(es) to kill when the system is extremely low on memory. The OOM killer will continue
to kill processes until enough memory is free for the kernel and the system to run smoothly.
Rather than killing processes at random, the OOM killer leverages an algorithm that assigns
each process an OOM score. The higher the score, the higher chance the process has of being
killed during an OOM event. The assignment algorithm considers what processes will free up
the greatest memory when killed, as well as what processes are least important for system
stability. It then assigns scores based on what it determines to be the most optimal targets for
termination.

Although this mechanism is mostly automated by the kernel, you do have the ability to control
some of its behavior. You can mount the oom control group at the desired mount point. If, for
example, you want to designate a group of processes as the first to be killed, you can create a
directory at this mount point and create a tasks file in this directory that lists the PIDs of the
relevant processes. Then, create an oom.priority file with a high integer value like 256 to give
the processes a higher priority for the OOM killer. Or, to prevent the processes from being
killed entirely, give 0 as the priority value.

Linux LPIC-1 562


SWAP SPACE CONFIGURATION
The configuration of swap space can alleviate memory-related issues, especially when the
system and applications request more memory than the system has. Systems with a low
amount of RAM are particularly vulnerable to these issues. Swap space is not a replacement for
adding more memory, but it can help minimize system and application sluggishness,
unresponsiveness, and crashes.
SWAP FILES
Swap files are created for storing data that is to be transferred from a system's memory to a
storage device. They are dynamic and change in size when data is moved in and out of memory.
Swap files are used as a medium to transfer data from RAM onto the storage device.
SWAP PARTITIONS
A swap partition is an area of virtual memory on a storage device to complement the physical
RAM in the computer. Swap partitions are used by Linux because they perform better than
swap file systems.
SWAP SPACE TYPES
Swap space can be one of three types
Swap Type Description
Device swap space is configured when you partition the storage device. It is used by the
Device swap
operating system to run large applications.
File system swap space is configured primarily when you install Linux. It is used by the
File system swap
operating system as an emergency resource when the available swap space runs out.
-Pseudo-swap Pseudo-swap space enables large applications to run on computers with limited RAM.

Linux LPIC-1 563


THE mkswap COMMAND
The mkswap command is used to create swap space on a storage partition. It is typically used
when you wish to move swap space to a different partition than the one that was created
during system installation. For example, you might want to save space on a low-capacity boot
drive.
It provides options to perform various tasks.

Option Used To
Verify that the device is free from bad sectors before mounting
-c
the swap space.
Set the page size to be used by the mkswap command. A page is a
-p chunk of memory that is copied to the storage device during the
swap process.
Activate the swap space using labels applied to partitions or file
-L {label}
systems.

Linux LPIC-1 564


SWAP PARTITION MANAGEMENT COMMANDS
The swapon command is used to activate a swap partition in a specified device. The swapoff
command is used to deactivate the swap space on a device.
Some of the frequently used swapon and swapoff command options are given in the following
table.

Option Used To

swapon -e Skip non-existent devices.

swapon –a Activate all of swap space.

swapoff –a Deactivate all of swap space.

Linux LPIC-1 565


GUIDELINES FOR TROUBLESHOOTING CPU AND MEMORY ISSUES
Use the following guidelines when troubleshooting CPU and memory issues.

TROUBLESHOOT CPU AND MEMORY ISSUES


When troubleshooting CPU and memory issues:
• Identify key information about the CPU and its logical cores using the /proc/cpuinfo file.
• Use the uptime command to identify CPU load averages.
• Use sar to see what component is causing heavy load on the CPU and when.
• Identify key information about memory usage using the /proc/meminfo file.
• Use free to more easily analyze memory usage information.
• Use vmstat to retrieve more information on both CPU and memory usage.
• Consider tweaking the OOM killer to spare or sacrifice specific processes when low on
memory.
• Consider creating more swap space if adding physical memory is not feasible.

Linux LPIC-1 566


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 567


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 568


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 569


The next component category you can configure is devices. At some point, physical hardware is
required to interface with the Linux® operating system, even if you're not co-located with the
system itself. You must therefore ensure that any hardware devices connected to the system
are recognizable to the system and properly configured. So, in this topic, you'll manage several
different kinds of devices.

Linux LPIC-1 570


In this topic, you will:

• Identify the different types of devices that support the Linux OS.
• Configure devices.
• Monitor devices.
• Troubleshoot various issues having to do with hardware devices.

Linux LPIC-1 571


Linux LPIC-1 572
Before you begin using Linux® commands to manage devices, you need to become familiar with
the types of devices that Linux supports.

THE IMPORTANCE OF DEVICE DRIVERS


As you know, device drivers act as an interface between the operating system and hardware
devices. Drivers are crucial for devices to function properly, or to even function at all within the
Linux environment. While great strides have been made by both the Linux kernel developers
and device manufacturers to write Linux-compatible drivers, there may still be compatibility
issues with certain hardware. Ultimately, no matter what the device is that you're trying to use,
you need to make sure it has proper driver support under Linux, and that your Linux system
actually has those drivers. Otherwise, you may be unable to use that device, or use it well.

Linux LPIC-1 573


THIN CLIENTS
A client device, typically referred to as a thin client, is any lightweight computing device that
connects to a more powerful server for doing work. The server does most of the heavy lifting,
including processing and storing data, while the thin client acts as little more than a user
interface. This type of computing architecture centralizes operations, making it easier for
administrators to manage groups of backend servers instead of workstations that are dispersed
throughout the organization.

As you've seen, Linux has robust remote connection support, whether through a GUI with
remote desktop apps, or through a terminal with SSH. A thin client will typically have
fundamental I/O devices like a keyboard, mouse, and monitor connected to it. It may or may
not be running Linux, and if it is, it will typically be a lightweight distribution with very few
features available or permissible to the user. The server the client connects to will usually
construct a virtual environment so that the user can work in a sandbox, segmented from other
portions of the server or network. The server, like the client, may be running Linux or another
operating system.

Linux LPIC-1 574


Thin clients connecting to a centralized, powerful server.

Linux LPIC-1 575


USB DEVICES
Universal Serial Bus (USB) is a peripheral interface technology that has become the de facto
standard for connecting input devices, external storage devices, mobile devices, and more, to
computers. USB also incorporates plug-and-play technologies that enable devices to self-
configure as soon as a connection is made.
A wide range of USB device types are supported in Linux, including, but not limited to:
• Thumb drives
• External HDDs and SSDs
• Digital cameras
• Smartphones and tablets
• Printers and scanners
• Keyboards and mice
• Microphones and webcams
• Game controllers

USB STORAGE AND DEVICE ASSIGNMENT


Linux registers USB storage devices attached to the system in the format /dev/sd# in the same
way as the SCSI/SATA naming convention.

Linux LPIC-1 576


WIRELESS DEVICES
Wireless devices transmit and receive signals over the air rather than through physical cables
connected to ports. There are many different wireless networking protocols, each of which may
have a specific or optimal application. Examples of common wireless networking protocols
supported by Linux include:
• Wi-Fi: A technology used primarily in establishing a wireless local area connection (WLAN) in
home and office environments. Common devices include wireless routers and access points
for networking infrastructure; and mobile devices, desktop computers, Internet of Things
(IoT) devices, and many more that act as Wi-Fi clients. Wi-Fi routers and access points may
often run some flavor of Linux, whereas Linux- based clients like AndroidTM smartphones
and desktop computers can connect to those infrastructure devices.
• Bluetooth: A technology used primarily for establishing a personal area network (PAN) in
which devices communicate wirelessly within a few feet of each other. A common
application is when wireless headsets or headphones are paired with a smartphone or other
computing device, enabling the user to listen to audio without the need for cabling. As
you've seen, Linux has Bluetooth® driver support and can act as either end of the pairing.
• Near Field Communication (NFC): A communications protocol used by mobile devices and
peripherals that are either touching or only inches apart. NFC is often used to quickly share
data from one device to another. As with Bluetooth, support for NFC on Android mobile
devices is robust. There is also Linux support for some NFC adapters and discrete devices
that connect to traditional computers.

Linux LPIC-1 577


VIDEO AND AUDIO DEVICES
Video and audio devices are I/O peripherals that are usually attached to client systems like
desktops and laptops, or thin clients. Common video input peripherals include webcams,
surveillance cameras, and digital cameras. Common video output peripherals include monitors,
televisions, and projectors. Microphones are the most common audio input peripheral, but
certain video input peripherals also capture audio. Likewise, monitors and televisions can
usually output audio, but audio-only output devices like speakers and headphones are also
popular.

When you connect a video/audio peripheral to a system running any OS, including Linux, you
need to be mindful of the connection types it uses and what types are available on the system.
Microphones and webcams commonly use USB, whereas USB is much less effective for
streaming video/audio output in real-time. Monitors, for example, are more likely to use
interfaces like HDMI and DisplayPort that can carry both video and audio signals with a high
degree of real-time performance. Some monitors may use older interfaces like DVI and VGA
that only carry video.

Linux LPIC-1 578


PRINTERS
Like most other operating systems, Linux provides support for printers. Support for a specific
type of printer is dependent on whether or not there are available drivers for the Linux kernel
to use, and how robust those drivers are. As driver support in the kernel has improved over the
years, so too has support for many printers offered by most major vendors.

You can connect to a printer using one or more interfaces and methods. Most modern printers
offer local connection support through a USB interface. However, in office environments
especially, clients often connect to printers over a network. In this case, the printer may include
a Wi-Fi adapter, an Ethernet adapter, or both, so that the printer is identifiable on the LAN.
Multiple clients can therefore connect to and use the same printer at once. A Linux computer
can even function as a print management server that interfaces with one or more physical
printers.

Linux LPIC-1 579


NETWORK ADAPTERS
A network adapter, also known as a network interface card (NIC), is a device that provides an
interface with which hosts exchange data over a network. A network adapter is mandatory for
any computing device that needs access to a network, whether a small LAN or a wider network
like the Internet.

In many cases, network adapters are built into a computer's motherboard. However, some
adapters can be added to the system on an expansion bus, or as an external peripheral that
connects through an interface like USB. A system can have more than one adapter; this is
especially common in servers and security systems like firewalls. In addition, each type of
network connection protocol requires its own type of adapter. A Wi-Fi adapter sends and
receives wireless signals in a WLAN, whereas an Ethernet adapter will include an Ethernet port
that you can plug a cable into to connect to a LAN.

Linux LPIC-1 580


GPIO
General-purpose input/output (GPIO) refers to pins on a circuit board that have no designated
purpose, but are controllable by the user at runtime. These pins send and receive digital signals
and can be in an on or off state. For example, a pin designated as output can turn an LED light
on or off; and a pin designated as input can itself be turned on or off from an external source
like a light switch. In most cases, GPIO functionality is controlled programmatically through
software. A developer might design their app to send or receive signals to and from the pins so
that the app can interface with the outside world.

GPIO pins are commonly found on single-board microcontrollers like Arduino and Raspberry Pi
devices. While these devices are often used by hobbyists and as a way to teach fundamental
computing concepts, they also have applications in the IoT space. Specialized Linux
distributions like Raspbian can be used to control GPIO functionality on single-board
microcontrollers through various programming libraries.

Linux LPIC-1 581


GPIO pins on a Raspberry Pi device.

Linux LPIC-1 582


SATA
Serial AT Attachment (SATA) is a computer bus interface standard for attaching storage devices
to traditional computers. In modern PCs, SATA has largely replaced earlier standards like Parallel
ATA (PATA) and Integrated Drive Electronics (IDE) as one of the dominant standards in storage
connection technology.

In the past, SATA was seen as a good solution for situations where capacity and cost were
paramount. SATA supports multiple-terabyte drives and is relatively cheap to manufacture.
However, its slower data transfer rate compared to alternative standards (6 gigabits per second)
made it less suitable for enterprise environments, and it was most commonly used for backup
purposes and in consumer storage. The most current revision of SATA (revision 3.2) combines
SATA with another bus technology called PCI Express, which allows it to supports a raw data
rate of up to 16 Gb/s—finally rivaling its competitors.

Linux LPIC-1 583


SCSI
Small Computer System Interface (SCSI) is a computer bus interface for connecting peripheral
devices to traditional computers. Whereas SATA is primarily used for attaching storage devices,
SCSI can be used to attach other types of devices as well, such as DVD-ROM drives, printers,
scanners, etc. However, its application in storage is much more common.

Traditionally, SCSI uses a parallel interface, which tends to cost more to manufacturer than a
serial interface. However, in the past, SCSI provided high transfer rates and therefore became
popular in enterprise storage arrays where speed was important. The Serial Attached SCSI
(SAS) standard was developed to apply a serial interface to SCSI technology. SAS offers greater
speeds than traditional SCSI—up to 24 Gb/s in the recent SAS-4—and supports higher-capacity
drives. The serial interface also supports a more reliable data transfer rate. SAS has become the
go-to technology for many enterprise storage environments.

Linux LPIC-1 584


HBA
A host bus adapter (HBA) is a hardware component that connects a host system to a storage
device, like in a storage area network (SAN), in order to facilitate the input and output of data.
They are to storage devices what network adapters are to networks. HBAs are commonly used
with interface technologies like SATA and SCSI. The HBA might be built into the motherboard, or
it might be a separate expansion card that attaches to the motherboard. In either case, you
connect a storage device to an HBA with the requisite interface in order for the system to work
with that storage device.

Linux LPIC-1 585


PCI
Peripheral Component Interconnect (PCI) is a connection interface standard that is primarily
used as an expansion bus for attaching peripheral devices. The initial PCI specification has been
largely superseded by the more recent PCI Express (PCIe). PCIe supports greater transfer
speeds, more reliable error detection, and is physically smaller than traditional PCI. In modern
computers, PCIe is the dominant expansion bus technology.

When it comes to non-storage devices, there are many applications of PCIe. It's common for
video cards to connect using this interface, as well as expansion cards that add more ports like
USB and SATA for the system to use. In more recent years, PCIe has been used to connect SSDs
that leverage the Non-Volatile Memory Express (NVMe) interface, which is specifically designed
for integration with PCIe. NVMe SSDs are even faster than SSDs connected over SATA and SAS;
they will likely become a prominent force in enterprise storage.

Linux LPIC-1 586


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 587


Linux LPIC-1 588
Now you're ready to use Linux tools to configure devices. In this topic, you'll use some common
services that enable you to customize how the system interacts with certain hardware.

DEVICE FILE LOCATIONS


Device files represent information about hardware devices, and in some cases, define settings
about those devices that you can customize. These files are located in several different
directories and subdirectories, many of which you've seen before.

Location Description
• Files representing info reported by kernel.
/proc/
• /proc/devices lists all character/block devices.
• Creates hierarchical view of device info.
/sys/
• /sys/devices/ includes files that expose device details.
• Device driver files.
/dev/ • Example: Mount block device through /dev/sda1
• /dev/mapper includes LVs, encrypted devices, etc.
• Config files for many components.
/etc/ • /etc/X11/ has files for configuring I/O devices impacting X.Org
Server.

Linux LPIC-1 589


HOTPLUGGABLE DEVICES
A hotpluggable device can be physically added or removed from the system without requiring
a reboot in order to use that device. Hotpluggable devices are detected by the system as they
are plugged in, whereas coldpluggable devices, such as RAM modules, CPUs, and some internal
storage devices, are not sensed when connected to a running system; they need a complete
reboot of the system to function. In fact, for internal devices like RAM modules, it is highly
recommended that the system is powered off before attempting to plug the device in.

Modern Linux distributions support hotplugging for many standard bus types, particular for
USB, FireWire, SATA, and other related technologies. Even expansion bus technology like PCIe
can support hotplugging.

Linux LPIC-1 590


udev
The device manager udev manages the automatic detection and configuration of hardware
devices. A function of systemd, udev is an integral part of the kernel that is initialized during
boot time. The udev utility handles module loading for both coldpluggable and hotpluggable
devices. It loads the modules for coldpluggable devices when the system is booted. The
modules for hotpluggable devices are loaded by udev dynamically during system run time.

Linux LPIC-1 591


udev RULES
The /etc/udev/rules.d/ directory is used to configure rules for how udev functions. You can
create files in this directory that tell udev to configure a device in a certain way or run a certain
command when a device is plugged in. For example, you might want to create a symbolic link
to a specific device every time it is plugged in; that way, you can always refer to this device in
the same way, rather than relying on the unpredictable and non-descriptive /dev/ naming
scheme like /dev/sda1, /dev/ sdb2, etc. In your rules file, you'd need to refer to the device by
attributes that are unique to that device, like its vendor and product IDs. For example, the
following line in a rules file will create a symbolic link to a specific USB thumb drive when it is
plugged in:
KERNEL=="sd*", ATTRS{idVendor}=="334455", ATTRS{idProduct}=="667788",
SYMLINK+="myusb"

Similar to writing rules for GRUB, you name this rule file in the format ##- name.rules where ##
determines its order in being executed by udev.

ADDITIONAL udev RULES DIRECTORIES


There are actually several directories that are used to configure udev rules.
The /etc/udev/rules.d/ directory mentioned previously is primarily used for
local administration of udev. An administrator applies their own customizations to this
directory so that udev behaves in accordance with the administrator's preferences and/or the
organization's business needs. As a result, the files in this directory are loaded with the highest

Linux LPIC-1 592


priority.
The /usr/lib/udev/rules.d/ directory also contains udev rules. However, these rules
are generated by the system, and you should refrain from editing them. Rules in this
directory are low priority, so a custom rule named 60- keyboard.rules in
/etc/udev/rules.d/ will supersede the default 60- keyboard.rules file in the
/usr/lib/udev/rules.d/ path.

Rules files can also be placed in the /run/udev/rules.d/ directory. These also take
precedence over the system rules path. Rules in this path are volatile, meaning that
they will apply at runtime but will be lost in the event of a system reboot. Volatile
rules can be useful when you need to temporarily override a system rule without
actually making the change persist.

Linux LPIC-1 592


THE udevadm COMMAND
The udevadm command is used to manage udev. It takes various subcommands, each of which
performs a certain task to modify the behavior of the systemd-udevd daemon and related
components. Some of these subcommands are described in the following table.

Subcommand Used To
Retrieve device information stored in the udev database, as well as
detailed device attributes from the /sys/ file system. For example, you
info
can view a device's vendor ID, product ID, serial number, and much
more.
Modify the running state of udev. For example, providing the --reload-
control rules option will ensure that udev is reading from any new rules files
you've added.
Execute rules that apply to any device that is currently plugged in. You
can also specify an action using the -c option, such as add, remove, or
trigger
change. As the names imply, these will trigger events where a device is
added, removed, or changed in the running kernel.
monitor Watch for events sent by the kernel or by a udev rule.
test Simulate a udev event running for a device, with results on output.

Linux LPIC-1 593


Displaying device attributes and other information.

SYNTAX
The syntax of the udevadm command is udevadm [options] [subcommand] [arguments]

Linux LPIC-1 594


PRINTING SOFTWARE
Printers are typically bundled with software utilities that enable you to configure settings for
the printer. These utilities may target a specific operating system, so you need to confirm
whether or not they were designed to run on Linux. Even if you cannot run the manufacturer's
software utilities, you may still be able to work with the printer through a Linux utility. Major
vendors will usually provide the most up-to-date drivers for download off their websites.

Linux LPIC-1 595


CUPS
CUPS is a print management system for Linux that enables a computer to function as a print
server. A system running CUPS is a host that can initiate print jobs from client systems. These
jobs are then processed and sent to the appropriate printer. The main advantage of CUPS is
that it can process different data formats on the same print server.

CUPS is designed for scheduling print jobs, processing administrative commands, and providing
printer status information to local and remote programs. CUPS provides a web-based interface
for configuring the service. Changes made through this interface modify the
/etc/cups/cupsd.conf and /etc/cups/cups-files.conf files.

Linux LPIC-1 596


The CUPS web interface.
CUPS used to stand for Common Unix Printing System and was developed by Apple.

Linux LPIC-1 597


THE lpr COMMAND
The lpr command submits files for printing. Files supplied at the command-line are sent to the
specified printer or to the print queue if the printer is busy. Without specifying the printer to
use, the command will send the print job to the default printer, which you can configure with
CUPS. The lpr command reads the print file from standard input if no files are supplied at the
command-line.

SYNTAX
The syntax of the lpr command is lpr [options] [file names]

Linux LPIC-1 598


lpr COMMAND OPTIONS
The lpr command options are described in the following table.

Option Used To
-E Force encryption when connecting to the server.

-P {destination} Send the print job to the destination printer specified.

-# {copies} Set the number of copies to print from 1 to 100.


-T {name} Set the job name.
Specify that the print file is already formatted and should be sent to the
-l
destination without being filtered.
Set a job option, like printing in landscape mode, scaling the printed
-o {option} output, printing double-sided, etc. Job options vary depending on the
printer.
Print the specified files with a shaded header that includes the date,
-p
time, job name, and page number.
-r Specify that the printed files should be deleted after printing.

Linux LPIC-1 599


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 600


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 601


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 602


Linux LPIC-1 603
THE lsdev COMMAND
The lsdev command displays various information about a system's hardware as reported by the
kernel. It compiles this information from three files in the /proc/ directory:
• /proc/interrupts —This file lists each logical CPU core and its associated interrupt requests
(IRQ). An IRQ is a signal sent by a device to the processor so that the processor can stop
what it is doing and handle some task that the hardware needs to perform, like pressing a
keystroke or moving the mouse. There are multiple IRQ addresses that signals can be sent
along, and for each address, this file lists how many signals were sent to each CPU core
along that address. It also names the hardware device that is mapped to each IRQ address.
• /proc/ioports —This file lists I/O ports and the hardware devices that are mapped to them.
• /proc/dma —This file lists all Industry Standard Architecture (ISA) director memory access
(DMA) channels on the system. ISA DMA is a hardware controller that typically supports
legacy technology like floppy disks.

Linux LPIC-1 604


THE lsusb COMMAND
The lsusb command is used to display information about devices that are connected to the
system's USB buses. This command scans the /dev/bus/usb/ directory for information. By
default, the command will print the number of the bus and the connected device, the ID of the
device, and the name of the vendor and product matching that device.

You can use the -v flag to see detailed information about each device, similar to using the
udevadm info command. You can also filter results by bus (-s) and by vendor/product (-d).

SYNTAX
The syntax of the lsusb command is lsusb [options]

Linux LPIC-1 605


Listing USB device information.

Linux LPIC-1 606


THE lspci COMMAND
The lspci command is used to display information about devices that are connected to the
system's PCI buses. By default, the output will list the logical slot address (typically in the
format Bus:Device.Function), the device's class (such as network controller, storage controller,
input device, or bridge device), the vendor name, and the device name. Like lsusb, lspci offers a
verbose mode for more detailed information about each device. For example, you can use
verbose mode to identify the physical slot in which an adapter is installed.

SYNTAX
The syntax of the lspci command is lspci [options]

Linux LPIC-1 607


Listing PCI device information.

Linux LPIC-1 608


THE lpq COMMAND
The lpq command shows the status of the printer queue. By default, it will report each print
job's rank in the queue, who owns the job, the job number, the files in the job, and the size of
the job. You can also have the report update every number of seconds that you specify with the
+interval option, until the queue is empty. If you don't specify the printer to monitor, the lpq
command will monitor the default printer.

SYNTAX
The syntax of the lpq command is lpq [options]

Linux LPIC-1 609


Listing the printer queue.

Linux LPIC-1 610


ADDITIONAL DEVICE MONITORING TOOLS
Some tools you've already used thus far can also be useful in monitoring hardware devices. For
example, you can use lsblk to identify block storage devices connected to the system. The
output of this command can help you ensure that your storage devices are recognized and that
they are correctly partitioned and mounted.

Another example is the dmesg command. Recall that this prints all messages sent to the
kernel's message buffer after system boot, including messages sent by device drivers. If
hardware devices encounter errors in operation or are unable to load the expected modules
into the kernel, the output of dmesg might indicate so. Use this output to monitor for issues
related to device drivers and the underlying hardware they control.

Linux LPIC-1 611


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 612


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 613


Linux LPIC-1 614
As you might expect, hardware devices are just as susceptible to problems as any other Linux
component. In this topic, you'll look at some of the common symptoms that indicate device
issues, as well as some suggested solutions for dealing with those issues.

COMMON HARDWARE ISSUES


Problems can affect a wide array of different hardware devices. Missing or poorly configured
drivers are a common source of these problems, as is user space software that is incompatible
with certain hardware. However, there are many other potential sources. Likewise, there may
be many potential solutions that differ based on the type of component you're
troubleshooting. In general, hardware issues can be categorized as follows:
• Keyboard mapping issues.
• Communications port issues.
• Printer issues.
• Memory issues.
• Video issues.
• Storage adapter issues

Linux LPIC-1 615


KEYBOARD MAPPING ISSUES
Certain keyboard keys, when pressed, may produce an unexpected character on the screen, or
no character at all. This is the most common and overt symptom of a keyboard mapping issue.
The most likely cause of these issues is that the system has configured the wrong keyboard
layout and/or the wrong language.

To address the problem, make sure you can correctly identify the layout of the physical
keyboard—not just its overall design type (e.g., QWERTY vs. Dvorak), but its specific regional
layout. Even standard QWERTY keyboards designed with the same language in mind don't
always have the same layout; for example, American English keyboards contain keys in different
spots than British English keyboards. Once you've identified the physical layout of your
keyboard, use localectl status to verify the layout that the system is using. If it's not correct, list
the available keymaps, identify the correct one, then set it on the system. You may also need to
adjust the system language to ensure one-to-one accuracy.

ADDRESSING ISSUES WITH A REMOTE TERMINAL


If you are accessing a Linux system remotely, your remote terminal client may have some
options for addressing keyboard mapping issues. SSH clients like PuTTY enable you to change
the effects that certain keystrokes have on the environment. For example, you can configure
the Backspace character to move one character to the left without deleting the character. This
can be helpful in certain applications that don't handle the default behavior well.

Linux LPIC-1 616


COMMUNICATIONS PORT ISSUES
Communications ports, like USB, may fail to recognize an attached device, or the connection to
that device may be unreliable. Your first step should be to ensure that the device is correctly
slotted into the port, and that any physical cables are not loose or damaged. Also make sure
that power is being supplied to the bus adapter. If this doesn't fix the issue, then ensure that
any necessary drivers are installed and loaded into the kernel, depending on the type of
interface you're using. Also ensure your device supports the correct version of the bus
interface. For example, each version of USB has a maximum data throughput value, and older
versions may not meet your performance expectations.

Certain devices, when connected to a serial port, will request a console interface with the Linux
operating system. Linux will typically assign the port an interface at /dev/ttyS# where # is the
number of the console (starting with 0). In some cases, you may need to ensure that the
connected device is configured to automatically use one of these consoles. Also, by default,
only the root user is granted access to these serial consoles. You may need to change the
permissions on the relevant serial console using chmod to ensure that other users can work
with it.

Linux LPIC-1 617


PRINTER ISSUES
Printers are a very common source of issues. In many cases, the printer itself will be at fault:
• It may be out of ink or paper.
• There may be a paper jam.
• The mechanical components may be damaged or misaligned.
• And many more issues.

For these issues, consult the printer's help manual and/or the manufacturer's website.
In other cases, however, you may be able to troubleshoot issues from your Linux client or
server. As always, ensure your specific printer is supported by Linux-compatible drivers, and
that those drivers are loaded. If you're trying to connect to your printer over a network but
can't, use network diagnostic tools like ping to ensure that your printer is identifiable on the
network and that it can be reached.

If you're using Linux as a print server in an office environment, the printer may become sluggish
or unresponsive if multiple users are trying to print to it. Use lpq to check the status of print
jobs; if any jobs are too large, or there are too many in the queue, you can use the lprm
command to stop a job with the job number you provide. For example, lprm 4 will remove job
4 from the queue. This will help clear up the queue and lighten the load on the printer.

Linux LPIC-1 618


MEMORY ISSUES
From a software perspective, memory can "leak" when a process fails to free up allocated
memory when it is no longer needed. The total available memory on the system is quickly
exhausted. This can lead to general performance degradation and system instability because
other software is unable to access the memory it needs. In these cases, you can use memory
monitoring tools like free as well as process monitoring tools like top to identify the problem,
then deal with the offending process (e.g., by killing it).

However, some memory issues indicate a fault in the physical RAM modules or the
motherboard that RAM is slotted into. Like other operating systems, Linux has ways of
detecting these faults during operation. For example, system logs that record a "Machine Check
Exception" error message usually indicate an issue with RAM. The mcelog command can
retrieve and print these error messages for easier analysis. If the messages contain error-
correcting code (ECC) errors, one of the memory modules has probably failed.

To confirm RAM module failure, you can use utilities like MemTest, MemTest86+, and
memtester to perform a stress test on all RAM modules for several hours, reporting any errors
that are encountered.

Linux LPIC-1 619


VIDEO ISSUES
Common video-related issues include:
• Consistent or intermittent blank screens.
• Incorrectly displayed colors.
• Multiple monitors not being detected.
• Sluggish performance in video-intensive applications.
• And more.

Some of these issues can be addressed by ensuring that monitors and other display devices are
properly connected and are compatible with the system and user software.

When it comes to performance of video-intensive applications, GPU driver support is one of


the biggest hurdles. Linux has historically been less well-supported by GPU manufacturers than
Windows, particularly with the two main GPU vendors: AMD and Nvidia. However, support
from both vendors has improved in recent times. It's crucial to have the latest drivers in order
to ensure optimal video performance. These drivers are made available for download from the
vendor's website.

Linux LPIC-1 620


STORAGE ADAPTER ISSUES
There are several possible indicators of a faulty bus adapter, including:
• Poor data transfer speeds.
• Less total space available than expected.
• Excessive read/write errors.
• Inability to read/write at all.
• The system cannot detect devices at all.
• And more.
The problem might be with the physical HBA itself, or it might be with the interface that the
HBA uses, such as SCSI or SATA. The first step is to ensure that the HBA is powered. Then, you
need to ensure that the storage device you're connecting to the HBA uses the appropriate
interface. Even though different generations of SCSI and SATA are usually backward compatible,
if the bus interface uses older technology than the drive, then the drive will be limited to that
older specification. And, of course, ensure that all devices are properly slotted and all cables
are connected and damage-free.
In some cases, if the system doesn't recognize a new SCSI device, you may need to rescan the
SCSI bus it's attached to. The following command rescans a specific SCSI bus:
echo "- - -" > /sys/class/scsi_host/host#/scan
The # represents the number of the bus you're trying to scan. The hyphens in the echo
statement are wildcards for SCSI controller, SCSI channel, and logical unit number (LUN),
respectively. This will prompt the system to scan for new devices on this bus and add any that
are detected. However, this process can be disruptive, so it should only be used when
necessary.

Linux LPIC-1 621


RAID TROUBLESHOOTING
As you've seen, the mdadm command is used to manage RAID arrays. The -F option
activates monitor mode, enabling you to identify missing or failed drives in an array.
You can then use some of the command's other modes to rebuild an array after
you've removed the faulty drive.
Some other useful mdadm options for troubleshooting RAID issues are as follows:
• -f —Mark a specified device as faulty to prepare it for removal from the array.
• -r —Remove the specified device from the array. Use the keyword failed to specify
that all devices marked as faulty should be removed.
• --re-add —Add a removed device back to the array for the purpose of recovering
data stored on the device.
• -a —Add a device to the array as a hot-spare. If the array is degraded, it will rebuild
data on that spare. This behavior only applies to devices that are unable to be re-
added or were never part of the array to begin with.

Linux LPIC-1 621


THE lshw COMMAND
The lshw command lists each detected hardware component on the system and provides
details about each device. The command pulls information from many different files in multiple
device file locations like /proc/ and outputs in a hierarchical format. Information that lshw
outputs includes the vendor, product name, capacity, speed, and many other attributes of the
motherboard, CPU, RAM modules, peripheral devices, storage devices, and so on.

Like other commands and files that retrieve device information, you can use lshw to identify
whether or not a device is recognized by the kernel, as well as to review a device's capabilities
and characteristics.

SYNTAX
The syntax of the lshw command is lshw [options]

DEVICE CLASSES
The output of lshw groups devices into one of several classes. You can filter the total results by
specifying a class with the -c option. For example, issuing lshw -c network will only output
details about network-class devices. To see a list of classes currently in use on your system,
enter lshw -short | sort -k2 to generate a non-detailed list of devices, sorted by the class
column.

Linux LPIC-1 622


Listing information about hardware devices.

Linux LPIC-1 623


THE dmidecode COMMAND
The dmidecode command dumps the system's Desktop Management Interface (DMI) table and
presents it in a human-readable format. The DMI table is an industry standard for tracking
information about hardware components. It separates components into types, with each type
given a number—for example, type 4 is a processor, type 39 is a power supply, etc. Like similar
commands, you can use dmidecode to verify connected devices and whether or not they
support certain features. However, the authors of dmidecode caution that the information in
DMI tables is, more often than not, "inaccurate, incomplete, or simply wrong." Therefore, don't
rely on DMI tables as the sole source of hardware information.

SYNTAX
The syntax of the dmidecode command is dmidecode [options]

Linux LPIC-1 624


ABRT
The Automatic Bug Reporting Tool (ABRT) is a utility, typically used on Fedora- and RHEL-based
distros, that analyzes and reports on problems detected during system runtime. ABRT collects
data like memory dumps from crashed applications to help administrators diagnose and
troubleshoot issues. It can also report on problems with various devices, such as MCEs that
typically indicate hardware failure.
ABRT can redirect problem data to many different destinations, including public issue trackers
like Bugzilla and support sites like Red Hat Technical Support (RHTSupport). Or, it can simply
write to a local or remote file in a standard format. The default location for problem data is in
/var/spool/abrt/ with timestamped subdirectories for each problem detected.

ABRT UTILITIES
ABRT runs as the abrtd daemon and can be configured using abrt-cli or abrt-gui, depending on
your system (and your own preference). You can use both
utilities to list problem data, view details about problem data, analyze and report on problem
data, and remove unnecessary reports.

Linux LPIC-1 625


GUIDELINES FOR TROUBLESHOOTING HARDWARE ISSUES
Use the following guidelines when troubleshooting hardware issues.

TROUBLESHOOT HARDWARE ISSUES


When troubleshooting hardware issues:
• Ensure that hardware devices are supported through robust drivers.
• Ensure that the necessary drivers are installed and loaded in the kernel.
• Ensure that hardware devices are compatible with the Linux software that controls,
manages, or interfaces with them.
• Verify that the system has the correct keyboard layout and language set.
• Verify that a network-enabled printer is identifiable on the network.
• Stop large or numerous print jobs with the lprm command.
• Check the mcelog for memory errors.
• Run a utility like memtester to stress test RAM modules.
• Download the latest GPU drivers from the vendor's website.
• Ensure storage and peripheral devices are properly slotted into the correct buses.
• Ensure connected cables are not loose or damaged.
• Use a command like lshw to identify connected hardware.
• Be aware that dmidecode may produce inaccurate results.
• Review crash data compiled by the ABRT utility.

Linux LPIC-1 626


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 627


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 628


Another major component of the operating system is networking. Networking is crucial for
almost all modern systems, including those that run Linux®. In this lesson, you'll review some of
the fundamental concepts that are involved in networking, and then you'll configure
networking in your Linux systems. This will ensure your systems, especially servers, will be able
to communicate with other computers both locally and around the world.

Linux LPIC-1 629


In this topic, you will:

• Identify the fundamental concepts of the TCP/IP networking protocol.


• Identify the roles that various Linux servers can play.
• Connect to a network.
• Configure DNS and DHCP client services.
• Configure cloud and virtualization technologies.
• Troubleshoot networking and connection issues.

Linux LPIC-1 630


Linux LPIC-1 631
Before you start developing your Linux-specific networking skills, you need to review some of
the fundamental concepts that comprise a modern TCP/IP network. This is essential knowledge
that will prepare you for the configuration ahead.

TCP/IP
The networking process is governed by protocols. Much like human conversation, computer
network communications are managed by rules. These rules control how much information is
communicated at any given time, what addresses are used to represent nodes, how nodes take
turns communicating on the network, what error checking may exist, etc. Many families or
suites of protocols have existed over the years, but the only protocol suite of note today is
Transmission Control Protocol/ Internet Protocol (TCP/IP). This is the default protocol of the
Internet and most internal private networks.

Linux LPIC-1 632


THE OSI MODEL
The Open Systems Interconnection (OSI) model standardizes how networking is meant to
function. The OSI model contains seven layers. Each layer represents an area of responsibility
that must be satisfied for the networking process to work. IT professionals need to be aware of
how these layers work. You should memorize them, in order, with a brief definition of each
layer.

The OSI Model also serves as a standard point of reference when communicating with other
network professionals. For example, you may be instructed to purchase a "Layer 2 switch" or to
troubleshoot a "Layer 3" problem. It serves as a common reference point for devices, and a
guide for developers creating network applications.

Linux LPIC-1 633


There are a great many additional functions and details about the OSI model. As a networking
professional, you must familiarize yourself with these functions. This table only serves as a brief
overview.

Layer Name Basic Function


7 Application Supports applications and end-users.

6 Presentation Formats data for use.


Establishes, maintains, and tears down a
5 Session
connection.

4 Transport Enables reliable transmission of information.

3 Network Enables logical addressing (IP addresses).

2 Data link Enables physical addressing (MAC addresses).

1 Physical Enables physical network connectivity.

Linux LPIC-1 634


TCP/IP LAYERS
The TCP/IP protocol suite satisfies the requirements of the OSI model in four layers. The suite is
used to govern network communications on most internal networks. It is the protocol suite of
the Internet, as well. TCP/IP is used by Linux, Unix®, macOS®, Windows®, etc. It is imperative
that you have a basic understanding of the TCP/IP suite and its layers.

An understanding of the TCP/IP suite can aid in troubleshooting and network configuration. For
example, IP address support occurs in the IP layer, while application support occurs at the
application layer.

Linux LPIC-1 635


The layers of the TCP/IP suite.

Linux LPIC-1 636


NETWORK IDENTITIES
The term "node" refers to devices with an identity on the network. That identity may be
represented by a physical address or one of two logical addresses, or any combination of the
three.

Identifier Description
Each network interface card (NIC) has a unique identity coded into
it that identifies that NIC on network segment. That code is
MAC address referred to as a media access control (MAC) address. It is the most
fundamental network identity and is considered a physical
address.
Each NIC may be assigned a logical address called an IP address.
The IP address uniquely identifies the NIC in the network
environment.
IP address
IP addresses are shown in dotted decimal (base 10), which is a
range of 0–9. The computer works with the IP address in binary
(base 2), which is a range of 0–1.
Nodes may be given a human-readable name that helps people
better understand what device they are working with. This
Hostname identity is often configured during the installation of the operating
system and is sometimes called the "computer name." Hostnames
are limited to 255 characters.

Linux LPIC-1 637


NETWORK DEVICES AND COMPONENTS
There are several essential network devices and components to understand. These may be part
of the troubleshooting process or network installation. Linux systems need to be configured
properly to interact with these network devices and components.

Device/Component Description
This device acts as a concentrator, centralizing all network
connections for a segment to a single device. Switches can be
Switch used to manage traffic for performance and security concerns. As
a general rule, switches work with MAC addresses at Layer 2 of
the OSI model. There are switches that work at higher layers, too.
This device acts as a control point for communications between
network segments. Administrators can configure the router to
Router permit or deny certain kinds of traffic, as well as pass traffic from
one network segment to another. Routers work with IP addresses
at Layer 3 of the OSI model.
Typically, network cable is twisted pair Ethernet cable. Twisted
pair may come shielded (STP) or unshielded (UTP). It is
inexpensive and relatively easy to work with. It is the most
Media
common type of network cable. Other cable types include coaxial
(coax) and fiber optic. Wireless networks forego cables and can
transmit data over the air.

Linux LPIC-1 638


DNS AND DHCP
There are two network services that are commonly involved with TCP/IP network configuration.
You will need to understand the role of these services in order to properly configure your Linux
system.

Humans have a difficult time working with long strings of numbers such as IP addresses. The
Domain Name System (DNS) service provides name resolution, a way of relating an easy-to-
remember hostname with a difficult-to-remember IP address. DNS is implemented as a
database hosted on one or more servers. The database may only contain the names and IPs of
nodes in your own network, or it may be part of the larger Internet DNS infrastructure.

All nodes on the network must be configured with a unique IP address and other corresponding
information. There are two ways of accomplishing this configuration— statically or dynamically.
Static configuration is usually appropriate for servers and network devices, while dynamic
configuration is typically used with end-user workstations. The Dynamic Host Configuration
Protocol (DHCP) service provides dynamic configuration.

Linux LPIC-1 639


IPV4 ADDRESSING
IP addresses provide an addressing system for managing network identities. Internet Protocol
version 4 was defined in 1981. The addresses are 32 bits in length, providing approximately 4.3
billion addresses. Humans usually work with IP addresses in the decimal form, such as
192.168.2.200, while network devices work with the address in binary.

IPv4 addresses are divided into at least two portions—a network identifier and a host identifier.
The network identifier defines to which network segment the host belongs, and the host
identifier uniquely identifies that host within the segment. Because the network ID may use
different bits within the address, a second numeric value is used to show which portion of the
IP address is the network ID and which part is the host ID. This value is known as the subnet
mask. It is essential to understand the role of the subnet mask. It indicates where in the IP
address the division is between the network ID and the host ID.

Linux LPIC-1 640


IPV4 CLASSES
The approximately 4.3 billion IPv4 addresses are divided into five classes. These classes provide
a framework for possible segmentation of networks. Each class provides a specified number of
networks, as well as a number of hosts available on each network. For the first three classes,
the division between the network ID and the host ID occurs at one of the dots. Network
professionals must be able to recognize all five classes by the value of the first octet, and know
the default subnet mask for each class.

The 4.3 billion IPv4 addresses are divided into the following five classes

Class Start Addr. End Addr. Networks Hosts per Network Default Subnet Mask
A 0.0.0.0 127.0.0.0 126 16,777,214 255.0.0.0 or /8
B 128.0.0.0 191.255.0.0 16,384 65,534 255.255.0.0 or /16
C 192.0.0.0 223.255.255.0 2,097,152 254 255.255.255.0 or /24
D 224.0.0.0 239.255.255.255 N/A N/A N/A
E 240.0.0.0 255.255.255.255 N/A N/A N/A

Linux LPIC-1 641


RESERVED RANGES
In addition to knowing the five IP address classes, there are several other IP addresses or
address ranges that are important. Due to the depletion of IPv4 addresses, there are three IP
address ranges that are reserved for internal use only. You will almost always find these in use
on internal business and home networks.
• Class A Reserved: 10.0.0.0–10.255.255.255
• Class B Reserved: 172.16.0.0–172.31.255.255
• Class C Reserved: 192.168.0.0–192.168.255.255

LOOPBACK AND LINK-LOCAL


There are also two other IP address configurations to recognize. The loopback address is used
for diagnostics purposes and to give the system the ability to network to itself. The link-local
range is used for zero-configuration LANs or when the DHCP lease generation process fails.
Link-local is also referred to as Automatic Private IP Addressing (APIPA).
• Loopback: 127.0.0.1
• Link-local: 169.254.0.0–169.254.255.255

Linux LPIC-1 642


IPV6
The IPv4 addressing scheme has many limitations. A newer standard is being implemented in
the form of Internet Protocol version 6. IPv6 addresses many of the weaknesses of IPv4.
The main advantages of IPv6 over IPv4 are:
• IPv6 has a much larger address space.
• IPv6 has built-in encryption.
• IPv6 has more efficient routing.
Linux is fully compatible with IPv6, so Linux server and workstations should not be a limiting
factor in the deployment of IPv6 in a network environment.

Linux LPIC-1 643


NETWORK PORT
Network port numbers are numeric values assigned to the various application-layer protocols.
Network devices use these port numbers to understand what application will handle the
communication. Humans work with the application-layer protocols by name, such as Hypertext
Transfer Protocol (HTTP). Computers need to work with these by port number.
A few common port numbers are:
• 22: Secure Shell (SSH)
• 25: Simple Mail Transfer Protocol (SMTP)
• 80: Hypertext Transfer Protocol (HTTP)
• 110: Post Office Protocol version 3 (POP3)
• 443: Hypertext Transfer Protocol Secure (HTTPS)

Linux LPIC-1 644


NETWORK SEGMENTS
Network administrators will divide a network into segments in order to better manage network
traffic. Their goal may be to manage that traffic more efficiently, resulting in better network
performance, and/or to isolate that traffic for the purpose of security.

The logical divisions of the network are referred to as subnets and are identified by a network
ID. This network ID is part of the IP address each node is using. All nodes in that subnet will
have the same network ID in their IP address. Each node will have a unique host ID within that
subnet. Recall that the subnet mask shows which part is the network ID and which part is the
host ID.

Linux LPIC-1 645


A network segmented into two subnets

Linux LPIC-1 646


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 647


Linux LPIC-1 648
NTP SERVICES
The Network Time Protocol (NTP) service enables the synchronization of a node's time with a
designated, definitive time source. Time synchronization is essential in networking, making NTP
configurations very important. Linux systems may be configured as NTP sources or NTP clients.
NTP uses UDP port 123.

Linux LPIC-1 649


NTP clients synchronizing with an internal NTP server, which itself synchronizes with an NTP
server on the Internet.

Linux LPIC-1 650


SSH SERVICES
The Secure Shell (SSH) service provides an authenticated, encrypted method of connecting to a
remote (or even a local) system. Most frequently, SSH is used for remote administration,
though it can be used as a tunnel to carry other kinds of network communications securely. SSH
administration is very common in the Linux and Unix worlds. Linux may be configured as an SSH
client and/or server. SSH uses TCP port 22.

PUTTY
Microsoft Windows operating systems do not commonly use SSH, though it can be added to
them. One of the most common Windows SSH clients is called PuTTY, and it is an excellent tool
for those working with both Linux and Windows systems.

Linux LPIC-1 651


WEB SERVICES
Web servers host the files and images that make up websites. Client machines connect to the
web server and download the files and images. Linux is a very common platform for hosting
websites. Web services on Linux are typically hosted through a service called Apache.

Two protocols are primarily used with web services: Hypertext Transfer Protocol (HTTP) uses
TCP port 80 and Hypertext Transfer Protocol Secure (HTTPS) uses TCP port 443.

Linux LPIC-1 652


CERTIFICATE AUTHORITY SERVICES
Certificates provide a way of guaranteeing identity. They are based on the use of a public key
infrastructure (PKI) and asymmetric encryption. Certificate authority (CA) servers manage the
enrollment, approval, expiration, and revocation of certificates. One use of certificates is in
guaranteeing the identity of websites for the use of HTTPS connections. Linux servers can be
configured as certificate authorities.

Linux LPIC-1 653


NAME SERVER/DNS SERVICES
Name resolution is the relating of easy-to-remember hostnames with difficult-to- remember IP
addresses. These relationships are typically stored in databases on Domain Name System
(DNS) servers. A DNS server may contain records for a company's internal network, or it may be
part of the Internet's name resolution infrastructure. Linux systems may be configured as DNS
servers and/or as DNS clients. DNS uses port 53 for both TCP and UDP.

Linux LPIC-1 654


DHCP SERVICES
Linux servers and workstations need to be properly configured to participate on the network.
These configurations include an IP address, a subnet mask, default gateway (router), and other
values. The configurations can be set manually, referred to as "static," or automatically, referred
to as "dynamic." When a client is configured to retrieve an IP address dynamically, it does so by
leasing the configuration from a Dynamic Host Configuration Protocol (DHCP) server.

Linux systems may be configured as DHCP servers, providing IP address configurations to other
systems, or as a DHCP client, leasing an IP address configuration from a DHCP server. Typically,
systems playing the role of server will have a static IP configuration, whereas client computers
will have a dynamic IP configuration. The DHCP service uses UDP port 67 and 68.

Linux LPIC-1 655


SNMP SERVICES
Some network devices are capable of passing information about their performance and
workloads to a central management database. These devices use the Simple Network
Management Protocol (SNMP) service to accomplish this goal. Linux can act as a central
management server for SNMP devices, or as an SNMP device itself. SNMP is not as common as
it once was due to security concerns. SNMP uses UDP port 161 and port 162 for both TCP and
UDP.

Linux LPIC-1 656


AUTHENTICATION SERVICES
Centralized authentication of user identities, rather than local authentication, makes the
network more secure, simpler to manage, and easier for users to navigate. Authentication
servers hold information about user identities in a directory store. When a user attempts to
authenticate to a system, their login name and password are compared with what the
authentication server has stored, instead of what the local workstation has stored. There are
many kinds of authentication used by Linux. One example is Kerberos and another is
Lightweight Directory Access Protocol (LDAP).

Linux LPIC-1 657


PROXY SERVICES
A proxy service resides on a system that has a direct connection to the Internet (an untrusted
connection) and also an internal network connection (a trusted connection). The purpose of
the proxy is to pass Internet requests between the two networks. One example of proxy
services is web browsing. A client computer will pass a web request to a proxy, then the proxy
will connect to the Internet to satisfy the request. The returned information comes to the
proxy, which then passes the web data to the client machine that originally requested it.

Linux systems can be configured as proxy servers. Linux is often a good choice for this role
because it can be run in a very lightweight configuration and is considered to be relatively
secure. One common example of a proxy service for Linux is Squid. Squid has existed for a very
long time and is frequently included with many Linux distributions.

Linux LPIC-1 658


LOGGING SERVICES
It is essential for Linux system administrators to be aware of occurrences on the servers they
are responsible for. Log files can provide an immense amount of information about how the
server boots, what services are running and how they are performing, what users may be doing
on the system, etc. The traditional log file mechanism for Linux has been syslog, though there
are now several different logging services available.

One of the key functions of these logging services is to centralize log files from many Linux
servers to one. This makes them easier to archive for service-level agreements (SLAs),
troubleshooting and diagnostics, and performance auditing. With centralization, the Linux
systems will forward their logs to a single server, which can then store all the log files. This long-
term storage may be in the form of an SQL database or other database technology.

Linux LPIC-1 659


MONITORING SERVICES
There are many monitoring services available in Linux. Some monitor specific applications, like
the Apache web service, while others monitor the Linux operating system itself. Whether or not
these particular tools are installed by default will depend on which distribution you're using.

Examples of monitoring services include:


• top —monitors CPU and memory usage.
• ApacheTop—provides log file analysis for Apache, as well as information on connection
response times, etc.
• Monit—a simple monitoring utility for Linux that watches hardware usage as well as
directory and file information.
• System Monitor—the GNOME GUI tool for gathering information on system resource usage.

Linux LPIC-1 660


LOAD BALANCING SERVICES
Load balancing services are used to distribute inbound connection requests across multiple
servers. A very common use for load balancing is to distribute connection attempts among web
servers. A web server would be a single point of failure and could easily be overwhelmed by
large amounts of traffic. Using multiple web servers alleviates these concerns, but a load
balancing service is needed to ensure connections are spread across the available servers.

Linux LPIC-1 661


CLUSTERING SERVICES
On an internal network, access to services such as databases is essential to productivity. Data
may reside on a storage area network (SAN). Access to the SAN and its stored content may be
provided through a cluster of servers. Each server in the cluster is referred to as a node and can
accept client connections. If one node in the cluster goes down, whether planned or
unplanned, the other nodes can maintain availability.

Linux LPIC-1 662


FILE/PRINT SERVICES
File and print services are two of the most common network services; nearly every network has
its foundation in basic file storage and print capabilities.

File servers, like those that use the File Transfer Protocol (FTP), enable the centralization of user
data. Such centralization provides many advantages in a business network. These advantages
include easier and more efficient backups, more secure storage of information, greater fault
tolerance, and easier access to information. It is much easier to manage data on a single file
server than to manage information that may be distributed across many end-user workstations.
Centralized printing services also include greater efficiency and significant cost savings. Print
costs are measured on a price per page basis. A single large, very fast, very efficient network
print device will be much less expensive on a per page basis than individual print devices
provided to each end-user. It is also much easier to manage paper and toner supplies for a few
powerful print devices than for a great many individual print devices.

SAMBA AND NFS


Recall that Linux has a Server Message Block (SMB)-compatible file sharing protocol called
Samba, as well as a separate file sharing protocol called NFS. Samba enables the integration of
Linux and Windows systems through a protocol that is native to Windows. When added to a
Linux workstation, that workstation can use the native Windows file and print sharing protocol
to access shared resources on a Windows Server. When the Samba service is added to a Linux
server, the server uses the native Windows protocol to share directories to Windows clients.

Linux LPIC-1 663


NFS, on the other hand, is a native Unix/Linux protocol used to provide workstations
access to directories stored on a server. The centralization of files on a single server is
highly desirable, because it makes physical security and backups much more
straightforward. The primary configuration file for NFS is the /etc/exports file. This file
is used to specify what directories are exported or made available on the network, as
well providing access controls to those directories.

Linux LPIC-1 663


DATABASE SERVICES
Databases are used to store large quantities of data and to make it easier to query the database
to retrieve the needed information. There are two database types frequently encountered in
Linux environments—SQL and NoSQL database structures. Structured Query Language (SQL)
databases use relational tables to relate information, whereas NoSQL databases do not
organize information with relational tables. Examples of SQL databases include: MySQLTM,
MariaDB®, and PostgreSQL. An example of a NoSQL database is MongoDB®.

Linux LPIC-1 664


VPN SERVICES
Virtual private network (VPN) servers enable remote users to connect to the internal company
network and access internal resources as if they were physically present at the network
location. This is very useful for users who work from home or work from the road. Linux is
capable of acting as both a VPN server and a VPN client.

VPN services are especially important because home and hotel networks are untrusted, as is
the Internet. Content is encrypted within the VPN client computer before it is sent across the
untrusted networks, then decrypted in the VPN server at the other end of the connection. Any
data intercepted on the untrusted networks remains secure because of this encryption.

Linux LPIC-1 665


VIRTUALIZATION/CONTAINER HOST SERVICES
Virtualization has become essential to business services in the past decade.

Virtualization is split into two general types: virtual machines and containers.

Virtual machines (VMs) rely on virtualization of the computer hardware. A hypervisor layer of
software resides over the physical hardware and manages the allocation of that physical
hardware to the virtual machines that are created. Operating systems, including Linux, can then
be installed into the virtual machine. A virtual machine can provide the same full functionality
of a traditional, physical server. VMs typically provide cost savings by more efficient use of the
hardware along with many additional fault tolerance and management advantages. Examples
of virtualization include Oracle® VM VirtualBox, VMware WorkstationTM, Microsoft Hyper-V®,
and Kernel-Based Virtual Machine (KVM).

Containers operate with a different structure. A single host operating system runs multiple
applications in isolation from each other, but all applications share the OS and its resources.
Containers also provide a great deal of efficiency and management advantages. One example of
a container service is Docker.

Linux LPIC-1 666


EMAIL SERVICES
Email services are key components of business communications. Email servers are responsible
for the distribution of electronic mail within an organization or between organizations.
Examples of email services for Linux include Sendmail and Postfix.

The common email protocols are:


• Simple Mail Transfer Protocol (SMTP) (TCP port 25)
• Post Office Protocol (POP3) (TCP port 110)
• Internet Message Access Protocol (IMAP) (TCP port 143)

Linux LPIC-1 667


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 668


Linux LPIC-1 669
Now that you're familiar with foundational networking concepts, you can start to configure
networking on your Linux servers. You'll use various utilities to ensure that your systems are
able to connect to the network and talk to other computers.

HOSTNAME CONFIGURATION
The systemd startup mechanism uses a command named hostnamectl set- hostname to
configure the hostname value for the system. As with other services, once the configuration
change is made, you must also restart the service. Here is an example of setting a new
hostname with the hostnamectl command:

sudo hostnamectl set-hostname server01

Linux LPIC-1 670


IP CONFIGURATION
For a computer to participate on a network, it must have a valid identity as well as know the
location of a few key services. The identities include a MAC address, an IP address, and a
hostname. IP addresses must be configured on the system. Hostnames are normally configured
during the installation of the operating system.

The IP configurations required include an IP address, the related subnet mask, the location of
the default gateway (router), and typically the location of one or more name servers (DNS
servers).

It is essential to verify this information early on in the configuration and troubleshooting


processes. Any errors or misconfigurations in these values will usually result in the system not
being able to participate on the network.

Linux LPIC-1 671


NetworkManager
Linux distributions often include a utility called NetworkManager to aid in the proper
configuration of the IP information. NetworkManager includes three different interfaces that
may be used, depending on whether or not a GUI is available on the Linux system.

Linux LPIC-1 672


THE nmcli COMMAND
The nmcli tool is the most fundamental of the NetworkManager interfaces. It contains many
subcommands that enable you to view and configure network information. Because many
network servers will not include a GUI, it is important to be comfortable with nmcli to manage
network settings.

SYNTAX
The syntax of the nmcli command is nmcli [options] [subcommand] [arguments]

Linux LPIC-1 673


The following are some example of subcommands you can use with nmcli

Subcommand Used To

general status View a summary of network connectivity data.

connection show View identification information for each NIC.

con up {device ID} Enable the specified NIC.

con down {device ID} Disable the specified NIC.

con edit {device ID} Enter interactive mode to configure the specified NIC.

device status Display the current status of each NIC.

Linux LPIC-1 674


THE nmtui UTILITY
While Linux administrators often work at the command-line, it is certainly useful to have a
visual representation of network configuration options. By running the nmtui command, you
can call up a text-based user interface, or TUI. Navigating a TUI is accomplished by using the
Tab key, the Spacebar, the Enter key, and the arrow keys. The Tab key moves the cursor from
field to field. The arrow keys are used to make selections within the field. The Enter key is used
to activate a setting, such as OK or Quit. The Spacebar is used to check or uncheck a check box.

Linux LPIC-1 675


Editing a network interface using a TUI.

Linux LPIC-1 676


THE nmgui UTILITY
NetworkManager also includes a GUI tool, which is particularly helpful for managing the
network connections of workstations. The nmgui tool enables IPv4 and IPv6 configuration, as
well as providing access to a wide variety of other network settings. This tool will certainly be
familiar to most end-users.

Linux LPIC-1 677


Viewing network interface details in a GUI.

Linux LPIC-1 678


THE ifconfig COMMAND
The ifconfig command enables a user to view the current IP addressing information for each
NIC recognized by the system. Viewing the IP address configuration is one of the earliest steps
in network troubleshooting. The ifconfig command shows the IP address, subnet mask,
broadcast ID, MAC address, basic performance information, and NIC name. The tool also
enables NICs to be placed in an up or a down configuration (enabled or disabled).

The ifconfig command is officially deprecated in Linux, as noted in the man page; however, it is
still available in many current distributions.

SYNTAX
The syntax of the ifconfig command is ifconfig [options] [interface]

Linux LPIC-1 679


THE ip COMMAND
The ip command replaces ifconfig in many distributions. It provides similar information to
ifconfig, including IP address, subnet mask, MAC address, etc. The ip command will be one of
the first tools used in network troubleshooting on a Linux system.

The following are examples of using the ip command:


• ip addr show —shows the IP address information on all interfaces.
• ip link —shows the status of each interface.
• ip link set eth1 up —enables the interface identified as eth1
• ip link set eth1 down —disables the interface identified as eth1

SYNTAX
The syntax of the ip command is ip [options] {object} [subcommand]

Linux LPIC-1 680


Showing details for a network interface.

Linux LPIC-1 681


THE iwconfig COMMAND
The iwconfig command is used to provide wireless NIC configurations, including settings like
SSID, encryption information, etc.

SYNTAX
The syntax of the iwconfig command is iwconfig [options] [interface]

iwconfig COMMAND OPTIONS


The following table describes some common iwconfig command options:

Option Used To

nick {name} Set a nickname for the NIC.


Set the operating mode for the NIC that corresponds to the network
mode {mode}
topology.
freq {number} Set the Wi-Fi frequency used by the NIC

channel {number} Set the Wi-Fi channel used by the NIC.

retry {number} Set the maximum number of MAC retransmissions for the NIC.

Linux LPIC-1 682


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 683


THE ethtool COMMAND
The ethtool is used to manage NIC driver and network configurations. Whether or not it is
installed by default will depend on the distribution in use. The ethtool utility has a great many
options for gathering information.

SYNTAX
The syntax of the ethtool command is ethtool [options] {device name}

ethtool COMMAND OPTIONS


The following table describes some common ethtool command options.

Option Used To

-S {interface} Show statistics for a NIC.

-i {interface} Show driver information for a NIC.

-t {interface} Execute a self-test on the NIC.


Change some of a NIC's settings, such as its speed and
-s {interface} {setting} {value}
duplex mode.

-f {interface} {image} Write ("flash") a firmware image to the NIC.

Linux LPIC-1 684


Showing statistics for a network interface.

Linux LPIC-1 685


THE brctl COMMAND
Network bridging involves associating two networks that normally would not pass network
traffic between them. Bridging works at OSI Layer 2 with MAC addresses. A Linux system can be
configured to bridge two networks. The brctl (bridge control) command is used to configure
bridging within Linux.

A common example of bridging is as follows:


• brctl show —View the bridging configuration.
• brctl addbr {bridge name} —Create an empty bridge.
• brctl addif {bridge name} eth0 —Add eth0 to the bridge.
• brctl addif {bridge name} eth1 —Add eth1 to the bridge, linking the networks connected to
eth0 and eth1.

SYNTAX
The syntax of the brctl command is brctl [command]

Linux LPIC-1 686


NIC BONDING
Associating two or more NICs together on the same system enables aggregation of their
combined bandwidth, fault tolerance/redundancy, and load balancing. The two interfaces
would normally be managed independently and have different IP address configurations. When
using bonding, the interfaces are managed as a single device and have the same IP address
configuration. The ability to bond two or more NICs is an important feature for a server. If there
are two NICs in a bond, and one fails, the other is present to continue providing connectivity.

NIC bonding can be configured in an active/passive setup. In this setup, one primary NIC is
active, and a secondary NIC is on standby (passive). If the active NIC fails, the system
automatically fails over to the secondary NIC to maintain availability. NIC bonding can also be
configured in a load balancing manner, where the combined bandwidth of each is used in a way
that one of the NICs is not overwhelmed. The NICs that are members of the bond are referred
to as "slaves."

NIC bonding is supported in Linux, but support must also be present in the network switch. This
support is called EtherChannel. It is a feature of most enterprise-class switches.

Linux LPIC-1 687


NIC BONDING PROCESS
The process for creating a NIC bonding configuration begins with creating the bond, then
adding NICs to the bond.
1. Ensure the kernel module that supports NIC bonding is loaded.
2. Run the modprobe --first-time binding command to load the module.
3. Run the modinfo binding command to see additional information on the kernel module.
4. Create a file named bond.conf in the /etc/modprobe.d/ directory with the following
content: alias bond0 bonding
5. Create the bond interface:
a. nmcli con add type bond con-name bond00 ifname bond00 mod active-passive
6. Add the NIC interfaces to the bond interface:
a. nmcli con add type bond-slave con-name bond00- <device ID> ifname <device ID>
masterbond00
b. nmcli con add type bond-slave con-name bond00- <device ID> ifname <device ID>
masterbond00
7. Set the bond00 interface with its IP configuration as if it were a regular NIC. For a server,
this usually means you will set a static IP address.
8. Test the connection, including any failover settings. Don't forget that you may also need to
configure the switch to support NIC bonding.

Linux LPIC-1 688


THE /etc/sysconfig/network-scripts/ DIRECTORY
The /etc/sysconfig/network-scripts/ directory contains network device configuration files.
These files include the configurations of any NICs, bonds, and bridges that might exist on the
Linux system. These files usually take the form of ifcfg-<NIC>. Settings can include whether the
NIC is configured for static or dynamic IP addresses, whether the NIC is enabled or not, etc. The
exact settings vary depending on the needed configuration and device type.

While it is possible to manually edit these files with a text editor like Vim or nano, the
NetworkManager utility is often a much better way of managing the interfaces. There is a
command-line, text interface, and graphical interface for NetworkManager.

THE /etc/network/ DIRECTORY


For Debian-derived distributions, network configuration files representing the interfaces can be
found in the /etc/network/ directory. Many Debian-based distributions also use
NetworkManager, so editing the files in /etc/network/ is usually not necessary.

NETPLAN
Netplan is a network configuration utility found on some distributions. It uses YAML description
files to configure network interfaces. These files are stored in the /etc/netplan/ directory. You
will use a text editor to create or modify interface configuration files. Netplan includes
subcommands to make configurations more reliable. For example, you can enter sudo netplan
to have the configuration file checked for syntax errors before attempting to implement it. The
sudo netplan apply command actually makes the configuration change.

Linux LPIC-1 689


The /etc/sysconfig/network-scripts/ directory.

Linux LPIC-1 690


THE /etc/sysconfig/network FILE
The /etc/sysconfig/network file is used to configure whether networking should be enabled at
boot, as well as hostname information, gateway information, etc. These settings may instead
be configured on a per-interface basis in the /etc/ sysconfig/network-scripts/ifcfg-<NIC> files.

Linux LPIC-1 691


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 692


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 693


Linux LPIC-1 694
STATIC VS. DYNAMIC IP ADDRESS CONFIGURATION
IP address configurations can be set two ways: statically or dynamically. Each method has
advantages and disadvantages. It is important to know when to use each method.
Static IP address configuration means that the settings are implemented manually by an
administrator. This method increases the risk of mistakes, but also ensures the system always
has the same identity. Static IP address configurations are usually appropriate for network
devices (routers, network switches, etc.) and servers. They may also be used for network print
devices.
Considerations for static configurations:
• IP address configuration never changes.
• Possibility of mistakes when entered manually.
• Administrative workload is increased for configuration and reconfiguration.

Dynamic IP address configuration means that the settings are retrieved from a server. This
method decreases the risk of mistakes, but also means the system may not always have the
same IP address. Dynamic IP address configurations are usually appropriate for client machines.
They may also be used for network print devices.
Considerations for dynamic configurations:
• IP address configuration may change over time.
• Reduces the risk of typographical errors during configuration.
• Administrative workload is decreased for configuration and reconfiguration.

Linux LPIC-1 695


DHCP CONFIGURATION
A Dynamic Host Configuration Protocol (DHCP) server contains one or more pools of IP
addresses and related configuration options that client machines can lease. This saves a
significant amount of administrative effort, since IP address information does not have to be
configured statically for each system.

DHCP servers are configured with a scope, or a range of available IP addresses, along with
additional options. The DHCP service must be installed on the server that will host the service
and allow client machines to lease configurations.

Linux LPIC-1 696


THE DHCP LEASE GENERATION AND RENEWAL PROCESS
Workstations lease their IP address configurations from a DHCP server. The process consists of
four steps, initiated by the clients will be required to renew their leases. The renewal process
provides an opportunity to update the clients if there have been network configuration
changes.

The lease typically includes the IP address for the client, the associated subnet mask, the IP
address of the default gateway (router), the IP address of one or more DNS servers, and the
length of time the lease is valid. There are additional options that may be configured as well.

Periodically, DHCP clients must renew their leased IP address configuration. If the DHCP server
detects that the client has out-of-date information, it will force the client to lease a new
configuration. If there have been no changes, the renewal will succeed. The lease renewal
process is steps three and four of the initial lease generation process.

Linux LPIC-1 697


THE /etc/dhcp/dhclient.conf FILE
The primary DHCP client reference file is the /etc/dhcp/dhclient.conf file. This file enables the
configuration of DHCP client settings, including timeout values, dynamic DNS configurations,
etc. The file is called and managed by NetworkManager, which serves as a network
configuration service for multiple network settings, including the DHCP client configuration. It is
typically appropriate to manage DHCP client configurations by using NetworkManager rather
than editing the /etc/dhcp/ dhclient.conf file directly.

Linux LPIC-1 698


NAME RESOLUTION
TCP/IP data packets must include a source IP address and a destination IP address. Humans
have a very difficult time remembering long strings of numbers. For example, imagine if every
website you have bookmarked or every email address you have in your contacts information
was noted for you as an IP address instead of a name!
Humans work with easy to remember names, such as www.redhat.com or www.ubuntu.com.
Such information is virtually useless to computers, which need the IP address information in
order to properly find the resource. Names are a description, whereas addresses are a location.

Name resolution is the process of relating these easy-to-remember names with difficult-to-
remember IP addresses. There are two general ways in which name resolution works. The first
is via static text files such as the /etc/hosts file. The second method is via a dynamic database
called Domain Name System (DNS).

TESTING NAME RESOLUTION


Various tools can be used to test name resolution, including the host and nslookup commands.

Linux LPIC-1 699


The name resolution process using a DNS server.

Linux LPIC-1 700


THE /etc/hosts FILE
Early network environments were relatively small and the identities of network nodes did not
change frequently. Name resolution could be managed by using a text file, stored locally on
each system, that contained all the systems and their related IP addresses. This file would have
to be manually updated if there were any name or IP address changes, additions, or deletions.
In today's modern, transient networks, this method is not realistic. The number of entries in the
file and the frequent changes to the identity entries would be overwhelming.

The /etc/hosts file is still important, however, because it can be used in special case situations
where a particular system—perhaps a developer's workstation—needs to connect to an
experimental server that is not registered on the network. While
the /etc/hosts file is not commonly used, it is essential in certain scenarios.

Linux LPIC-1 701


Configuring name resolution locally.

Linux LPIC-1 702


THE /etc/resolv.conf FILE
Modern networks use a name resolution service like DNS to relate computer names and IP
addresses. Network devices will query a DNS server in order to resolve a name and IP address
relationship. The DNS server contains resource records that will provide answers to the query.
DNS servers are centralized and much easier to maintain and keep current than /etc/hosts files
are.
The /etc/resolv.conf file is stored locally on each system, informing that system of the IP
address of one or more DNS servers. DNS is an essential service, so it is a good practice to have
at least two DNS servers listed in the /etc/resolv.conf file.

Linux LPIC-1 703


Configuring name resolution using public DNS servers.

Linux LPIC-1 704


THE /etc/nsswitch.conf FILE
The /etc/nsswitch.conf file includes several configuration options. The option related to name
resolution defines the order in which name resolution methods will be used by the system. The
order may be the /etc/hosts file first, then DNS; or DNS first, then the /etc/hosts file. The
preferred configuration is /etc/hosts then DNS.

Linux LPIC-1 705


The /etc/nsswitch.conf file.

Linux LPIC-1 706


DNS CONFIGURATION USING NetworkManager
DNS configurations can also be set using NetworkManager. NetworkManager includes
command-line, text-based, and graphical interface utilities. In all three utilities, it is essential to
configure the IP address of at least one DNS server.

Linux LPIC-1 707


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 708


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 709


Linux LPIC-1 710
CLOUD COMPUTING
A relatively new and rapidly changing aspect of IT is the growth of cloud computing. There are
many examples and uses of cloud computing. According to the National Institute of Standards
and Technology (NIST), there are five essential characteristics of cloud computing:
• On-demand self-service
• Broad network access
• Resource pooling
• Rapid elasticity
• Measured service
These five concepts combine together to form one of the most important aspects of today's IT
industry. Cloud computing has become a mission-critical service for many businesses, large and
small alike. At its most fundamental, you might think of cloud computing as a method of off-
loading responsibility. That responsibility might be for the cost, ownership, and maintenance of
the network and server infrastructure, or responsibility for the development environment, or
responsibility for operating system and application support.
Cloud services are characterized by flexibility of deployment, scale, support, and fault
tolerance. Businesses are able to rapidly expand their resources on demand, and only pay for
the resources that are actually consumed. Subscription-based payment provides greater
financial flexibility and control. In a traditional infrastructure, where network and server
components are purchased by the organization, resources may go unused for long periods of
time or not be able to grow quickly enough to support business agility.

Linux LPIC-1 711


CLOUD MODELS
There are three primary models of cloud computing, with many variations of each.

Model Description
SaaS provides applications to end-users. The applications are not
installed directly on the user workstation, although to the user it seems
Software as a
as though the application is local. Deployment, maintenance, upgrades,
Service (SaaS)
and security patches are off-loaded to the cloud service provider. This
area of cloud computing typically provides service to all end-users.
PaaS includes virtualization of the operating system layer of the
environment. The development or database platform is supported by the
Platform as a cloud service provider and given to the customer in a ready-to-use
Service (PaaS) manner. Support for the platform is off-loaded to the cloud service
provider. This area of cloud computing typically provides service to
developers and database administrators.
In IaaS, the physical devices (servers, switches, routers, etc.) are
virtualized and owned by the cloud service provider. Responsibility for
Infrastructure as a
the hardware lifecycle is off- loaded to the cloud service provider. This
Service (IaaS)
area of cloud computing typically provides service to systems
administrators.

Linux LPIC-1 712


PUBLIC, PRIVATE, AND HYBRID CLOUDS
Cloud services can be provided with different structures. Public clouds refer to
hardware resources that are owned by the cloud service provider, and customer
resources, compute functions, storage, etc., may be shared among multiple
customers. Laws, industry regulations, and company security policies may not permit
all companies to use such shared resources. Private clouds refer to the use of cloud
technologies as an on-premise solution. Private clouds often satisfy security
requirements, enable a company to retain a great deal of control over exactly where
their data resides at any given moment, and may provide easier management. Private
clouds do require that the company continue to own the hardware lifecycle,
application support, etc. Hybrid clouds are a combination of the other two concepts,
enabling more effective cost management combined with strict security
management.

Linux LPIC-1 712


CLOUD SERVICE PROVIDERS
Many cloud service providers (CSPs) exist, but Amazon and Microsoft cloud solutions are the
two primary providers in the cloud industry. Amazon Web Services (AWSTM) supports a great
many deployment options. AWS is built on a Linux solution. Microsoft® Azure® also supports a
great many deployment options. Azure supports the deployment of Linux-based solutions, not
just Windows solutions.

Red Hat® Cloud Suite is another CSP. Red Hat's solution is a Linux-based, full-featured private
cloud.

Although AWS and Microsoft Azure are considered the industry leaders in cloud services, there
are a great many additional CSPs. Many provide specialized services for particular parts of the
cloud market. Here are a few additional CSPs for you to investigate:
• Google Cloud™: Supports a very wide variety of services, including compute, storage,
database, IoT, development tools, etc.
• Rackspace: Services include compute, database, business continuity, and data center
management.
• Heroku™: Provides PaaS options for application development.
• Digital Ocean™: A PaaS cloud provider that provides scalability and management.

Linux LPIC-1 713


CLOUD AND VIRTUALIZATION
Virtualization enables significantly more efficient use of hardware, plus many additional options
for fault tolerance, disaster recovery, and scalability. It also allows for much quicker deployment
of servers and services. It is for these reasons that virtualization is the foundation of cloud
computing. Cloud providers virtualize the resources they make available to customers to make
management of those resources easier.

This virtualization extends to every model: SaaS, PaaS, and IaaS. For example, an administrator
can easily build and later tear down an entire cluster of systems with a single action, or even
automate this process in response to changes in the environment. It would be much less
efficient if the administrator had to do all of this on physical systems, so virtualization is
essential.

Linux LPIC-1 714


HYPERVISORS
The hypervisor software layer provides control between the virtual machines and the physical
hardware. It manages allocation of hardware, control of networking, administrative control, etc.
There are two types of hypervisors: Type 1 runs directly on the hardware in a "bare metal"
deployment. Examples include VMware ESXi and Microsoft Hyper-V. Type 2 runs as a service on
a locally installed operating system. Examples include Oracle VM VirtualBox and QEMU.

Kernel-Based Virtual Machine (KVM) is a Linux-based virtualization solution that can be added
to most Linux distributions. It enables the management of virtual machines on Linux platforms
with attributes of both type 1 and type 2 virtualization.

Linux LPIC-1 715


The architecture of a type 1 hypervisor.

Linux LPIC-1 716


TEMPLATES
Virtual machine templates can make deployments much more efficient. Administrators and
users can deploy servers themselves in a self-service environment using pre- defined templates
that specify different processor, memory, storage, and network configurations.
There are different templates that can be used to make deployments easier.

Template Description
• Contains config files, packages, etc. for VMs and network
OVF devices.
• OVA is a single package for a network appliance.
• Easily interpreted by programming languages.
JSON • Easy for humans to write and read.
• Used in quick deployment/config of VMs.
• Stores config info used to deploy VMs.
YAML • Can install software/create user accounts on first boot.
• Consists of key–value pairs.
• Provides app isolation, different than VMs.
Container images • Used for testing apps.
• Images contain everything needed to run container.

Linux LPIC-1 717


BOOTSTRAPPING
The term bootstrapping refers to the startup of the operating system. It refers to the adage
"pulling yourself up by the bootstraps," meaning that the operating system starts with simple
layers that move toward more complex functionality. With virtual machines, the bootstrapping
steps are handled by the virtualization layer. It is possible to modify the startup and the
deployment of virtual machines during the bootstrapping sequences. Three ways of managing
bootstrapping include cloud-init, Anaconda, and Kickstart.

Cloud-init is a cloud-based Linux mechanism to customize a virtual machine during its first
bootup. This customization might include security settings, software package installations, user
and group creation, etc. Cloud-init references YAML files to find the necessary settings. Cloud-
init is supported by many distributions, including Ubuntu® Server 18 and Red Hat® Enterprise
Linux® (RHEL) 7.

Many Linux distributions use the Anaconda installer to manage their deployments. This installer
can provide prompts to an administrator to configure the new Linux server, or it can reference
files to customize the installation. Linux uses Kickstart files to customize the installation,
providing an unattended install. All information about partitions, packages, user accounts,
software deployments, etc., are contained in the Kickstart file. The combination of Anaconda
and Kickstart enables rapid, consistent, and customized Linux installations.

Linux LPIC-1 718


STORAGE
With traditional physical computers, storage capacity is provided as physical space. This space is
usually one or more storage drives. With virtualization, storage capacity may be exposed to the
virtual machines as virtual storage drives. The virtual storage drive is a file that resides on the
physical drive, much like any other data file. That file is treated as if it were a physical drive. It is
partitioned and given a file system, a boot loader is installed, and an operating system is
deployed. While from the administrator's perspective the virtual drive is just a file, from the
virtual machine's perspective, it's a physical device.

Because virtual drives are just files, they may provide more opportunity for fault tolerance,
simpler rollback of a system's status, redundancy, and storage scalability as compared to a
traditional physical drive.

THIN VS. THICK PROVISIONING


When deploying virtual machines, you may be offered the option of configuring thin storage or
thick storage. Thin storage refers to a virtual storage device file that will grow on demand up to
a maximum size. This may make for more efficient use of drive space, but it may also include a
performance hit. Thick provisioning of a virtual storage device immediately reserves the
allocated space for use by the virtual device only, regardless of whether that much capacity is
actually needed. Performance is better, but it may consume more drive space than it needs.
Thin provisioning is most appropriate in environments where the cost of maintaining large
storage pools is much more of a concern than the risk of temporarily running out of storage.

Linux LPIC-1 719


Likewise, thick provisioning is most appropriate in environments where disruptions to
the continuous storage process present an intolerable risk, more so than the expense
of unused storage.

PERSISTENT VOLUMES
Some organizations will manage container virtualization with Kubernetes. Kubernetes
provides an orchestration solution for container management. As part of that
orchestration, persistent volumes are created. When used in conjunction with a Linux
cluster, they keep the storage configuration separate from the configurations of the
individual cluster nodes. This makes it easier for nodes to be replaced through their
lifecycle without impacting the storage.

Linux LPIC-1 719


BLOB AND BLOCK STORAGE
Data may be stored in multiple ways. One way is to use traditional SQL databases, like
MariaDB® or MySQL™. It is also possible to store data in an unstructured manner, which is
referred to as a blob. Blob stands for binary large object. Audio, video, and other multimedia
files—as well as text files—may be stored in this manner. This is an example of object storage.
Data itself is written to the storage device (whether physical or virtual) in small chunks called
blocks. These blocks are the fundamental storage areas of the drive. Most files are too large to
be stored in a single block, so the files are broken into pieces that are then written to the
blocks. Data is reassembled when called by the operating system.

Object storage may be more efficient than block storage, especially for larger files. It may also
be more flexible when storing data in multiple geographical regions.

Linux LPIC-1 720


NETWORKING CONFIGURATIONS
The virtualization hypervisor can be configured to provide access to networking services in
several ways. The virtual machine can be configured with one or more virtual NICs. The virtual
NICs can then be connected to virtual switches within the hypervisor. Those virtual switches
may then be given access to the host computer's physical NICs.
Some network configuration options include:
• No networking: Simulates a computer that does not include a NIC at all.
• Internal: The VM is connected to a virtual switch that permits network
• communication with other virtual machines, but not network communication with the host
operating system or the physical NIC.
• Private: The VM is connected to a virtual switch that permits network communication with
other virtual machines and with the host operating system, but no network connectivity to
the physical NIC.
• Public: The VM is connected to a virtual switch that permits network communication with
other virtual machines, the host operating system, and the physical NIC. This configuration
exposes the VM to the business network, where it can participate as if it were a regular
client or server.

Network configuration for virtual machines must be carefully managed, because VMs
frequently are configured as production servers to which end-users need access. Once network
connectivity is provided, it is essential to follow best practices for securing network-connected
nodes. The fact that the network node is a virtual machine does not prevent it from needing
protection from network threats.

Linux LPIC-1 721


ADDITIONAL NETWORKING CONSIDERATIONS
Networking in virtualized environments is as flexible as it is in physical environments.
Services such as Network Address Translation (NAT) provide the same functionality. In
the case of NAT, that's to translate between the reserved, private IP address ranges
and the public, Internet address ranges. These virtualized networks may be thought
of as "overlay networks," especially when deployed in a cloud environment. The term
overlay network simply means one network built over the top of another. Virtualized
network environments also support bridging, which connects two networks into a
single managed unit.

Virtualization supports the use of multiple NICs in virtual machines as well. If the NICs
are connected to different network segments, the server is referred to as being "dual-
homed."
Blob and Block Storage

Linux LPIC-1 721


VIRTUALIZATION TOOLS
Virtualization Tools
Many virtualization host servers will run Linux without a graphical user interface. Such a
configuration enables more hardware resources to be available to the virtual machines.
Management of the virtual machines must then occur at the command-line.
The virsh command is an interactive shell to KVM virtual machines. The following are some
subcommands you can use within virsh.

Subcommand Used To
help Get help with virsh command.
list Get list of recognized VMs.
shutdown {VM} Gracefully shut down VM.
start {VM} Start VM.
reboot {VM} Reboot VM.
create {XML file name} Create VM from XML file.
save {VM} {file name} Save the state of a VM with the given file name.
console {VM} Open console to VM.

Linux LPIC-1 722


libvirt
Linux virtualization solutions are built on top of libvirt, an application programming
interface (API) that provides the software building blocks for developers to write their
own virtualization solutions. Solutions can also be composed of a daemon and a
management interface. Several hypervisors, including VMware ESXi, KVM, QEMU,
etc., are all built using libvirt. It provides a solid foundation for Linux-based
virtualization. For example, the virsh tool is a part of the libvirt API.

GNOME VMM
The GNOME Virtual Machine Manager (VMM) utility can be used for managing
connectivity to virtual machines. It enables the deployment, management, and
removal of virtual machines using an intuitive graphical interface. Download and
install the virt-manager package to begin using VMM.

Linux LPIC-1 722


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 723


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 724


Linux LPIC-1 725
COMMON NETWORKING ISSUES
Network troubleshooting begins with a series of general steps before moving to more complex
techniques.

First, check the basics: Is the device powered on? Is the device plugged in? Are the cables
properly connected to the correct network devices (switches, routers, etc.) and the hosts
themselves? Also, remember that NICs can be in an "up" or a "down" state. Verify that they are
available. Next, verify that the network interfaces are configured correctly. They need to have
an appropriate IP address configuration, subnet mask, default gateway value, and name
resolution settings. Also check that the network interface is detected by Linux and use the
ethtool command to gather driver and other information about the device.

You can troubleshoot name resolution issues using several different techniques. The first is to
ping a destination by both hostname and then by IP address. If the hostname-based ping fails,
but the IP address-based ping succeeds, then the system is not properly resolving network
names. At that point, you can use tools like host and nslookup to further test name resolution.

The network itself may also be experiencing issues. These issues might include very high traffic,
causing latency and saturation issues at various points within the network. If a router is
misconfigured or down, then the optimal path may not be found between two systems, or no
path may be found at all. Network interface cards that are failing could cause data packets to be
dropped on the network, causing a loss in data, timeout messages, or reduced network

Linux LPIC-1 726


throughput. You may need to escalate these problems to the network team at your
organization.

APPLICATION PERFORMANCE TROUBLESHOOTING


When troubleshooting application performance, developers may need to choose how
communication with a service occurs. One method, localhost, creates a full network
connection, including all TCP error checking, etc. This method may be significantly
slower. The alternative design for developers is Unix sockets (or Unix domain
sockets). This approach will often provide a performance increase by removing the
TCP overhead from the transaction. The overhead isn't needed because the
connection is entirely local.

NETWORK ADAPTER TROUBLESHOOTING


As you know, network adapters, also called network interface cards (NICs), provide
physical connectivity to the network. These cards will typically have an RJ-45
connector. They may be found integrated on the motherboard or added to the board
via an expansion slot. Network cards require the appropriate driver to be installed so
that Linux can take advantage of their features.
Some NICs support remote direct memory access (RDMA) interfaces, which are
specialized hardware components implemented on very low-latency, high-speed
networks to provide a significant performance increase. Support for RDMA is
provided through a kernel module, so you will have to check the kernel on your
server to see if the module is already loaded. In addition, you will need to provide a
driver for the RMDA device if the kernel does not already contain one.

Linux LPIC-1 726


THE ping COMMAND
One of the earliest parts of network troubleshooting is sending test packets between two
systems. This is done using a TCP/IP utility called ping. The ping command will generate a
response request from the sending computer and should receive a reply from the destination
computer.

Possible outcomes of the ping command include:


• Reply from <host>: The connection was successful.
• Destination unreachable: The source computer cannot find a path to the destination. This
often indicates the problem is with the source computer.
• Timeout: The request reached the destination computer but a response did not return to
the source computer before the source computer timed out. This often indicates the
problem is with the destination computer.
Although using ping is one of the earliest steps in the network troubleshooting process, it only
tells you that something is wrong—not what is wrong.

SYNTAX
The syntax of the ping command is ping [options] {destination}
The {destination} can be an IP address, such as 192.168.1.1, or it can be a hostname, such as
server01

Linux LPIC-1 727


ping COMMAND OPTIONS
Some common ping command options include:
-c —only send a specified number of pinging attempts. By default, Linux sends a
continuous ping until interrupted with Ctrl+C.
-v —specify verbose output.

SEQUENCE NUMBER
The ping command also provides a sequence number (icmp_seq) for each ping
attempt. The host sending the ping can use this number to match each request with
its response. Mismatched sequence numbers might indicate a dropped packet.

Linux LPIC-1 727


The possible results of pinging across a network.

Linux LPIC-1 728


THE traceroute AND tracepath COMMANDS
The traceroute command is used to report the network path between the source and
destination computers, including any routers the connection uses. The process of a packet
traveling from one router to the next is called a hop. The traceroute command therefore
outputs each hop along the path. This is particularly effective when troubleshooting Internet
connectivity or connections within very large routed environments. If the traceroute fails, being
able to identify where along the path it failed is useful for troubleshooting.

The tracepath command is a simplified version of traceroute that does not require
administrative privileges to run. It also contains fewer options.

SYNTAX
The syntax of the traceroute and tracepath commands is traceroute/ tracepath [options]
{destination}

ROUTING ISSUES
Many routing issues are the result of misconfigured routing tables. These issues can usually be
fixed by updating the routing tables. However, you must first identify what is causing the issue.
Commands like traceroute and tracepath can reveal routing issues like routing loops, in which
traffic is continuously routed back and forth between multiple nodes and never reaches its
destination. For example, node A uses node B as a path to node C; but node B uses node A as a
path to C. If traffic is bound for node C, nodes A and B will endlessly send the traffic between
them because they both think each other is the path to C.

Linux LPIC-1 729


Following the route between two network hosts.

Linux LPIC-1 730


THE netstat COMMAND
The netstat (network statistics) command is used to gather information about TCP connections
to the system. Depending on the options used, netstat informs the user of existing connections,
listening ports on the server, NIC information, etc.
Common options for the netstat command include:

Option Used To

-v Activate verbose mode.

-i [interface] Display info about all network interfaces or interface specified.

-c Continuously print information every second.

-l Show only what ports are being listened on.

The netstat command has been deprecated in favor of the ss command, but it may still be
installed with some Linux distributions.

SYNTAX
The syntax of the netstat command is netstat [options]

Linux LPIC-1 731


OUTPUT
The default output of netstat is in columnar format, as follows:
• The protocol used by the socket.
• The number of processes attached to the socket.
• Flags that give further information about the socket's status.
• The type of socket access.
• The state of the socket.
• The ID of the process attached to the socket
• The path of the process attached to the socket.

An example is as follows:
unix 2 [ ] STREAM CONNECTED 472 /run/dbus/system_bus_socket

Linux LPIC-1 731


THE ss COMMAND
The ss (socket state) command is an information gathering utility similar to netstat but provides
simpler output and syntax. The ss tool can provide information about established TCP
connections or which ports the system may be listening on for inbound connections. This can
help you diagnose problems related to clients and servers being unable to communicate with
one another over the desired protocol; a missing socket could mean that the service isn't
running, and a closed socket could mean that either the client or the server is prematurely
terminating the connection. Another way to use ss is to gather information about a particular
client that may be connected.

SYNTAX
The syntax of the ss command is ss [options]

Common options for the ss command include the following.

Option Used To

-l Show currently listening sockets.

Show whether the specified host is connected and what the


dst {host}
connection statistics are.

-i Show only what ports are being listened on.

Linux LPIC-1 732


Displaying listening sockets related to SSH.

Linux LPIC-1 733


THE dig, nslookup, AND host COMMANDS
One of the most important network services is name resolution. If systems are not able to
reach or use DNS name resolution servers, they are not likely to be able to access the needed
network services.
Three different tools can be used to test and troubleshoot name resolution. These tools should
be used after it has been confirmed that the system is configured with the proper IP address of
one or more DNS servers (use cat /etc/resolv.conf to verify) and after using ping to test
connectivity to the DNS server.

Command Description

• Outputs IP address mapped to domain, answering DNS server, and


dig time taken to receive answer.
• Example: dig @{IP address} {domain name}
• Has interactive and non-interactive mode.
nslookup
• Example: nslookup {domain name}
• Simple tool.
host
• Example: host {domain name} {IP address}

Linux LPIC-1 734


THE ip COMMAND FOR TROUBLESHOOTING
The ip command can be used for troubleshooting as well as for network configuration. The first
step in troubleshooting network connectivity is to verify all settings are correct. The ip addr
command enables an administrator to ensure the configuration is accurate.

Examples of troubleshooting with ip addr include:

• Check the IP address configuration: If the ip addr command reports back an address in the
link-local range, then the NIC is not configured with a legitimate IP address. The link-local
range is 169.254.#.#. If the system is a DHCP client, then verify connectivity to the DHCP
server.
• Check the status of the NIC: The ip command can be used to "up" or "down" a NIC (enable
or disable it). If the NIC shows as down, it is disabled and not functional.
• Check the usage statistics of a NIC: Using ip with the -s option enables you to view
connectivity statistics for the connection.

Linux LPIC-1 735


THE route COMMAND
It is possible to configure a Linux system to act as a router. The role of a router is to pass traffic
from one network segment to another, based on the network ID of packets. In order to
properly direct traffic to the appropriate subnet (and prevent traffic from getting to certain
subnets, too), routing table entries are configured. This is not a common configuration for Linux
hosts, but is important to be aware of.
The route command is used to view the routing table. The command is also used to manipulate
the routing table, enabling the administrator to configure desired routes.
Examples include the following.

Command Used To
route View the current routing table on the system.
Configure a default gateway by its IP address. Packets
route add default gw {IP address} will be passed to this destination if there are no other
routes that match their network ID.
Filter traffic destined to the specified address, which
enables an administrator to control connections to a
route add –host {IP address} reject
particular host. Can also be configured for an entire
subnet.

SYNTAX
The syntax of the route command is route [options]

Linux LPIC-1 736


Displaying the routing table.

Linux LPIC-1 737


THE nmap COMMAND
Network Mapper, or nmap, is a powerful tool for exploring a network environment. It identifies
nodes and is often able to report back available services, operating system versions,
hostnames, IP addresses, MAC addresses, network devices (switches, routers), network
printers, etc. The nmap utility has a great many options. It also has a GUI version called
Zenmap.
The nmap utility may be used initially to audit and document the network. In troubleshooting,
having such documentation is essential. It can also be used directly in the troubleshooting
process to confirm whether expected components are in place or if there have been changes to
the network environment.
The following is an example troubleshooting process:
1. ip addr —does the local host have the correct IP configuration?
2. ping {destination} —is traffic able to flow from the source to the destination and back?
3. nmap —view the network structure to verify the existence of a path between the source
and destination systems.
SYNTAX
The syntax of the nmap command is nmap [options] {target}
TROUBLESHOOTING EXAMPLES
The following are some examples of troubleshooting with nmap:
• nmap -p 1-65535 -sV -sS -T4 {target} —Port scan for all listening ports on the designated
target (hostname, IP address, subnet). This ensures the destination computer is listening for
the source computer's connection attempt.
• nmap -sP 192.168.1.0/24 —Host discovery scan for all devices on the 192.168.1.0/24
subnet. This reports all devices detected on the designated subnet.

Linux LPIC-1 738


Scanning a target host over the network

Linux LPIC-1 739


WIRESHARK
Wireshark is a very common packet sniffer and network analyzer. Network analyzers are used
to intercept and potentially read network traffic. These tools may be used for eavesdropping
attacks, but also for network troubleshooting. When network traffic is intercepted, information
such as source/destination MAC address, source/destination IP address, port numbers, and
packet payload (data) is exposed. One advantage of a tool like Wireshark is the ability to see
exactly what packets are moving through a network segment or NIC and what packets are not.
This is very useful for troubleshooting.
The following is an example troubleshooting process:
1. ip addr —does the local host have the correct IP configuration?
2. ping {destination} —is traffic able to flow from the source to the destination and back?
3. firewall-cmd --list-services —view what traffic may be filtered by the local firewall.
4. Wireshark—identify what network traffic is moving in a given network subnet.

Linux LPIC-1 740


Wireshark capturing network traffic as it flows between two hosts.

Linux LPIC-1 741


THE tcpdump COMMAND
Another network analyzer is the tcpdump utility. Created in 1987, tcpdump remains one of the
most popular packet sniffers available. It is installed by default on many Linux distributions.
Users can determine traffic type and content using this command. It provides similar
information to Wireshark, and you can use it in a similar troubleshooting process.

Linux LPIC-1 742


SYNTAX
The syntax of the tcpdump command is tcpdump [options] [-i {interface}] [host {IP address}]

Some common options with tcpdump are provided in the following table.

Option Used To

-i Specify the interface to use.

-n Not resolve hostnames, speeding up the capture.

-v Specify verbose mode.

Linux LPIC-1 743


THE netcat COMMAND
The netcat command can be used to test connectivity and send data across network
connections. The command may be spelled out as "netcat" or abbreviated as "nc" depending
on the distribution. Systems may be identified by IP address or by hostname.
When troubleshooting, use netcat to listen on the destination computer and attempt a
connection from the source computer in order to verify network functionality.

SYNTAX
The syntax of the netcat command is netcat [options]

The following table provides some example use cases for the netcat command.

Use Case Command Example

Connect two computers to On comp1 (listen on port): netcat -l 4242


transfer data On comp2 (connect to listener): netcat comp1 4242
Transfer files between two On comp1 (listen on port): netcat -l 4242 > received.file
computers On comp2 (connect to listener): netcat comp1 < original.file

Port scan a computer netcat -z -v domain.tld 1-1000

Linux LPIC-1 744


THE iftop COMMAND
The iftop command displays bandwidth usage information for the system, helping to identify
whether a particular NIC or protocol is consuming the most bandwidth. The iftop command
may not be installed on all Linux distributions.

This command can help you identify why a particular link may be slow by showing the traffic on
that connection. You can use it to check to see what is consuming the most bandwidth on an
interface. For example: iftop -i eth0

Network slowness is often a symptom of bandwidth saturation, in which a network link's


capacity is exceeded, i.e., all bandwidth is being used up. This can lead to degraded network
performance or even service outages. With the iftop command, you can investigate any NICs
on a network link that you suspect may be sending or receiving excessive sums of traffic across
that link. For example, one host might be making repeated requests to an internal web server,
and both hosts might be flooding the network with their requests and responses. Once you've
identified the source of the issue, you can then take steps to stop the offending host from
making these requests, such as terminating the service responsible for the requests.

SYNTAX
The syntax of the iftop command is iftop [options] [-i {interface}]

Linux LPIC-1 745


Displaying connection bandwidth statistics.

Linux LPIC-1 746


THE iperf COMMAND
The iperf command is used to test the maximum throughput an interface will support. The
utility must be installed on both endpoint systems. One system is designated as a "server" and
the other as a "client." It is the iperf client that is getting tested. You can use this command to
ensure that throughput is meeting your expectations.

A basic test is as follows:


1. On the server, run iperf -s
2. On the client, run iperf -c {server address}
3. Examine the results that appear.

SYNTAX
The syntax of the iperf command is iperf {-c|-s} [options]

THROUGHPUT VS. BANDWIDTH


Bandwidth is the potential amount of data that may move through a network connection in a
given amount of time. Throughput is the amount of data that actually moves through a
network connection in the given amount of time. Both the iftop and iperf utilities measure
throughput.

Linux LPIC-1 747


Testing network bandwidth between two hosts.

Linux LPIC-1 748


THE mtr COMMAND
The mtr utility is a combination of ping and traceroute, with additional improvements to enable
testing of the quality of a network connection. Ping packets are sent to the destination in large
groups, with mtr noting how long responses take to the packets.

The mtr command also takes note of lost packets, a symptom of a problem called packet drop
or packet loss. This occurs when one or more packets sent from a source are unable to reach
their intended destination. Packet loss can cause latency if the packets are queued for
retransmission, or the data may not be successfully transmitted at all. A large number of lost
packets are a strong indicator of a network issue along the path. By identifying that the issue
exists, as well as where in the path it exists, mtr enables an administrator to find potentially
failed networking components. The output of mtr identifies the percentage of packets along
the path that are dropped, and one or more nodes in that path experiencing a high percentage
of packet loss may be at fault.

SYNTAX
The syntax of the mtr command is mtr [options] [hostname]

Linux LPIC-1 749


Analyzing connection information to a remote host.

Linux LPIC-1 750


THE arp COMMAND
As you know, nodes on the network typically have three identities: hostname, IP addresses, and
MAC addresses. DNS translates hostnames to IP addresses. The Address Resolution Protocol
(ARP) is used to relate IP addresses and MAC addresses. There is also an arp command that
administrators can run to discover information about known MAC addresses.

Computers will cache recently resolved MAC and IP address combinations. If a computer has
cached incorrect or out-of-date information, connectivity may be lost to a particular node. The
ARP cache can be cleared as part of the troubleshooting process.

For example, you can run arp -d {IP address} to a clear entry for a particular IP address, and
then try to ping the host again. Use arp -a to view the cache.

SYNTAX
The syntax of the arp command is arp [options]

Linux LPIC-1 751


The ARP cache.

Linux LPIC-1 752


THE whois COMMAND
The whois command provides information on Internet DNS registrations for organizations. This
can be useful for learning or verifying information regarding ownership of a domain name,
contact information for an organization, etc.

Some examples include:


• whois google.com
• whois ubuntu.com
• whois redhat.com

SYNTAX
The syntax of the whois command is whois [options] {domain name}

Linux LPIC-1 753


GUIDELINES FOR TROUBLESHOOTING NETWORKING ISSUES
Use the following guidelines when troubleshooting networking issues.
TROUBLESHOOT NETWORKING ISSUES
When troubleshooting networking issues:
• Narrow the scope of the problem—if the issue occurs on one machine, it's likely a
misconfiguration on that machine. If the issue occurs on several machines, it could be a
network problem. If several nodes are affected, check to see what they have in common. Are
they all connected to the same switch or wireless access point? Are they all in the same
subnet?
• Verify the IP address configuration on the system using the ip command. If the system has an
IP address beginning with 169.254.x.x, then it failed to lease an IP address configuration
from a DHCP server, which gives you a place to start.
v Attempt to renew the dynamic IP address configuration from a DHCP server.
v Verify there are no typographical errors if the IP address configuration is static.
• Use the following tools and processes to diagnose bandwidth issues when experiencing slow
network performance:
v Continuously ping affected hosts to confirm that a connection between hosts is slow.
v Use traceroute to identify where along a routing path the network bottleneck might
be occurring.
v Use iftop on affected or suspected hosts to identify what applications are consuming
bandwidth. Some applications, like streaming media, can consume a great deal of
bandwidth if left unchecked.

Linux LPIC-1 754


• Use iperf to test network interface throughput if a connection is slow, but
bandwidth is not the issue. The interface may itself be unable to handle the
desired speeds and require an upgrade or replacement.
• Utilize these general commands:
v Use the ping command to test connectivity.
v Use the traceroute command to understand the network between two
endpoints.
v Use the nslookup and host commands to test name resolution.
v Use the ethtool command to verify the network card driver and
configuration information.
v Use the virsh subcommands to verify and manage KVM virtual machines.
v Use the iperf tool to test throughput between two endpoints.

Linux LPIC-1 754


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 755


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 756


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 757


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 758


Unlike in other operating systems, software is provided to Linux® systems in multiple different
ways. You need be able to acquire and manage software packages in order to install the
necessary applications and keep them updated. Since packaged software is typically delivered
over a network like the Internet, it'll be easier for you to manage those packages now that
you've configured networking on your Linux systems.

Linux LPIC-1 759


In this topic, you will:

• Identify the most common package managers in Linux, including RPM and dpkg.
• Manage RPM packages with the YUM front-end.
• Manage Debian packages with the APT front-end.
• Configure package repositories.
• Acquire software through means other than package managers.
• Compile software packages that are in source code form.
• Troubleshoot issues with software dependencies.

Linux LPIC-1 760


Linux LPIC-1 761
There are multiple utilities that enable you to manage packages on your Linux systems. In this
topic, you'll explore the major package managers that are available.

PACKAGE MANAGERS
Linux distributions rely on two different methods of managing the software lifecycle. The first
method is package managers—programs that install, update, inventory, and uninstall packaged
software. The second method is compiling software manually from source code. The open
source nature of Linux means that compiling code is much more common for Linux
administrators than for Windows or macOS users.

Package managers govern the software lifecycle, making it much easier for Linux administrators
to control what software is installed, manage software versions, and to uninstall the software.
The term package refers to a collection of files needed for a particular program. This set of files
includes the pre-compiled application itself, any supporting files it might require, and
supporting documentation. Packages are easy to distribute, verify, and manage via package
managers.

Linux LPIC-1 762


SOFTWARE DEPENDENCIES
Many Linux applications are modular and depend on other pieces of software already being
present. The packages will list dependencies, the required components without which the
application cannot function properly. Package managers will check for these dependencies
before installing the software from the package. A "failed dependency" error indicates that one
or more of these dependencies has not been satisfied.

Linux LPIC-1 763


RED HAT INSTALLATION VS. DEBIAN INSTALLATION VS. COMPILING
There are two dominant methods for managing software packages. The first method, created
by Red Hat® in 1995, is called the Red Hat Package Manager (RPM). The second method,
created in 1994, is the Debian dpkg system. The two managers are significantly different from
each other but functionally provide the same end result. As a Linux user, your choice will
usually be driven by your preferred Linux distribution. The vast majority of Linux distributions
trace their origins back to either Red Hat Linux or Debian Linux.

An alternative to using package managers is to compile the software yourself. This is the
traditional method of managing software. It has advantages and disadvantages. Windows® and
macOS® users don't typically consider compiling software, because most of the software
available is closed source, and therefore is only available in a pre- compiled format. Because
Linux relies on open source software, access to the source code is much more common. Users
can make changes to the source code, enabling or disabling options, customizing installation
choices, and even expanding the functionality of the software before compiling the code on
their systems.

Manually compiling software requires more effort and more knowledge, but it can result in a
more useful piece of software.

Linux LPIC-1 764


DISTRIBUTION ORIGINS
The following table lists the origins of several common Linux distributions.

Red Hat Linux (1995) Debian Linux (1993)

Red Hat® Enterprise Linux® (RHEL) Debian


CentOS® Ubuntu®
Fedora® Linux Mint
Scientific Linux Kali Linux
VMware ESXi™ Raspbian
Amazon™ Linux SteamOS
Oracle® Linux openSUSE

Linux LPIC-1 765


RED HAT PACKAGE MANAGERS
Red Hat's package manager is called RPM. It is still in use today by many administrators.
Software packages that are prepared for RPM use the .rpm file extension. RPM is very flexible
and very powerful. One of its most useful features is the ability to inventory software, enabling
administrators to easily see installed software and software version information.

There is a newer and more advanced package manager that is commonly used by Red Hat
derivatives. This package manager is called the Yellowdog Updater, Modified (YUM). It relies
on RPM and uses .rpm packages. It offers a more elegant set of commands and greater
flexibility for using software repositories and handling dependencies. Today, even Red Hat
prefers YUM to manage the software lifecycle.

Linux LPIC-1 766


DEBIAN PACKAGE MANAGERS
Debian's package manager is called dpkg. It is still available for use in Debian and Debian-
derivatives. The dpkg manager can control the entire software lifecycle. Software packages with
the .deb file extension can be managed using dpkg.

The preferred method of package management in Debian-derivatives today is the Advanced


Package Tool (APT). It is more flexible than the original dpkg package manager. It also relies on
.deb packages. Most software management tasks on Debian- derived distributions will use APT.

Linux LPIC-1 767


DNF AND ZYPPER
The Dandified YUM (DNF) package manager is an improved version of YUM. It uses fewer
resources while still maintaining support for the fundamental RPM package manager. It
includes a simplified set of commands as compared to YUM. Most of the YUM subcommands
are used by DNF, so it will be relatively familiar to those used to using YUM.

Zypper is a package manager that supports repositories, dependency solving, and management
of the software lifecycle. Zypper is an openSUSE package manager that supports .rpm packages.
It is very efficient and does an excellent job of managing package dependencies.

DNF SYNTAX
The syntax to install a DNF package is dnf install {package name}
The syntax to uninstall a DNF package is dnf remove {package name}

ZYPPER SYNTAX
The syntax to install a Zypper package is zypper in {package name}
The syntax to uninstall a Zypper package is zypper rm {package name}

Linux LPIC-1 768


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 769


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 770


Linux LPIC-1 771
Because RPM packages are central to Red Hat, one of the most prominent distribution families,
you'll use several tools to manage those types of packages.

THE rpm COMMAND


The rpm command is used to manage RPM packages on Red Hat-derived distributions. It
includes many different options, some of which are described in the following table.

Option Used To

-i {package name} Install the specified software.

-e {package name} Erase (uninstall) the package.

-v Enable verbose mode, providing more detail.

-h Print hash marks as a progress bar.

-V {package name} Verify software components of package exist.

SYNTAX
The syntax of the rpm command is rpm [options] [package name]

Linux LPIC-1 772


Verifying the software components of a package.

Linux LPIC-1 773


RPM QUERYING
One of the most powerful features of the RPM package manager is the ability to maintain a
database of software information. This database enables administrators to discover package
version information, list all installed software, discover dependency information, etc.
Example command queries include the following.

Command Used To

rpm -qa List all installed software (typically a very large output).

rpm -qi {package name} List information about a particular package.

rpm -qc {package name} List the configuration files for a particular package.

Linux LPIC-1 774


Querying information about a package.

Linux LPIC-1 775


RPM VERIFICATION
RPM can be used to verify software. The verification will check to see if the installed software
components match what the RPM package specifies should be installed. The verify option is
used when troubleshooting installed software to ensure that the entire software package is
installed and valid.

Linux LPIC-1 776


RPM UPGRADES
Part of the software lifecycle is to keep software current. RPM offers two primary ways of
accomplishing this goal:
• -U —upgrades the installed package, and installs the package if it is not already installed.
• -F —freshens the installed package, i.e., upgrades but does not install the package if it is not
already installed.

Linux LPIC-1 777


THE yum COMMAND
The yum command improves on the functionality of rpm while still using .rpm packages and
maintaining an RPM database. It provides a more straightforward method for managing
packages.
One of the biggest benefits of YUM is the ability to automatically handle software
dependencies. This means that administrators can tell YUM to install a particular package,
along with automatically installing any additional packages that package depends on.
An additional YUM benefit is the use of repositories. Repositories are storage locations for .rpm
files. Repositories enable administrators to more easily maintain version control over software.

SYNTAX
The syntax of the yum command is yum [options] [subcommand] [package name]

THE -y OPTION
Use the -y option with the yum command to automatically answer yes to installing additional
software dependencies. If you do not, YUM will prompt you to answer yes or no to whether the
additional dependencies should be installed.

Linux LPIC-1 778


Installing a software package using YUM.

Linux LPIC-1 779


yum SUBCOMMANDS
The yum command comes with several subcommands for managing packages.

Subcommand Used To

install {package name} Install the package from any configured repository.

localinstall {package name} Install package from local repository.

remove {package name} Uninstall the package.

Update the package; if none provided, updates all installed


update [package name]
packages (time-consuming).

info {package name} Report information about the package.

provides {file name} Report what package provides the specified files or libraries.

Linux LPIC-1 780


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 781


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 782


Linux LPIC-1 783
The other prominent distribution family with its own package manager is Debian. In this topic,
you'll use various tools to manage Debian packages.
THE dpkg COMMAND
The dpkg command is used to manage packages on Debian-derived distributions. It includes
many different options, some of which are described in the following table.

Option Used To

-i {package name} Install the package.

-r {package name} Remove (uninstall) the package.

List information about the specified package; if none provided, list all
-l [package name]
installed packages.

-s {package name} Report whether the package is installed.


SYNTAX
The syntax of the dpkg command is dpkg [options] [package name]

DEBIAN PACKAGE VERIFICATION


The -i installation option with the dpkg command repairs a software installation by ensuring all
necessary components are installed.

Linux LPIC-1 784


THE apt COMMAND
Although dpkg is the original installer for Debian-derived distributions, today .deb packages are
more commonly managed using APT. APT is a front-end manager to the dpkg system, much like
YUM is a front-end manager to the RPM system.

Until recently, the common software management tools were implemented as a mix of the apt-
get and the apt-cache commands, along with several other variations on the apt-* format.
Many Debian-derived distributions now use the more streamlined package manager simply
named apt

SYNTAX
The syntax of the apt command is apt [options] [subcommand] [package name]

THE apt-get AND apt-cache COMMANDS


The apt-get and apt-cache commands are still functional, as they provide lower-level
functionality and more specific controls than the apt command does, but they may be more
confusing due to their large number of options and less organized command structure.

Most of the subcommands mentioned previously with apt have the same effect with the apt-
get command. You can use apt-cache show {package name} to display package information.

Linux LPIC-1 785


apt SUBCOMMANDS
The apt command comes with several subcommands for managing packages.

Subcommand Used To
install {package name} Install the package.
remove {package name} Uninstall the package, leaving behind its configuration files.
purge {package name} Uninstall the package and remove its configuration files.
show {package name} Report information about the package.
version {package name} Display version information about the package.
update Update APT database of available packages.
Upgrade the package, or upgrade all packages if none
upgrade [package name]
provided (time-consuming).

Linux LPIC-1 786


DEBIAN PACKAGE UPGRADES
When using apt or apt-get to manage packages on your Debian-derived distribution, there are
two subcommands that you must understand. The first is update and the second is upgrade.

The apt update command updates the APT database of available packages, enabling APT to
become aware of new versions of software available in the repositories. This does not install
any software. The apt upgrade command upgrades all installed software based on newer
versions of the packages as seen by the APT database. This is a full upgrade of all software, and
as such can be time-consuming. The apt upgrade {package name} command upgrades the
specified package based on a newer version of the package as seen by the APT database.

It is important to run the apt update command first, and then run the apt upgrade command. If
the apt update command is not run first, the database will not be aware of newer packages.

Linux LPIC-1 787


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 788


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 789


Linux LPIC-1 790
You'll likely acquire most of your software packages from repositories. You may even set up
repositories yourself to deliver packages to other systems on your network. In this topic, you'll
configure repositories to meet your needs.

REPOSITORIES
Repositories, or repos, are storage locations for available software packages. Repositories can
be checked by package managers like YUM and APT when installing or upgrading software.
There are three kinds of repositories:
• Local repositories: These repositories are stored on the system's local storage drive.
Installation is easy, but version control is difficult because of the decentralized nature of local
repositories. If you manage 20 Linux servers, each would have its own repository to be
maintained.
• Centralized internal repositories: These repositories are stored on one or more systems
within the internal LAN and managed by the Linux administrator. This centralized approach
makes version control much simpler. If you manage 20 Linux servers, one could host the
repository and the other 19 could download their packages from it.
• Vendor repositories: These repositories are maintained on the Internet, often by the
distribution vendor. Version control is very difficult because the vendor decides what
package versions are made available.

Linux LPIC-1 791


The types of repositories.

Linux LPIC-1 792


YUM REPOSITORY CONFIGURATION
Administrators can designate a specific location as a YUM repository by using the createrepo
command. The command updates the XML files that are used to reference the repository
location. The repository might be on the local storage drive (a local repository) or available
from an Apache web server (centralized internal repository).
After the createrepo command is run, a .repo configuration file must be created that provides
additional information about the repository. The .repo files are stored in the /etc/yum.repos.d/
directory. Some of the components of the .repo file are as follows:
• [repo-name] —The repository name.
• name=Repository Name —The human-friendly name of the repo.
• baseurl= —The path to the repo. May be a file (file:///) or http:// path.
• enabled=1 —Enables the repo.
• gpgcheck=0 —Disables GPG checking.

ADDITIONAL YUM SUBCOMMANDS


The yum command includes some additional subcommands for viewing and using repositories.

Subcommand Used To
repolist See all available repositories.
makecache Locally cache information about available repositories.
clean all Clear out-of-date cache information.

Linux LPIC-1 793


REPOSITORY SYNCHRONIZATION
YUM also enables the synchronization of an online repository to a local storage location. This is
also known as mirroring. It has the advantage of reducing WAN traffic and lessening the load on
the parent repository. The reposync utility is used to manage this process. You can choose to
synchronize the parent repository once, or cause it to update periodically. For example, an
administrator might want to synchronize the Red Hat Network (RHN) repository to a local
server, enabling internal Red Hat servers to use the local server as a repository. This local
repository might be then configured to update nightly.

SYNTAX
The syntax of the reposync command is reposync [options]

The following example synchronizes the server-rpms repo to a local directory named packages:
reposync -p packages -r server-rpms

Linux LPIC-1 794


APT REPOSITORY CONFIGURATION
Like the YUM package manager, the APT package manager can also be configured to access
repositories as part of the software management lifecycle. Repositories are exposed to APT in
the /etc/apt/sources.list file and in the /etc/apt/sources.list.d/ directory. Like YUM
repositories, APT repositories may also be on the local system, on the local network, or hosted
on the Internet.

Entries in the /etc/apt/sources.list include the following fields, separated by a space:


deb URL distro-name components

Be sure to let APT know about new repositories after editing the /etc/apt/sources.list file by
running the apt update command

Linux LPIC-1 795


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 796


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 797


Linux LPIC-1 798
Repositories are not the only way to download and install software. Several other tools that
you'll use in this topic enable you to acquire the files necessary to use software.

DOWNLOAD SITES
Because of the open source nature of Linux software, it is very common to be able to freely
download applications directly from the application vendor. In addition, there are many
websites that centralize information about available software, as well as about Linux
distributions.

You can search the Internet for Linux software. Here are a few examples of Linux applications
that are available for download:
• Audacity®, a music production application.
• Atom, a powerful text editor.
• GIMP, a powerful image editor.
• Nmap, a very useful network mapping utility.

You can also search open source hosting sites like GitHub® for software.

Linux LPIC-1 799


THE wget AND curl COMMANDS
Most of us are used to accessing websites using a web browser such as Firefox. It is also
possible, however, to access websites from the command-line. This is especially useful when
downloading a file for which you already know the URL. The wget and curl commands can be
written into scripts, automating the process of downloading package files.
The following is an example of using wget to download a file from the Samba website:
wget http://download.samba.org/pub/samba/samba-latest.tar.gz

The following is an example of using curl to download a file from the Nmap website:
curl -o nmap-7.70.tar.bz2 https://nmap.org/dist/nmap-7.70.tar.bz2

DIFFERENCES
While wget and curl perform the same basic function, there are some key differences:
• wget is a command-line utility only, whereas curl is implemented using the cross-platform
libcurl library and is therefore more easily ported to other systems.
• wget can download files recursively, whereas curl cannot.
• curl supports many more network protocols than wget, which only supports HTTP/S and FTP.
• wget is better suited for straightforward downloading of files from a web server, whereas
curl is better suited to building and managing more complex requests and responses from
web servers.
SYNTAX
The syntax of the wget and curl commands is wget/curl [options] {URL}

Linux LPIC-1 800


.tar FILES
Linux often uses two particular utilities to help manage files. The first utility is tape archiver, or
tar. The second is a compression utility such as gzip. The purpose of tar is to bundle together
multiple files into a single tarball with a .tar extension. This makes functions like downloads
much easier, since there is only one download necessary to acquire multiple files. The server
administrator creates the bundle of files, and whoever downloads the bundle extracts the files
from it.
It is essential to know how to work with tar because a great deal of the software available for
Linux is distributed in tarballs.

The following is an example of creating a tarball: tar -cvf tarball.tar file1 file2 file3
This bundles file1, file2, and file3 into a tarball named tarball.tar.

Linux LPIC-1 801


tar COMMAND OPTIONS
The basic options for the tar command are as follows.

Option Used To

-c Create the tarball.

-x Extract the tarball.

-v Enable verbose mode.

-r Append more files to an existing tarball.

-t Test the tarball or see what files are included in the tarball.

Specify the name of the tarball in the next argument (must be used as
-f
the last option).

Linux LPIC-1 802


COMPRESSED FILES
File compression takes one or more files and reduces their size, making downloads far more
efficient. There are actually several compression utilities available—gzip being
one of the common ones in the Linux world. Files compressed with gzip take on
the .gz extension. It is common to compress a tarball to create the .tar.gz or .tgz extension,
which many repositories use when distributing software packages. Another extension you may
see is .tar.bz2, indicating that the tarball was compressed with the bzip2 utility.

The basic commands for gzip are:


• gzip {file name} —Compresses the file and appends the .gz extension.
• gzip -d {file name} —Decompresses the file.

Linux LPIC-1 803


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 804


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 805


Linux LPIC-1 806
Package managers are efficient and convenient forms of acquiring and installing software.
However, there may be times when you want to build software from source code—after all,
most Linux software is open source.

WHY COMPILE?
Software that is packaged as an .rpm or a .deb is pre-compiled by the vendor. Usually, this
packaged software is configured with generic settings and options. A Linux user may want to
modify the software, for example, to optimize it for their specific hardware. This may result in
maximum performance. Packaged software is most common in Linux, but compiling your own
software is a normal Linux task. The same is not true for Windows and macOS, where nearly all
software is pre-compiled (because you don't typically have access to the open source code).

Linux LPIC-1 807


COMPILERS
Compiling software manually does not use a management tool as packaged software does. To
compile software, there must be a compiler installed. Compilers translate source code written
in a human-friendly programming language, such as C or C++, into machine-readable binaries.
A common compiler for Linux is the GNU Compiler Collection (GCC), implemented as the gcc
utility. There are often other supporting libraries that must also be in place.

The required libraries vary by the software being compiled. Typically, software developers will
provide a list of these necessary libraries with the application source code. These may be
header files (.h file extension) or library files (.a file extension).

Linux LPIC-1 808


LIBRARIES
Program libraries are chunks of compiled code that can be used in programs to accomplish
specific common tasks. Shared libraries enable more modular program builds and reduce time
when compiling the software. Compiled software must be able to access needed libraries when
it runs.

Shared libraries are typically included with a Linux distribution and are placed in
the /usr/lib/ directory for general accessibility. Libraries that need to be accessed by essential
binaries are typically placed in the /lib/ directory. Libraries that aren't packaged with a distro
can also be included by the developer to ensure that the user can run their program.

Linux LPIC-1 809


THE ldd COMMAND
The ldd command enables a user to view shared library dependencies for an application. This
can be useful for troubleshooting or gathering information about system requirements for an
application.

SYNTAX
The syntax of the ldd command is ldd [options] {program binary}

Linux LPIC-1 810


Viewing a program's shared libraries.

Linux LPIC-1 811


THE SOFTWARE COMPILATION PROCESS
When an administrator downloads software, there is a common process to build the executable
file called software compilation:
1. Unpack the download, typically using tar and/or gzip commands.
2. Change into the directory that gets created as part of the unpacking process.
3. Run the ./configure command to gather system information needed by the application. This
information is stored in the makefile, which is referenced during the next step.
4. Use the make command to compile the application using the information stored in the
makefile. Note that this usually requires root privileges.
5. Use the make install command to install the resulting binaries (the application).

Many developers will provide instructions and options that may modify this process somewhat.
Specifically, there may be options or modifications that can be made to the makefile before the
make command is run to optimize the software for the system or the user's needs. It is
important to review any README or other instruction files that are downloaded as part of the
software.

THE make COMMAND


In most cases, once the makefile is created, simply issuing make and then make file without
arguments will install the application. This is because the make command automatically looks
for the makefile in the current directory. You can, however, issue make with various options.

Linux LPIC-1 812


MORE ON MAKEFILES
A makefile is a file that contains instructions used by a compiler to build a program
from source code. These instructions typically define the resources that the program
depends on in order to function properly, as well as any additional directives as
defined by the developer. In the following simple example, the program executable
myprog depends on two object files, mymain.o and myfunc.o:
myprog: mymain.o myfunc.o
gcc -o myprog mymain.o myfunc.o
mymain.o: mymain.c
gcc -c mymain.c
myfunc.o: myfunc.c
gcc -c myfunc.c

On the second line, gcc compiles the objects necessary for the program to run. On
the remaining lines, each object is associated with a C source code file, then compiled
using that source file. Using this approach, if you make changes to a single C source
file (e.g., mymain.c), the make command will be able to efficiently rebuild the
program based on the directives in the makefile.

Linux LPIC-1 812


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 813


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 814


Linux LPIC-1 815
One of the biggest issues when it comes to managing software is dependencies. You need to
ensure that all dependencies are accounted for in order for applications to work as intended.
So, you'll identify some common dependency issues and implement solutions.

DEPENDENCY TROUBLESHOOTING
Dependency troubleshooting involves discovering what package dependencies exist before
attempting a deployment and ensuring that the needed dependencies are stored in the
repositories. Troubleshooting repository issues usually starts by verifying network access to the
repositories, and then checking the repository configuration files. On a Red Hat-derivative
distribution, for example, these files will be located in the /etc/yum.repos.d/ directory.

When troubleshooting problems while compiling software, begin by verifying that the
appropriate compiler, compiler version, and supporting libraries are present.

Linux LPIC-1 816


HOW YUM AND APT MANAGE DEPENDENCIES
The YUM and APT package managers rely on information inside the packages to discover what
dependencies the software might have. YUM and APT then search the repository for the
additional packages that are needed. Both can be configured to automatically install the
dependencies. This ability greatly simplifies the installation process. YUM and APT essentially
interpret the installation commands as "install this software and anything else it might need."

Linux LPIC-1 817


GUIDELINES FOR TROUBLESHOOTING SOFTWARE DEPENDENCY ISSUES
Use the following guidelines when troubleshooting software dependency issues.

TROUBLESHOOT SOFTWARE DEPENDENCIES AND REPOSITORIES


When troubleshooting software dependencies and repositories:
• Use the rpm -V {package name} command to verify that all components of a package are
installed. This is particularly useful if you believe configuration files or other needed files
have been deleted.
• Use the rpm -qR {package name} and yum deplist {package name} commands to discover
dependencies before attempting an installation on Red Hat-derivative distributions.
• Use the apt-cache depends {package name} command to discover dependencies before
attempting an installation on Debian-derivative distributions.
• Use repositories and ensure all dependency packages are stored in the repository along with
the primary software package.
• Ensure your repositories are current.
• Ensure systems have network connectivity to repositories.

TROUBLESHOOT PATCHING AND UPDATE ISSUES


When troubleshooting patching and update issues:
• Read patch documentation before applying the patch. You must use this information to plan
for potential disruption (e.g., downtime as a result of a required restart).
• Ensure there is network connectivity when retrieving updates.

Linux LPIC-1 818


• Test patches and updates before deploying them to production systems to ensure
they work as expected.
• Ensure dependencies and software versions are satisfied for the patches and
updates.
• Check installation logs if systems experience issues after patching.
• Have a contingency plan in case patches result in unexpected behavior, even if
thatbehavior is not immediately noticeable. Ensure you can roll back to a pre-
patched version and that any stored data that could be affected by a patch issue is
backed up beforehand.

Linux LPIC-1 818


TROUBLESHOOT GCC AND LIBRARY ISSUES
When troubleshooting GCC and library issues:
• When compiling software, check the documentation for required GCC or other compiler
versions.
• Verify any required versions of the Linux kernel and software dependencies that the
compiled program has.
• Use ldd [options] {program binary} to check for shared library file dependencies for
software you will be compiling.
• Verify library file versions and availability.
• Consider compiling and testing a program in a virtual machine to ensure it runs properly.
• Assume root privileges when using the make install command.

Linux LPIC-1 819


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 820


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 821


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 822


The importance of cybersecurity cannot be overstated. This is true of all organizations, no
matter their size or what industry they're in. After all, numerous information breaches and
other attacks have dominated the headlines in recent years. Because Linux® systems store and
process much of the world's data, including data of a sensitive nature, those Linux systems
need to be secured. In this lesson, you'll use multiple techniques to bolster the security of your
Linux systems and therefore minimize the risk of the organization falling victim to an attack.

Linux LPIC-1 823


In this topic, you will:

• Implement best practices for cybersecurity in Linux.


• Implement identity and access management (IAM) methods in Linux.
• Configure Security-Enhanced Linux (SELinux) or AppArmor.
• Configure firewalls to filter network traffic.
• Implement event and system logging services.
• Back up, restore, and verify data.

Linux LPIC-1 824


Linux LPIC-1 825
There are some foundational best practices for securing systems that apply to Linux, as well as
operating systems in general. You'll start your security tasks by identifying and implementing
those best practices.

CYBERSECURITY
Cybersecurity refers to the protection of computer systems and digital information resources
from unauthorized access, attack, theft, or data damage. As a business discipline, cybersecurity
is pivotal for essentially all modern organizations, no matter their size. It is also an essential
practice for individuals whose identities are inseparable from the digital space, especially in the
highly connected ecosystem that is the Internet.

As with any computer system, Linux systems must be subjected to sound cybersecurity
practices in order for them to function with minimal risk to the organization. While your
organization may employ security specialists, anyone who touches a computer system,
especially those with administrative access to sensitive assets, is responsible for security.

Linux LPIC-1 826


THE CIA TRIAD
Cybersecurity seeks to address three specific principles: confidentiality, integrity, and
availability. This is called the CIA triad. If one of the principles is compromised, the security of
the organization is threatened.
The CIA triad consists of three principles

Principle Description

This is the fundamental principle of keeping information and communications private and
protected from unauthorized access. Confidential information includes trade secrets,
Confidentiality
personnel records, health records, tax records, and military secrets.
Confidentiality is typically controlled through encryption and access controls.
This is the fundamental principle of keeping organizational information accurate, free of
errors, and without unauthorized modifications. For example, if an attack on a school system's
server occurred and student test scores were modified, the integrity of the grade information
Integrity
would be compromised by unauthorized modification.
Integrity is typically controlled through hashing, digital signatures, certificates, and change
control.
This is the fundamental principle of ensuring that computer systems operate continuously and
that authorized persons can access the data that they need. Information available on a
computer system is useless unless the users can get to it. Consider what would happen if the
Availability
Federal Aviation Administration's air traffic control system failed. Radar images would be
captured but not distributed to those who need the information.
Availability is typically controlled through redundancy, fault tolerance, and patching.

Linux LPIC-1 827


AUTHENTICATION METHODS
Authentication is the verification of an individual's identity. It is a prominent component in
cybersecurity because it enables an organization to trust that users are who they claim to be.
There are various ways to authenticate a user, some of which you should be familiar with.

Authentication Method Description

• Strings of text input along with user name.


PINs/passwords/passphrases
• Meant to be memorized only by user they apply to.
• Physical or digital unique object that you possess to verify identity.
Tokens/OTPs • Can generate OTPs that expire and are not meant to be
memorized.
• Verify identity based on user's physical characteristics.
Biometrics
• Fingerprint scanners, iris scanners, voice recognition, etc.
• RADIUS provides AAA services to remote access clients.
RADIUS/TACACS+
• TACACS+ is more secure and scalable version.
• Directory service protocol that runs over TCP/IP networks.
LDAP
• LDAPS uses SSL/TLS encryption for better security.
• Centralized SSO method based on ticket-granting system.
Kerberos
• Can manage access control to many different services.

Linux LPIC-1 828


LINUX KERBEROS COMMANDS
The Linux implementation of Kerberos has a few commands of note:
• kinit —Authenticates with Kerberos, granting the user a ticket granting ticket (TGT)
if successful.
• kpassword —Changes the user's Kerberos password.
• klist —Lists the user's ticket cache.
• kdestroy —Clears the user's ticket cache.
For example, issuing kinit [email protected] will prompt for the user's password that
is stored in the directory server database. If the correct password is provided, then
the user will obtain a ticket from the Kerberos server. The user can then issue klist -v
to verify that the ticket was obtained. The following is a sample part of the output:
Credentials cache: API:501:9
Principal: [email protected]
Cache version: 0
Server: krbtgt/[email protected]
Client: [email protected]
Ticket etype: aes128-cts-hmac-sha1-96
Ticket length: 256

Linux LPIC-1 828


MULTI-FACTOR AUTHENTICATION
Authentication methods can make use of several factors. These factors are typically expressed
as something you know, something you have, and something you are. Multi-factor
authentication (MFA) is the practice of requiring the user to present at least two different
factors before the system authenticates them. This helps prevent unauthorized access should
one factor be compromised, like an attacker guessing a user's password. Tokens and OTPs
(something you have) are commonly used as the second factor after the user's standard
password. On more advanced systems, biometrics (something you are) are also used as a
factor.

In order for a system to be MFA, it must incorporate more than one factor, not more than one
method. For example, using a hardware token and a software token would not qualify, because
they are the same factor (something you have).

Linux LPIC-1 829


Using a password and a smart card as two different factors for logging in to a system.

Linux LPIC-1 830


PRIVILEGE ESCALATION
Privilege escalation occurs when a user is able to obtain access to additional resources or
functionality that they are normally not allowed access to. One of the most common scenarios
is when a normal user is able to exploit some vulnerability on a system to gain root-level
privileges.

Although privilege escalation can be used for legitimate purposes, e.g., an administrator
assuming root privileges through sudo, you must be on the lookout for any behavior that
enables attackers to escalate their privileges. One pitfall that can enable such behavior is poorly
configured SUID and SGID permissions.

While changing the permissions of a file to use either SUID or SGID, consider the following:
• Use the lowest permissions needed to accomplish a task; i.e., adhere to the principle of least
privilege. It is recommended not to give a file the same SUID or SGID as the root user. A user
with fewer privileges is often enough to perform the task.
• Watch for back doors. If the user runs a program with the SUID set to root, then the user
retains root as the effective user ID when the user goes through the back door. For example,
some programs enable an attacker to shell out to a remote system.

Linux LPIC-1 831


chroot JAIL
A chroot jail is a technique of controlling what a process—a user, for example—can access on a
file system by changing the root directory of that process's environment. This new root
directory is called a "jail" because the process and any child processes that it spawns will be
unable to "break out" of that location and access other parts of the file system. For example, if
you change a process's root location to /home/user/ then, when it references the root (/), the
process will be confined to /home/user/ instead of the actual root of the file system. This is
useful in separating privileged access on the file system so that a malicious or rogue process
cannot cause damage outside of its jail.
The chroot command is used to actually change the root directory for an environment.
For example, chroot /home/user /usr/bin/bash will create the new root directory using the
Bash shell as the process inside the jail.

SYNTAX
The syntax of the chroot command is chroot [options] {new root directory} [command]

Linux LPIC-1 832


A chroot jail

Linux LPIC-1 833


ENCRYPTION
Encryption is a cryptographic technique that converts data from plaintext form into coded, or
ciphertext, form. Decryption is the companion technique that converts ciphertext back to
plaintext. An algorithm called a cipher is responsible for the conversion process.

When a message is encrypted, only authorized parties with the necessary decryption
information can decode and read the data. This information is called a key, and it is used with
the cipher to ensure the message is unreadable to those not in possession of the key.
Encryption is therefore one of the most fundamental cybersecurity techniques for upholding
the confidentiality of data.

TYPES OF ENCRYPTION
Encryption can be applied to data in transit (passing through a network), data in use (accessed
in memory), and data at rest (stored on a device). There are several subtypes of data at rest
encryption, with two of the most prominent being:
• Full drive/disk encryption (FDE), which encrypts an entire storage drive, partition, or volume
using either hardware or software utilities.
• File encryption, which encrypts individual files and folders on a file system using software
utilities.

Linux LPIC-1 834


Encryption and decryption.

Linux LPIC-1 835


LUKS
Linux Unified Key Setup (LUKS) is a platform-independent FDE solution that is commonly used
to encrypt storage devices in a Linux environment. On Linux, LUKS uses the dm-crypt subsystem
that was incorporated in the Linux kernel around version 2.6. This subsystem creates a mapping
between an encrypted device and a virtual device name that user space software can work
with. LUKS offers a high degree of compatibility with various software because it standardizes
the format of encrypted devices.

THE shred COMMAND


Before encrypting a device, it's a good idea to overwrite its contents with random data or all
zeros. This ensures that no sensitive data from past use remains on the device. The shred
command can be used to securely wipe a storage device in this manner.

Linux LPIC-1 836


THE cryptsetup COMMAND
The cryptsetup command is used as the front-end to LUKS and dm-crypt. The LUKS extensions
to cryptsetup support various actions, including the following.

LUKS Action Used To


luksFormat Format a storage device using the LUKS encryption standard.
isLuks Identify if a given device is a LUKS device.
Open a LUKS storage device and set it up for mapping, assuming the
luksOpen
provided key material is accurate.
luksClose Remove a LUKS storage device from mapping.
luksAddKey Associate new key material with a LUKS device.
luksDelKey Remove key material from a LUKS device.

SYNTAX
The syntax of the cryptsetup command is cryptsetup [options] {action} [action arguments]

Linux LPIC-1 837


Encrypting a storage device.

Linux LPIC-1 838


HASHING
Hashing is a process or function that transforms plaintext input into an indecipherable fixed-
length output and ensures that this process cannot be feasibly reversed. The resulting output of
the hashing process is called a hash, hash value, or message digest. The input data can vary in
length, whereas the hash length is fixed. In a hash function, even the smallest of changes to
data can modify the hash considerably, making it much more difficult to deduce the
cryptographic material based on certain patterns. When comparing a value against its hash (to
verify the value hasn't been changed), if the hash you generate matches the hash provided with
the value, you can be pretty sure the value was not modified.

Hashing has several uses:


• It is used in a number of password authentication schemes.
• A hash value can be embedded in an electronic message to support data integrity.
• A hash of a file can be used to verify the integrity of that file after transfer.

Linux LPIC-1 839


Hashing text using the SHA-256 algorithm.

Linux LPIC-1 840


NETWORKING SECURITY BEST PRACTICES
The following describes some best practices you should incorporate in your networking
configurations:
• Enable SSL/TLS in all web server technology. This guarantees confidentiality and authenticity
in the data that is sent to and received from clients. This is especially important in websites
that deal with sensitive data, like credit card information, personally identifiable information,
etc.
• Configure SSH to disable root access. This can prevent an authorized user from gaining
complete access over a system from a remote location. Instead of enabling root access,
assign sudoer privileges to the necessary accounts.
• For remote access and receiving other types of network connections from clients, configure
the system to, by default, deny hosts that it does not recognize. You can create a whitelist of
acceptable hosts so that all hosts not on the list are automatically untrusted.
• Consider changing the default port associations for certain services, like SSH and HTTP/S.
This might be able to confound attackers or temporarily stop automated attacks that target
well-known ports; however, it's important to note that actions like this—called security
through obscurity—are not effective when done in isolation. In some cases, changing default
ports may be more hassle than it's worth.

ENABLING SSL/TLS IN APACHE


The following is a general process for enabling SSL/TLS for use with the Apache web service:
1. Generate a self-signed certificate using a tool like OpenSSL, or request and obtain a

Linux LPIC-1 841


certificate from an external authority.
2. Download and install the mod_ssl package.
3. Open the /etc/httpd/conf.d/ssl.conf file for editing.
4. Find the <VirtualHost _default_:443> line and uncomment the DocumentRoot
and ServerName lines, then replace their values as necessary.
5. Below this, ensure SSLEngine is set to on.
6. Point SSLCertificateFile to the path where your certificate file is located.
7. Point SSLCertificateKeyFile to the path where your private key file is located.
8. Restart Apache.
9. Open a browser and verify that the site is presenting a certificate.

Linux LPIC-1 841


USER ACCESS SECURITY BEST PRACTICES
The following describes some best practices you should incorporate when managing user
access:
• Protect the boot loader configuration with a password to prevent unauthorized personnel
from tampering with boot options.
• Enable a password within your system's BIOS/UEFI to prevent unauthorized personnel from
installing and/or booting into a new operating system.
• Consider discouraging the use of USB devices, particularly USB storage devices like thumb
drives. USB thumb drives can make it easy for an insider threat to exfiltrate sensitive data
from a system, or to load malware onto that system. You can also explicitly block USB access
by unloading the relevant modules from the kernel. Use lsmod to search for usb_storage
and any dependent modules. Then use modprobe -r <module name> to unload the relevant
modules from the kernel. You can also prevent the relevant modules from being loaded at
boot by creating a blacklist file in /etc/modprobe.d/ that contains the line:
install <module name> /bin/false
• Ensure that user IDs (UIDs) are not being shared and are instead unique to each user. By
sharing UIDs, your ability to audit user actions is compromised, as you cannot maintain
accountability for each individual user.
• Consider establishing a public key infrastructure (PKI) that can enforce the use of private and
public keys for authentication. This creates a password-less login scheme to mitigate
password cracking techniques used by attackers to gain access to an account.
• Restrict access to cron, the Linux job scheduler. This can prevent unauthorized users from

Linux LPIC-1 842


configuring the system to automatically run a malicious or unwanted task every so
often, bypassing the need to log in and manually issue a command. You can add
user names to the /etc/cron.d/cron.deny file to blacklist these users from
accessing cron. Each user name must appear on its own line. To whitelist users,
create the /etc/cron.d/cron.allow file and add the names of authorized users. All
other users will be prevented from accessing cron.
• Disable the use of Ctrl+Alt+Del to prevent users from rebooting a system and
disrupting service availability. On systemd systems, you can mask ctrl-alt-del.target
to disable Ctrl+Alt+Del functionality: systemctl mask ctrl-alt-del.target

Linux LPIC-1 842


ADDITIONAL SECURITY BEST PRACTICES
The following describes some additional best practices you should consider implementing in
your Linux systems.
• Enable the auditd service to ensure that records used in auditing are being written to
storage. These records include everything from number of failed logins, number of
commands issued, and much more. Use the aureport and ausearch commands to see
auditing data. Enter systemctl enable auditd to enable auditd at boot.
• Add a banner message to /etc/issue that will display useful information every time a user
logs in. This information can include what purpose the system serves, any behavior the
administrator expects the user to adhere to, etc. You can also edit the message of the day
(MOTD) in /etc/motd to display more information below the banner. To display a message to
SSH clients, edit the /etc/issue.net file.
• Separate operating system data and other types of data, like application files, into different
partitions. Segmenting data can help increase the availability of one type of data should
another type be inaccessible; for example, if a partition containing application data were to
become corrupted, the system partition can still continue to function. A common approach
is to create separate partitions for the root file system (/) and the /home directory. User-
specific data is therefore segmented from the rest of the file system.
• Regularly monitor the Common Vulnerabilities and Exposures (CVE) database, a public
dictionary of vulnerabilities that facilitates the sharing of data among organizations, security
tools, and services. CVE monitoring enables you to stay current on the latest vulnerability
trends that might affect your Linux systems. The official CVE website from the MITRE

Linux LPIC-1 843


Corporation (https://cve.mitre.org/) and the National Vulnerability Database (NVD)
(https://nvd.nist.gov/) are both useful sources for identifying CVE entries.
• Harden your system by disabling or uninstalling unused and/or insecure services.
Only enable services that the system needs, and try to only use services that use
security techniques like cryptography and that are patched. Services that are
popular vectors for attack can include, but are not limited to:
v FTP—Default FTP configurations do not use encryption and therefore send
data in cleartext over the network. They can also be used for data
exfiltration and the spreading of malware. Most modern systems use a
more secure FTP daemon like vsftpd, but if your system is using standard
FTP, you should use a package manager like YUM to uninstall the ftp
package.
v Telnet—Similar to FTP, remote connections using Telnet do not encrypt
data and passwords used in authentication. Telnet is not installed on many
modern distributions, but if it is, you can uninstall the telnet package or set
disabled = yes in the /etc/xinetd/telnet file.
v Finger—This is an outdated service used to retrieve the status of hosts and
users over a network. It is susceptible to many attacks and should not be
used. Like standard FTP and Telnet, this is likely not installed on your
system. If it is, uninstall the finger package or set disabled = yes in the
/etc/ xinetd/finger file.
v Sendmail—This mail transfer agent (MTA) has been susceptible to many
vulnerabilities over the years, including buffer overflows and race
conditions that could expose sensitive data. This is still included in some
modern distros, and can be removed by uninstalling the sendmail package
or removing its binary manually.
v Postfix—This is another MTA that you should consider disabling if mail is
not needed on the system. If this is included in your system, you can
uninstall the postfix package or disable its service using systemctl stop
postfix and then systemctl disable postfix

Linux LPIC-1 843


GUIDELINES FOR IMPLEMENTING CYBERSECURITY BEST PRACTICES
Use the following guidelines when implementing cybersecurity best practices.

IMPLEMENT CYBERSECURITY BEST PRACTICES


When implementing cybersecurity best practices:
• Protect the CIA of information: confidentiality, integrity, and availability.
• Consider using advanced authentication methods like LDAP and Kerberos to centralize
authentication.
• Consider requiring multi-factor authentication for sensitive accounts.
• Ensure you are not granting more access than is necessary when setting SUID and SGID
properties.
• Place unprivileged processes in chroot jails to prevent them from accessing other parts of
the file system.
• Encrypt sensitive data in transit, in use, and at rest.
• Use LUKS to fully encrypt storage devices.
• Implement networking best practices like limiting root access over SSH.
• Implement user access best practices like ensuring that users don't share UIDs.
• Implement additional best practices like separating OS data from app data on different
partitions/volumes.

Linux LPIC-1 844


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 845


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 846


Linux LPIC-1 847
One major dimension of cybersecurity is identity and access management (IAM). You'll
configure various IAM solutions in order to better protect your Linux systems against
unauthorized access.

IDENTITY AND ACCESS MANAGEMENT


Identity and access management (IAM) is a security process that provides identity,
authentication, and authorization mechanisms for users, computers, and other entities to work
with organizational assets like networks, operating systems, and applications. IAM enables you
to define the attributes that comprise an entity's identity, such as its purpose, function, security
clearance, and more. These attributes subsequently enable access management systems to
make informed decisions about whether to grant or deny an entity access, and if granted,
decide what the entity has authorization to do. For example, an individual employee may have
his or her own identity in the IAM system. The employee's role in the company factors into his
or her identity, like what department the employee is in, and whether or not the employee is a
manager.

In most business environments, IAM is a crucial service for provisioning and managing access,
as well as bolstering the overall security of the IT infrastructure.

Linux LPIC-1 848


SSH AUTHENTICATION
In many distros, the default authentication method for SSH access is a password typically the
same password the local user would enter to sign in. However, this type of authentication is
susceptible to various password attacks. An attacker can simply guess a poor password, like a
password that is based on a common word. Or, they can automate the attack process through a
brute force or dictionary attack in order to crack the password using various combinations of
characters.

A more secure alternative, and one that is common in sensitive organizational environments, is
to use public-key cryptography. Using public-key cryptography, the user generates a key pair
one public key, one private key. The server they are trying to remote into has a copy of the
user's public key. The server presents the user with an encrypted challenge that can only be
decrypted by the user's private key. If the user can successfully answer the challenge, the server
can validate that they own the private key. This eliminates the risk of using a password
(assuming password authentication is turned off) because the private key is virtually impossible
to guess or brute force. However, because the key is a "something you have" factor, it must be
stored on a highly secure system, where the risk of it being stolen is low.

Linux LPIC-1 849


The SSH challenge and response process using a public/private key pair.

Linux LPIC-1 850


SSH AUTHENTICATION FILES IN LINUX
The following is a list of files that are used to configure SSH key-based authentication in Linux:
• ~/.ssh/ —A directory that contains files related to SSH keys.
• id_rsa —Contains the user's private key.
• id_rsa.pub —Contains the user's public key.
• authorized_keys —A file on the remote server that lists the public keys that the server
accepts. In other words, the server uses this file to authenticate the client.
• known_hosts —A file on the client that lists the public keys that the client accepts. In other
words, the client uses this file to authenticate servers.
• config —A file on the client that you can use to configure SSH connection settings, such as
using an IdentityFile directive to associate multiple keys with specific servers.

Linux LPIC-1 851


SSH KEY COMMANDS
Various commands are available that you can use to work with SSH keys, including the
following.

Command Used To

Generate a public/private key pair using a specified asymmetric


ssh-keygen
encryption algorithm.
Append the user's public keys to the remote server's
authorized_keys file so that the server can authenticate the user's
ssh-copy-id
private key. The public key is sent over SSH and typically requires
password authentication to be enabled.
Add private key identities to the SSH key agent. If the key is
protected by a password, the user only needs to enter the
ssh-add
password once, and the agent will automatically authenticate the
user.

Linux LPIC-1 852


Generating a public/private key pair for use in SSH.

Linux LPIC-1 853


THE sshd_config FILE
The /etc/ssh/sshd_config file is used to configure an SSH server. Some of the settings you can
configure include the following.

Setting Used To
PasswordAuthentication Enable/disable password authentication.
PubkeyAuthentication Enable/disable public key authentication.
HostKey Reference server's private keys.
UsePAM Enable/disable PAM support.
Port Change port SSH service binds to.
ListenAddress Change IP address SSH service listens on.
SyslogFacility Change logging level of SSH events.
ChrootDirectory Reference a chroot jail path for a user.
AllowUsers, AllowGroups Allow specified users/groups access over SSH.
DenyUsers, DenyGroups Deny specified users/groups access over SSH.
PermitRootLogin Enable/disable root login over SSH.

Linux LPIC-1 854


TCP WRAPPERS
While you can deny access to specific users and groups, you can also deny
connections to SSH that come from specific hosts. This is done by wrapping the SSH
service in a TCP wrapper, which checks what hosts are explicitly allowed and denied
before permitting the host to connect with the SSH service. You can specify hosts to
allow in /etc/hosts.allow and hosts to deny in /etc/hosts.deny. The former has
precedence over the latter, and is applied first. In these files you can specify hosts by
their hostnames, IP addresses, network segments, etc.

For example, to deny all hosts, add the following line to /etc/hosts.deny:
sshd : ALL
Then, to whitelist your desired hosts, add them to /etc/hosts.allow:
sshd : 192.168.1.0/24
sshd : [email protected]

Linux LPIC-1 854


PAM
Pluggable Authentication Modules (PAM) define the underlying framework and centralized
authentication method leveraged by authentication services like Kerberos and LDAP. This
provides a common mechanism for many different authentication services and applications.
Authentication can therefore be streamlined within that single framework, rather than be
different for each application and service.

The streamlining of authentication also benefits administrators, as PAM makes it easier for
them to configure authentication policies across all applications and services on the system, as
opposed to configuring policies in different formats depending on the service. Developers can
also write their own PAM modules in order to support specific authentication and authorization
functions within an app.

ACTIVE DIRECTORY
One popular implementation of LDAP is Microsoft's Active Directory® (AD). While AD is
primarily implemented in Windows® environments, Linux systems can leverage pass- through
authentication to forward AD credentials to PAM. For example, you can configure the System
Security Services Daemon (SSSD) to cache credentials provided by AD or other external
authentication mechanisms, which SSSD can then use with PAM to manage identities.

Linux LPIC-1 855


PAM CONFIGURATION
PAM configuration files are located in the /etc/pam.d/ directory, where each PAM- aware
service or application has its own file. Each file includes directives, formatted in the following
way:
<module interface> <control flag> <module name> <module arguments>

Module interfaces define functions of the authentication/authorization process contained


within a module. Control flags indicate what should be done upon a success or failure of the
module. The module name defines the module that the directive applies to. Module arguments
are additional options you can pass into the module.

MODULE INTERFACES
There are four module interfaces:
• account —Checks to see if a user is allowed access to something.
• auth —Used to verify passwords and set credentials (e.g., Kerberos tickets).
• password —Used to change passwords.
• session —Used to perform tasks in a user session that are required for access, like mounting
home directories.

CONTROL FLAGS
There are four control flags:
• optional —Module result is ignored.

Linux LPIC-1 856


• required —Module result must be successful in order to continue authentication.
The user is notified when all tests in the module interfaces are finished.
• requisite —Same as required, but notifies the user immediately upon failure.
• sufficient —Module result is ignored upon failure.

PASSWORD POLICIES
In addition to the prior dictionary test example, the following are some more
examples of PAM password policy directives.
In the following example, the module will require that the user enter a "quality"
(strong) password. Non-local users—those not found in /etc/passwd—are ignored:
password requisite pam_pwquality.so local_users_only
The next example enforces a password history so that users don't re-use old
passwords when changing theirs. Passwords are "remembered" for 90 days:
password requisite pam_pwhistory.so remember=90
Lastly, the following example hashes the user's password using the SHA-512
algorithm. The use_authtok argument essentially tells the module not to do any
password
checks, but to instead pull in the password that has already been checked by any
prior modules (like quality and history)—assuming that the password has actually
passed those checks:
password sufficient pam_unix.so sha512 use_authtok

USER LOCKOUTS
There are two PAM modules you can use to trigger a temporary user lockout if
multiple authentication attempts fail: pam_tally2 and pam_faillock. The
pam_faillock module is recommended, as it is a newer module that improves upon
pam_tally2 by supporting user lockout when authentication is done over a screen
saver.
You can place these user lockout directives in /etc/pam.d/password-auth and
/etc/pam.d/system-auth
To unlock a user and reset their failure count, you can issue pam_tally2 -r -u user

LDAP INTEGRATION
You can configure PAM to use LDAP by leveraging the pam_ldap module. Using this
module, you can specify other directives that restrict what users can log in and how
they can access resources. If they meet the criteria you set, the pam_ldap module
can then authenticate the user with the LDAP service. You can add these directives to
the /etc/pam.d/common- files.

Linux LPIC-1 856


The following is an example of a password policy directive:
password required pam_cracklib.so retry=5

The module interface password indicates that this directive pertains to changing passwords.
The required control flag means that the result of the module must be successful, or else the
authentication process will not continue. The pam_cracklib.so module contains functionality
that prompts a user for a password and will test that password to see if it can be easily cracked
in a dictionary attack. The retry=5 argument gives the user five chances to fail the dictionary
test.

Linux LPIC-1 857


TTY SECURITY
Recall that, in Linux, controlling terminals are referenced by /dev/tty# where # is a number
unique to a terminal. Each user can work with one or more terminals at a time, including the
root user. However, allowing the root user to work with a terminal can become a security risk,
as anyone with access to the root account can issue essentially any command on the system.
This is where the /etc/securetty file comes in. This file is leveraged by the pam_securetty
module to determine what controlling terminals (tty#) the root user is allowed to login to. If
this file does not exist, the root user can log in from any controlling terminal. If the file exists
and is empty, root access is limited to single user mode and certain programs like ssh.
Otherwise, adding the name of a controlling terminal to this file in the format tty# will give root
access to that terminal.

PSEUDOTERMINALS
A pseudoterminal (PTY) is an emulation of a standard controlling terminal that is used by a
program. The pseudoterminal appears to other software as if it is a real terminal, but data is
being input and output to the program that is emulating the terminal. For example, when you
SSH into a server and enter a command, that command is sent to the pseudoterminal, which is
actually controlled by the SSH service. You can enable the root user to log in to a
pseudoterminal by adding a pts/# entry to the /etc/securetty file. However, this is a security
risk, as it will allow insecure or malicious programs to leverage root privileges.

Linux LPIC-1 858


PKI
A public key infrastructure (PKI) is a system that is composed of certificate authorities,
certificates, software, services, and other cryptographic components, for the purpose of
enabling authenticity and validation of data and entities. The PKI can be implemented in
various hierarchical structures and can be publicly available or maintained privately by an
organization. As its name implies, a PKI implements asymmetric cryptography for the
encryption and decryption of network data, including transactions over the Internet.

Linux LPIC-1 859


PKI COMPONENTS
There are many cryptographic components that comprise a PKI. The following table lists some
of the most important of those components.
PKI Component Description
A digital signature is a message digest that has been encrypted with a user's private key.
Asymmetric encryption algorithms can be used with hashing algorithms to create digital
Digital signature signatures. The sender creates a hashed version of the message text, and then encrypts the
hash itself with the sender's private key. The encrypted hash is attached to the message as
the digital signature.
Digital certificates are the most fundamental component of a PKI, and the overarching
task of a PKI is to manage digital certificates in a variety of ways. A digital certificate
is an electronic document that associates credentials with a public key. Both users
Digital certificate
and devices can hold certificates. The certificate validates the certificate holder's
identity through a digital signature and is also a way to distribute the holder's public
key. In addition, a certificate contains information about the holder's identity.
A CA is a server that issues digital certificates for entities and maintains the
associated private/public key pair. CAs sign digital certificates so that clients can
Certificate validate the authenticity of certificates owned by entities. This is in contrast to a self-
authority (CA) signed certificate—one that is owned by the same entity that signs it. In other words,
the certificate does not recognize any authority, and is essentially certifying itself.
Self-signed certificates require the client to trust the entity directly.
Certificate A CSR is a message sent to a CA in which an entity applies for a certificate. It
signing request typically includes information that should go into the entity's certificate, like its public
(CSR) key, digital signature, and other identifying information.

Linux LPIC-1 860


A PKI hierarchy in which a CA issues certificates to servers.

Linux LPIC-1 861


OpenSSL
OpenSSL is an open source implementation of the SSL/TLS protocol for securing data in transit
using cryptography. On Linux, the openssl command is an interface into accessing a variety of
OpenSSL features. It is also one of the most common tools for generating and managing
components of a PKI. Using openssl, you can:
• Generate public and private keys.
• Generate self-signed digital certificates in various formats.
• Generate digital certificates for other entities based on CSRs.
• Calculate hash values using various functions.
• Encrypt and decrypt data using various algorithms.
• Manage keys and certificates in a CA.
• And more.

The openssl command can be used interactively through one of several subcommands, or you
can provide these subcommands and any options non- interactively.

SYNTAX
The syntax of the openssl command is openssl [subcommand] [options]

Linux LPIC-1 862


VPNs AND IPSEC
In order to authenticate clients and encrypt data in transit, VPNs employ one of several
tunneling protocols. One of the most prominent protocols for site-to-site connections is
Internet Protocol Security (IPSec). IPSec is a set of open, non-proprietary standards that can be
used to secure data as it travels across the network or the Internet. IPSec uses different
protocols and services to provide data authenticity and integrity, anti- replay protection, non-
repudiation, and protection against eavesdropping and sniffing. IPSec operates at the network
layer (layer 3) of the OSI model, so the protocol is not application-dependent.
IPSec has two primary modes of operation: transport mode and tunnel mode. In transport
mode, only the packet contents are encrypted, whereas the header is not. Transport mode is
typically used in remote access VPNs. In tunnel mode, both the packet contents and header are
encrypted. Tunnel mode is typically used in site-to-site VPNs.
Many operating systems support IPSec, including Linux. Networking devices, such as most
routers, also support IPSec. Although IPSec is an industry standard, it is implemented differently
in each operating system and device.

StrongSwan
One popular utility for implementing IPSec tunnels for VPN clients is StrongSwan, available
from the strongswan package. With StrongSwan you can set up user name and password
authentication, and you can also generate digital certificates to use as a method of
authentication. The main configuration file for StrongSwan is located in
/etc/strongswan/ipsec.conf and user accounts are configurable in the
/etc/strongswan/ipsec.secrets file.

Linux LPIC-1 863


A VPN client connecting to a VPN server using IPSec encryption.

Linux LPIC-1 864


VPNs AND SSL/TLS
SSL/TLS is also used as a VPN authentication and encryption protocol, used primarily for remote
access connections. Unlike IPSec, SSL/TLS is an application-layer (layer 7) protocol and is
therefore application-dependent. One of the most popular implementations of an SSL/TLS VPN
on Linux is OpenVPN. OpenVPN supports password-based, certificate-based, and smart-card
based authentication mechanisms for clients. For certificate-based authentication, OpenVPN
can generate self-signed certificates or leverage certificates issued from an existing CA.
OpenVPN is available through the openvpn package. Configuration files are typically stored in
the /etc/openvpn/ directory.

DTLS
The Datagram Transport Layer Security (DTLS) protocol essentially implements SSL/TLS over
datagrams (e.g., using UDP as the transport layer protocol). This means DTLS traffic is not
susceptible to the same delays that TCP-oriented traffic is, particularly when TCP packets are
encapsulated within a TCP connection, like in certain VPN configurations. DTLS is therefore used
as an alternative VPN tunneling protocol. OpenConnect is a popular cross-platform VPN that
supports DTLS tunneling.

Linux LPIC-1 865


ACCESS AND AUTHENTICATION TROUBLESHOOTING
In setting up remote access, you may run into issues where users cannot successfully
authenticate. You need to be sure that these users have set up the proper credentials for their
accounts, and that they are transmitting those credentials to the SSH, VPN, or other external
authentication server. For example, in a public-key SSH authentication environment, users will
need to have the correct key pair in their home directory, as well as place the SSH server in
their list of known hosts. You should also check to see if their remote connection attempts are
triggering a policy violation; for example, if they are trying to use a password when your
configuration file permits public-key authentication only.

If remote access still fails, try signing on with the account locally to see if it's a service issue or
some other networking issue. You can also test if it's a local issue by ensuring the account is
active and not expired and that the password is still valid. If the account has expired or its
password is otherwise invalid, you may need to reset the password using the passwd
command. In addition, you should verify that the account is a member of the correct group(s)
using the groups command.

If users are authenticating through an external service like a Kerberos or RADIUS/ TACACS+, you
should ensure the user identities are correctly configured in those services and that those
services are available over the network. VPNs and SSL/TLS

Linux LPIC-1 866


PAM POLICY VIOLATIONS
Policy violations can also apply to PAM authentication. For example, a user may fail
too many login attempts and is locked out, or the user may fail to configure their
account with a suitably strong password. You should ensure that users are made
aware of the policy's expectations beforehand. If the violation occurs and prevents
users from correcting the issue themselves, you'll need to reset their account status.
If such violations continue to occur and therefore have a negative impact on system
availability, you may need to consider being more lax on the policy directives (e.g.,
reduce password complexity, length, or history requirements). On the other hand,
you may find that lax PAM policies are leading to unauthorized users accessing
resources they shouldn't, indicating that you need to tighten up your policies.

Linux LPIC-1 866


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 867


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 868


Linux LPIC-1 869
Several Linux distributions provide an additional layer of security on top of the operating
system. That layer is usually implemented in the form of SELinux or AppArmor, both of which
can further harden your Linux systems against malicious or careless use.

CONTEXT-BASED PERMISSIONS
Context-based permissions describe multiple types of information about processes and files
that are used in combination to make decisions related to access control. In other words, the
permission scheme defines various properties for a file or process, and uses those properties
together, rather than in isolation, to determine whether to grant or deny access. This makes
context-based permissions more advanced than the default scheme of granting a user or group
access to a file directly.

In Linux, there are two main context-based permission schemes available: SELinux and
AppArmor.

Linux LPIC-1 870


MAC
Mandatory access control (MAC) is a model in which access is controlled by comparing an
object's security designation and a subject's (users or other entities) security clearance. Objects
such as files and other resources are assigned security labels of varying levels, depending on
the object's sensitivity. Subjects are assigned a security level or clearance, and when they try to
access an object, their clearance level must correspond to the object's security level. If there is
a match, the subject can access the object; if there is no match, the subject is denied access.
Both context-based permissions schemes in Linux leverage MAC. This differs from the default
scheme in Linux, discretionary access control (DAC), in which each object has a list of entities
that are allowed to access it, and which the object owner can change directly.

Linux LPIC-1 871


SELinux
Security-Enhanced Linux (SELinux) is the default context-based permissions scheme provided
with CentOS and Red Hat Enterprise Linux, and is optionally available on other distributions. It
was developed by the U.S. National Security Agency (NSA). It provides additional file system
and network security so that unauthorized processes cannot access or tamper with data,
bypass security mechanisms, violate security policies, or execute untrustworthy programs.

SELinux enforces MAC on processes and resources and enables information to be classified and
protected based on its confidentiality and integrity requirements. This helps mitigate the
damage caused to information by malicious applications and users.

Linux LPIC-1 872


SELinux CONTEXTS
SELinux defines three main contexts for each file and process. When you list an object's
contexts, each one is delineated by a colon.
• User: This context defines what users can access the object. Note that this does not refer to
Linux system users, but distinct SELinux users. Each Linux system user is mapped to one of
these SELinux user values. Different distributions provide different users, but common ones
include:
v unconfined_u —All users.
v user_u —Unprivileged users.
v sysadm_u —System administrators.
v root —The root user.
• Role: This context defines what roles can access the object. SELinux users are authorized to
be in roles. Roles are typically used to permit or deny users access to domains, which apply
to processes. The object_r role applies to files and directories.
• Type: This context is the "label" portion of MAC, and is perhaps the most important context
for fine-grained access control. It is a way of grouping objects together that have similar
security requirements or characteristics. The word "type" usually applies to files and
directories, whereas a "domain" is just a type that applies to processes. For example, ssh_t is
the domain for the SSH process.

Linux LPIC-1 873


An example of a file's SELinux contexts.

MULTI-LEVEL SECURITY
Multi-level security (MLS) is an optional feature of SELinux that enables a fourth context, called
a level, to describe the sensitivity level and/or category of an object. This enables you to further
fine-tune and constrain access even when the main three contexts are fulfilled.

Linux LPIC-1 874


SELinux MODES
SELinux has three different modes. Each mode configures the overall implementation of
SELinux on the system.

Mode Description

In this mode, SELinux is turned off. So, MAC will not be implemented and the
Disabled
default DAC method will be prevalent.
In this mode, all the SELinux security policies are enforced. Therefore,
Enforcing
processes cannot violate the security policies.
In this mode, SELinux is enabled, but the security policies are not enforced. So,
Permissive processes can bypass the security policies. However, when a security violation
occurs, it is logged and a warning message is sent to the user.

Linux LPIC-1 875


SELinux POLICIES
An SELinux security policy defines access parameters for every process and resource on the
system. It enforces rules for allowing or denying different domains and types to access each
other. Configuration files and policy source files located in the /etc/selinux/ directory can be
configured by the root user.

Each policy is categorized as either targeted or strict. According to a targeted policy, except the
targeted subjects and objects, all other subjects and objects will run in an unconfined
environment. The untargeted subjects and objects will operate on the DAC method and the
targeted ones will operate on the MAC method. A targeted policy is enabled by default.

A strict policy is the opposite of a targeted policy, where every subject and object of the system
is enforced to operate on the MAC method.

Linux LPIC-1 876


SELinux COMMANDS
The following table describes some of the major commands that you can use to configure an
SELinux environment.

Command Used To
semanage Configure SELinux policies.
sestatus Get detailed status of SELinux.
getenforce Display mode SELinux is running in.
setenforce Change mode SELinux runs in.
getsebool Display on/off status of SELinux boolean values.
setsebool Change SELinux boolean values.
ls –Z List security contexts of files/directories.
ps –Z List security contexts of running processes.
chcon Change security context of files.
restorecon Restore default security context of files.

Linux LPIC-1 877


Checking the status of SELinux.

Linux LPIC-1 878


SELinux VIOLATIONS
Violations occur when SELinux denies a subject access to an object based on policy. This is
typically because the subject has insufficient privileges and is therefore not authorized by the
SELinux environment to perform a particular action. Although violations are expected under
certain circumstances, they can sometimes affect users and processes that should be able to
access an object.

One way to diagnose and troubleshoot unexpected violations is by using the sealert command
with the -a option and the audit log provided as an argument. For example:
sealert -a /var/log/audit/audit.log

This will display all of the policy violations that have occurred, along with detailed information
about each violation, including the timestamp, log type, permission requested, names of the
process and the target it tried to access, security contexts of both, and more.

The output of sealert can be difficult to parse, so you can use the audit2why command to
translate an event into a more human-friendly format that explains why a violation occurred.
You can redirect the entire log to this command. If you only want to analyze one or a few
events, you can grep an identifier that is unique to an event, like its timestamp, and then pipe
that to the audit2why command.

Linux LPIC-1 879


AppArmor
AppArmor is an alternative context-based permissions scheme and MAC implementation for
Linux. Whereas SELinux is more commonly associated with RHEL, AppArmor is packaged with
Debian-based and SUSE Linux distros. AppArmor provides the same fundamental service as
SELinux, but its approach is different in many significant ways. Perhaps the most overarching
difference is that SELinux is very complex and often difficult to configure, whereas AppArmor
was designed to be much simpler.

Functionally, the main difference is that AppArmor works with file system objects based on
paths, whereas SELinux references inodes directly. These paths are referenced in flat
configuration files, or profiles, that AppArmor uses to determine how to control access. This
also means that there are no types or domains in AppArmor, only these profiles.

Linux LPIC-1 880


AppArmor PROFILES
Each executable can have an associated AppArmor profile. Profiles are located in
the /etc/apparmor.d/ directory. Within this directory are several text files that are named in a
path.binary format. For example, the /bin/dig command binary's AppArmor configuration file
would be located at /etc/apparmor.d/bin.dig.

Within a profile, you can configure two main types of rules: capabilities and path entries.
Capabilities provide the executable in question access to some sort of system functionality. For
example, the net_bind_service capability enables the executable to bind to a well-known
TCP/IP port (port numbers below 1024).

Path entries enable the executable to access a specific file on the file system. As the name
suggests, you reference the files by their paths. After the path you specify what permissions
you want to grant to this executable for the files. There are several possible permissions,
including r for read, w for write, ux for unconfined execute (file being accessed doesn't have a
profile), l for link, and so on.

AppArmor MODES
Each profile operates in one of two modes: complain and enforce. In complain mode, profile
violations are logged but not prevented. In enforce mode, profile violations are both logged and
prevented.

Linux LPIC-1 881


AppArmor TUNABLES
Tunables enable you to configure AppArmor functionality without directly modifying
profiles. For example, profiles may reference a common object or path using a
variable name, like @{HOME} to refer to the user's home directory. If the user's
home directory is not in the default location, you can adjust the appropriate tunable
file to account for this. Tunable files are located in the /etc/apparmor.d/tunables/
directory.

Linux LPIC-1 881


AppArmor COMMANDS
The following table describes some of the major commands that you can use to configure an
AppArmor environment.

Command Used To

apparmor_status Display the current status of AppArmor profiles.

Place a profile in complain mode. The basic syntax is aa-


aa-complain
complain {path to profile}
Place a profile in enforce mode. The basic syntax is aa- enforce {path
aa-enforce
to profile}
Disable a profile, unloading it from the kernel. The basic syntax is aa-
aa-disable
disable {path to profile}
List processes with open network sockets that don't have an AppArmor
aa-unconfined
profile loaded.

Linux LPIC-1 882


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 883


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 884


Linux LPIC-1 885
FIREWALL
A firewall is a software program or a hardware device that protects a system or a network from
unauthorized access by blocking unwanted traffic. A firewall can allow or deny incoming and
outgoing traffic based on a set of rules that are either explicitly configured by an administrator
or which are active by default. Firewalls often provide logging features and alerts that track
security problems and report them to the administrator.

There are three main generations of firewalls:


• Packet filters (first generation): These firewalls make decisions based on rules that
correspond to one or more network packet attributes. These rules appear in the form of an
access control list (ACL). Packet filtering firewalls are also called stateless firewalls because
they can only inspect a packet in isolation, and cannot determine what has come before that
packet that might provide valuable context.
• Stateful firewalls (second generation): In contrast to packet filters, stateful firewalls can
identify past traffic that is related to a packet. This means that a stateful firewall can view
the entire conversation of a transmission, such as the three-way TCP/IP handshake. Stateful
firewalls can therefore make more informed decisions about what traffic to deny and what
to allow.
• Application-layer firewalls (third generation): These firewalls can inspect the contents of
application-layer traffic (e.g., protocols like HTTP and FTP) and make decisions based on
these contents. An application-layer firewall can detect attempts to bypass traditional
filtering and stateful inspection that leverage known software exploits.

Linux LPIC-1 886


A packet filtering firewall.

Linux LPIC-1 887


ACL FEATURES
ACL Features
A stateless firewall's ACL can allow or deny packets based on various factors. Those factors
include:
• Source IP address
• Destination IP address
• Source TCP or UDP port
• Destination TCP or UDP port
• TCP or UDP protocol used
For example, one of the most common ways to configure an ACL is to deny incoming traffic that
uses a port that the network or its systems do not need to use. You might configure the ACL to
block incoming traffic on port 21 (FTP) if it is bound for a system that doesn't host an FTP
server.
Once the firewall matches traffic to a rule, it needs to perform one of the following actions:
• Accept: The traffic is allowed through the firewall and sent on to its destination.
• Reject: The traffic is blocked at the firewall and the firewall notifies the sender.
• Drop: The traffic is blocked at the firewall and the firewall does not notify the sender.

In addition, you can configure the firewall to log any of the previous actions. These logs
typically include information about the packet, like its source and destination, as well as
timestamps and other useful data.

Linux LPIC-1 888


THE iptables TOOL
The iptables tool enables you to manage packet filtering as well as stateful firewall functionality
within Linux through various tables. Each table applies to a certain context and consists of rule
sets, called chains, that the table uses to implement the firewall. A packet is compared to the
first rule in the appropriate chain, and if it does not match that rule, it is compared to the next
rule in the chain, and so on. If the packet matches a rule, it can either be evaluated by a new
chain or have one of three actions applied to it: ACCEPT, DROP, or RETURN (skip to next rule in
previous chain).
Each table has one or more built-in chains, but you can also define your own chains as desired.

SYNTAX
The syntax of the iptables command is iptables [options] [-t table] [commands] {chain/rule
specification}

DEFAULT TABLES
There are five default tables that may be active depending on how the kernel is configured:
• filter —The default table used for typical packet filtering functionality.
• nat —Used to implement Network Address Translation (NAT) rules.
• mangle —Used to alter packets' TCP/IP headers.
• raw —Used to configure exceptions for packets involved in connection tracking.
• security —Used to mark packets with SELinux security contexts.

Linux LPIC-1 889


PERSISTENCE
By default, rules set with iptables will be lost on reboot. In CentOS/RHEL, you can
install the iptables-services package and issue the service iptables save command to
ensure your changes persist. For Debian-based distros, you can install the iptables-
persistent package. After installation, you'll be asked to confirm that you want your
current rules to persist. The iptables-persistent service will then automatically run at
boot and load your rules.

LOGGING
You can enable logging for iptables rules by including the LOG action. In the following
example, all dropped packets are being logged:
iptables -N LOGCHN
iptables -I INPUT -j LOGCHN
iptables -I LOGCHN -j LOG
iptables -I LOGCHN -j DROP
The first line creates a new chain called LOGCHN. The second line ensures all
incoming packets not already processed by any prior rules will "jump" to the LOGCHN
chain. The third line logs all packets that reach this chain, and the fourth line
performs the actual dropping of packets. You can also substitute ACCEPT for DROP if
you only want to log accepted packets.
Events for iptables are typically written to the /var/log/messages or
/var/log/kern.log files.

Linux LPIC-1 889


Listing the rules in a firewall chain.

Linux LPIC-1 890


UFW
The Uncomplicated Firewall (UFW) is a firewall management tool that makes it easier
to configure the iptables service. UFW originated with Ubuntu® but can be downloaded and
installed on other distributions. It is primarily useful for home users who don't have experience
with the intricacies of firewall configuration.
The ufw command enables you to work with the command-line interface. For example, the
following commands set up an allow rule for HTTP, turn on logging, and enable the firewall.
This automatically creates a default deny configuration for incoming traffic—in other words,
everything without an explicit allow rule is dropped:
ufw allow http/tcp
ufw logging on
ufw enable

SYNTAX
The syntax of the ufw command is ufw [options] {action}

ADVANCED CONFIGURATION
If you want to use UFW to employ a more complex firewall configuration, you'll need to edit
text files rather than use the ufw command. The /etc/default/ufw file is used to configure
high-level settings like policy defaults and kernel module usage. More granular configuration
files are found in the /etc/ufw/ directory. You can edit these files to control when rules are
applied, when customizations are run with respect to the ufw command, and more.

Linux LPIC-1 891


For example, UFW defaults to accepting outgoing traffic through the firewall. You
change this behavior by specifying a different policy directive in /etc/default/ufw:
DEFAULT_OUTPUT_POLICY="DROP”
As a more granular example, you can configure /etc/ufw/applications.d/myapp to
instruct UFW to recognize your app and its port/protocol information:
[My App]
title=My App
description=My custom application
ports=23534/tcp

Linux LPIC-1 891


THE firewalld SERVICE
The firewall daemon (firewalld) is used to dynamically manage a firewall without requiring the
firewall to restart upon modification. It is an alternative to iptables and uses zones and services
rather than chains and rules.

Firewall zones are the rule sets that can apply to specific network resources, like a network
interface. You'd typically place resources in a zone to group them with resources that have
similar security requirements or similar levels of trust. There are various default zones, each
with different levels of trust. For example, the zone with the lowest level of trust is called drop
and it immediately drops all incoming connections. Firewall services are the rules that apply to
specific services that operate within a zone. For example, you can add a service like HTTP to the
dmz zone to allow incoming connections from untrusted networks like the Internet, while
denying outgoing access to the rest of the network.

Linux LPIC-1 892


THE firewall-cmd COMMAND
The firewall-cmd command enables you to configure firewalld by querying, adding, modifying,
and deleting zones and services as desired. Because firewalld is the default firewall service for
many Linux distributions, including Red Hat® Enterprise Linux® and CentOS®, you will be using
the firewall-cmd command regularly. The command includes options to identify which zone
and which interface you want to configure, as well as the ability to permit services by name or
by port number.

SYNTAX
The syntax of the firewall-cmd command is firewall-cmd [options]

Linux LPIC-1 893


Listing the configurations for a specific firewalld zone.

Linux LPIC-1 894


firewall-cmd COMMAND EXAMPLES
The following are some common examples of using the firewall-cmd command:
firewall-cmd --get-zones —list all available firewalld zones.
firewall-cmd --zone=dmz --list-all —list all details of the dmz zone, including the interfaces,
ports, services, protocols, and more that the zone applies to.
firewall-cmd --zone=dmz --change-interface=<device ID> —add the specified interface to the
dmz zone.
firewall-cmd --zone=dmz --add-service=http —add the HTTP service to the dmz zone.
firewall-cmd --zone=dmz --add-port=21/tcp —add TCP port 21 (FTP) to the dmz zone.
firewall-cmd --zone=dmz --remove-service=http—remove the HTTP service from the dmz
zone.
firewall-cmd --zone=dmz --remove-port=21/tcp —remove TCP port 21 (FTP) from the dmz
zone.
firewall-cmd --reload —reload the zone's configuration.

PERSISTENCE
Like iptables, firewalld does not persist its changes by default. This is called runtime mode. You
must commit a change with the --permanent option for it to persist upon restart of the
daemon.

Linux LPIC-1 895


NETFILTER
Netfilter is a Linux kernel framework that handles packets that traverse a network interface.
Some of the major services it provides are packet filtering, NAT, and connection tracking.
Netfilter supports the configuration of these services by providing hooks into the kernel's
network stack. Every packet that traverses the network interface will be "caught" by these
hooks. User space programs that are registered with the relevant hooks are able to interact
with the packets on the hooks.

The iptables tool is closely integrated with Netfilter. It is able to allow, drop, and perform other
firewall actions because it can interact with packets that are on Netfilter hooks. Both UFW and
firewalld call iptables in some capacity, so they likewise rely on Netfilter.

Linux LPIC-1 896


IP FORWARDING
IP forwarding is the Linux kernel implementation of network routing functionality. It enables
incoming traffic on one network interface to be forwarded to another network interface. IP
forwarding is therefore only useful on systems that have multiple interfaces, particularly
systems that act as routers or gateways for other systems in the network.

IP forwarding is often used in conjunction with iptables firewall configuration. For example, say
you have a Linux host acting as a router. It has one public, Internet-facing interface; and one
private, internal-facing interface. You also have a separate web server with only a private
interface. You want traffic from the Internet to pass through your router, and only be forwarded
on to the internal network if the traffic uses ports 80 or 443 (HTTP/S). You can do this by
configuring a FORWARD chain that will allow traffic on ports 80 and 443 to be forwarded on to
the private interface, while preventing any other kind of traffic from being forwarded.

In order to leverage IP forwarding, you must first enable it in the kernel. This is as simple as
altering a single value in the appropriate file:
echo 1 > /proc/sys/net/ipv4/ip_forward
Or, for IPv6 traffic:
echo 1 > /proc/sys/net/ipv6/conf/all/forwarding

Linux LPIC-1 897


A Linux system receiving traffic on one NIC and forwarding that traffic to another NIC.

Linux LPIC-1 898


IP SETS
IP sets are stored collections of IP addresses, network ranges, MAC addresses, port numbers,
and network interface names. The iptables tool can leverage IP sets for more efficient rule
matching. For example, let's say you want to drop traffic that originates from one of several IP
address ranges that you know to be malicious. Instead of configuring rules for each range in
iptables directly, you can create an IP set and then reference that set in an iptables rule. This
makes your rule sets dynamic and therefore easier to configure; whenever you need to add or
swap out network identifiers that are handled by the firewall, you simply change the IP set.

SYNTAX
The syntax of the ipset command is ipset [options] {command}

Linux LPIC-1 899


The ipset command enables you to create and modify IP sets. First you need to set a name,
storage method, and data type for your set, such as:
ipset create range_set hash:net

In this case, range_set is the name, hash is the storage method, and net is the data type. Then,
you can add the ranges to the set:
ipset add range_set 178.137.87.0/24 ipset add range_set 46.148.22.0/24
Then, you use iptables to configure a rule to drop traffic whose source matches the ranges in
this set:
iptables -I INPUT -m set --match-set range_set src -j DROP
Alternatively, to drop traffic whose destination matches the set:
iptables -I OUTPUT -m set --match-set range_set dst -j DROP

TROUBLESHOOTING
The ipset tool can also be used when troubleshooting the iptables firewall. For example, you
can use the test subcommand to test whether or not an entry exists:
ipset test range_set 178.137.87.5
If the firewall still isn't handling the IP address ranges as expected, you can list the rules that
are using the relevant set:
iptables -L | grep range_set
Even if the rules are using your set, keep in mind that the rules are processed in order; the
unexpected behavior may be due to how these rules flow in the table.

Linux LPIC-1 900


FIREWALL CONFIGURATION FOR APPLICATIONS
As you know, network services and applications require the use of a port to establish a
connection endpoint. Most common protocols have a dedicated port number as assigned by
the Internet Assigned Numbers Authority (IANA). However, you may need to run a custom or
uncommon application that requires network access, and this application may not have a
standardized port number. In that case, you'll need to choose a port number and associate it
with your application, then open that port at the firewall.

Linux keeps a database of services and their corresponding port numbers in the /etc/services
file. This file enables services to, by default, attempt to bind to their corresponding port when
activated. The format of each entry is:
service-name port/protocol [aliases] [# comment]

So, to map an application called my-app to port number 55111, you'd add the following line:
my-app 55111/tcp # My custom app

Whenever my-app is started, it will attempt to bind to port 55111 and start listening on that
port. So, you'd use a firewall service like iptables or firewalld to allow traffic bound for port
55111 on the network.

TRUSTED PORTS
Trusted ports, also called privileged ports, are ports in the well-known range (0– 1023). In

Linux LPIC-1 901


Linux, if a process is to start listening on a trusted port, or to establish a remote
connection from a trusted port, it must have superuser privileges. This helps the
other side of the connection confirm that the service they are connecting to is
trusted. This is especially important when it comes to FTP, HTTP, SSH, and other
common protocols that involve the transfer of data. Because many servers use these
protocols, you'll need to ensure that their ports are open in the firewall.

Linux LPIC-1 901


FIREWALL TROUBLESHOOTING
As you configure and implement a firewall, you may run into a common issue: The firewall
blocks traffic that it shouldn't. The following table lists some potential causes and solutions
associated with this issue.

Cause Solution

Check your firewall's rule set to ensure that it is not overtly blocking a port that your
system needs in order to forward outgoing traffic. Likewise, your firewall is likely in
Blocked ports
default deny mode for incoming connections, so be sure to create an explicit rule that
allows traffic on the port you need.
Even though you may be correctly allowing a port, you may not have configured it for
the correct protocol. Ensure that you are opening up the port on either TCP, UDP, or
Blocked protocols both— depending on what transport protocol the connection requires. Also ensure
that, for application-layer firewalls, they are not configured to drop packets whose
contents match a specific application-layer protocol (e.g., HTTP, FTP, SSH).
The factors that an ACL uses to allow or deny traffic can be used in conjunction; for
example, you can configure an ACL to only block a specific source port if its source
matches a known IP address and if it is headed for a specific destination port. Granular
Restrictive ACLs filtering like this can be very useful, but it can also become complex and has a higher
potential for false positives. Configure your ACL rules to be as straightforward as your
needs allow and don't get carried away with trying to write a granular rule for every
possible scenario.

Linux LPIC-1 902


IPSs
An intrusion prevention system (IPS) is a security appliance that monitors and evaluates a
system for signs of attacks in progress, and can actively block traffic that it determines is
malicious. IPSs are similar in purpose to firewalls in that both can stop unwanted traffic from
entering a network. However, they have some key differences.

A firewall is like a security guard who lets guests into a building based on whether or not they
match predefined rules. An IPS is more akin to a second security guard inside a building. Even if
the outside guard (the firewall) lets someone in, the inside guard (the IPS) will watch that guest
for signs of suspicious behavior. If the guest exhibits a repeated pattern of suspicious behavior,
the inside guard will kick them out. In other words, an IPS is a second layer of defense that
monitors traffic that makes it past the firewall, looking for signs of anomalous behavior.

The other major difference is that IPSs are only concerned with managing incoming traffic,
whereas firewalls apply to both incoming and outgoing traffic.

Linux LPIC-1 903


An IPS appliance monitoring traffic on a LAN segment.

Linux LPIC-1 904


DENYHOSTS AND FAIL2BAN
There are many IPS solutions available. Two common third-party solutions are DenyHosts and
Fail2ban, both of which examine log files for anomalies.
DenyHosts primarily protects SSH servers from brute force password cracking attacks. In such
attacks, an attacker will repeatedly attempt to log in to the SSH server using credentials that
increment each time. DenyHosts monitors the authentication log to look for failed login
entries. It will take the source IP address and number of failed attempts into consideration. If
enough failed attempts from the same source meet the threshold you've configured (or the
default), DenyHosts will block that source. A major limitation of DenyHosts is that it only works
with IPv4 traffic and not IPv6.
Fail2ban also prevents brute force attacks, but unlike DenyHosts, it does not focus on any one
service. Instead, it can monitor log files that pertain to any system service with an
authentication component. Fail2ban leverages Netfilter and iptables to actually perform
blocking actions, and can even be used to update your firewall rules. Fail2ban supports both
IPv4 and IPv6.

CONFIGURATION
The primary configuration file for DenyHosts is the /etc/denyhosts.conf file. There are various
settings you can adjust in this file. Some examples include:
• ADMIN_EMAIL —Define what email address to send alerts to.
• BLOCK_SERVICE —Define what services will be blocked from access by unauthorized users.
• DENY_THRESHOLD_VALID —Defines how many times a user can attempt to log in to an

Linux LPIC-1 905


existing account before being blocked.

The primary configuration file for Fail2ban is the /etc/fail2ban/jail.conf file. However,
if you plan on configuring Fail2ban, it is best to copy this file to /etc/
fail2ban/jail.local or make a custom .conf file within the /etc/ fail2ban/jail.d/
directory. The following are some example settings:
• bantime —Defines how long a host is blocked from accessing a resource.
• maxretry —Defines the number of times a host can fail to authenticate before
being blocked.
• ignoreip —Defines a whitelist of accepted hosts.

Linux LPIC-1 905


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 906


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 907


Linux LPIC-1 908
Security is not just a process of designing a hardened system. Another major element is the
analysis of system, software, and user events. By generating and maintaining logs of these
events, you'll be able to more easily identify malicious behavior or misconfigurations that
increase the risk of compromise.

SYSTEM LOGS
System logs are records of system activities and events that are tracked and maintained by the
syslogd daemon. System logs use the syslog standard, which facilitates a centralized logging
server that can receive and process syslog data from many systems across a network. This is
called remote logging. The syslog standard also supports local logging, where logs are stored on
the same system that generated them.
System logs are recorded in simple text files that you can examine and process like any other
text. Entries in a syslog system typically include the date and time of the event, the process
name and ID that sent the message, and the message itself. The syslog format may also
prioritize messages by facility and severity. Facility codes indicate what system was affected,
such as "kern" for kernel and "mail" for the mailing system. Severity codes indicate what level
of impact the event might have, from 0 (most critical) to 7 (least critical).

Linux LPIC-1 909


LOG FILE LOCATIONS
In most Linux distributions, system logs are located in the /var/log/ directory. Inside this
directory are the logs themselves, and each file corresponds to a service, application, or
feature. The following table lists some of the most common log files.

Log File Contains

/var/log/syslog All system events except authentication messages (Debian).

/var/log/messages General non-critical system events (RHEL).

/var/log/auth.log Authentication messages (Debian).

/var/log/secure Authentication messages (RHEL).

/var/log/kern.log Kernel messages.

/var/log/[application] Messages from miscellaneous applications.

Linux LPIC-1 910


LOG ROTATION
Log rotation is the practice of creating new versions of a log file to maintain a minimum log file
size. The logrotate utility is used to perform automatic rotation of logs. When executed,
logrotate adds a .1 to the end of the file name of the current version of the log files. Previously
rotated files are suffixed with .2, .3, and so on. The utility can also be configured to append the
date of the log to the file name rather than a decimal number.
Using automatic rotation, all versions of a log file will be maintained on the system unless
otherwise specified. Log files can be rotated on a daily, weekly, monthly, or yearly basis. They
can also be automatically rotated if they reach a certain size threshold. Log rotation makes it
easier to process and analyze logs, as a log file with too many entries can be come unwieldy.
Likewise, if the log rotation service is configured to purge older log files, it can save on storage
space.
CONFIGURATION
Log rotation behavior can be configured in the /etc/logrotate.d/ directory, where each relevant
service has its own configuration file. The following is an example configuration file for a service
called myservice:
/var/log/myservice.log {
size 1k
create 700 user group
dateext
rotate 10
}

Linux LPIC-1 911


The first line defines where the log should be output. The size directive indicates that
the log should rotate when it reaches 1,000 bytes in size. The create directive rotates
the log file by creating a new one with the specified permissions, user, and group. The
dateext directive appends the date to the rotated log. Finally, rotate specifies that
only the 10 most recent log files should be kept.

Linux LPIC-1 911


THE rsyslogd SERVICE
The syslogd service is the original syslog service on Linux. The rsyslogd service makes several
improvements, including support for:
• TCP instead of UDP as the transport protocol, increasing the reliability of transmitted data.
• Data encryption using SSL/TLS.
• Outputting data to various database technologies like MySQL.
• Buffering data on local systems when the remote receiver is not ready to accept it.
• Filtering data based on content.
In addition, rsyslogd maintains the same basic configuration format of its predecessor, so it is
backwards compatible in that sense.

Linux LPIC-1 912


THE /etc/rsyslog.conf FILE
The /etc/rsyslog.conf file is the configuration file for the rsyslogd service. This file determines
how to handle syslog messages through a variety of rules that you can modify as needed.
The file takes a two-column format. The first column lists message facilities and/or severities.
Severities are defined in word format rather than as numbers 0–7. The second column defines
what actions should be taken for messages that correspond to the facility and/or severity.
Actions include which file to write the message to; which users to print the message to if they
are logged in to a terminal; and which remote hosts to forward the message to.

THE syslog-ng SERVICE


The syslog-ng service is another replacement for the older syslogd service. Although it offers
similar functionality to rsyslogd, syslog-ng has its own syntax.

Linux LPIC-1 913


The /etc/rsyslog.conf file.

Linux LPIC-1 914


THIRD-PARTY AGENTS
Although centralized administration capabilities grant you greater control over logging in your
network, the syslog standard is not universally supported on all platforms. Windows, for
example, uses the proprietary Windows Event Log format to record system messages. In order
to facilitate integration between syslog and non-syslog platforms, you need to use third-party
agents. An agent is a software program that acts on behalf of some other program or service.

You install a syslog agent on the platform that doesn't normally support the standard, like
Windows. Which agent you install will depend on the platform, as well as the type of syslog
service you're targeting. For example, rsyslog and syslog-ng both require their own agent
software. Once the agent is installed, you'll be able to configure it to capture messages in a
syslog format and send those messages on to your centralized syslog server.

Linux LPIC-1 915


THE journalctl COMMAND
The journalctl command enables you to view and query log files created by the journal
component of the systemd suite. Log information is collected and stored via the systemd
journald service. You can use journalctl to print the entire journal log, or you can issue various
options with the command to filter the log in a variety of ways, such as matching a service
name or only printing messages matching the specified severity level.

The journald service is often used in conjunction with a traditional syslog daemon such as
syslogd or rsyslogd. The settings for journald are configured in the /etc/systemd/journald.conf
file.

SYNTAX
The syntax of the journalctl command is journalctl [options] [matches]

THE /var/log/journal/ DIRECTORY


In its default configuration, the systemd journal only stores logs in memory, and logs are
cleared on each system reboot. You can have the journald logs persist after a reboot by
creating the /var/log/journal/ directory. The systemd service is configured to automatically
maintain logs in this directory if it exists.

Linux LPIC-1 916


Viewing the systemd journal.

Linux LPIC-1 917


journalctl COMMAND OPTIONS
The journalctl utility provides a number of options for querying journald log data. Some of the
frequently used options are listed in the following table.

Option Used To

-n {number of lines} Specify the number of lines of journal logs to display.

Specify the format of the output. For example: short, verbose, or


-o {output format}
export.
Display the most recent journal entries, and continuously update the
-f
display with new entries as they are added to the journal.
Filter journal log output by severity (alert, err, warning, notice, info,
-p
etc.).
Filter journal log output by the specified unit, such as the name of a
-u
service.
Show log message from the current boot only, or the boot ID
-b [boot ID]
specified.

Linux LPIC-1 918


THE last COMMAND
The last command displays the running history of user login and logout events, along with the
actual time and date. It also has various options that enable you to filter the results, such as
filtering by users who have logged in through a specific terminal. For example, last 1 will display
the details of users who logged in using the first terminal (tty1). The last command retrieves
information from the /var/log/wtmp file.
To pull this same information for only failed login events, you can use the lastb command. This
command retrieves information from the /var/log/btmp file.

SYNTAX
The syntax of the last command is last [options]

THE lastlog COMMAND


The lastlog command is similar to the last command, but instead of listing the most recent
login events, it lists all users and the last time they logged in. This command retrieves
information from the /var/log/lastlog file.

Linux LPIC-1 919


Listing recent login and logout events.

Linux LPIC-1 920


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 921


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 922


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 923


Linux LPIC-1 924
Another major element of cybersecurity is the backup process. Backing up data is crucial in any
organization that cannot afford to lose data or suffer damage to that data's integrity. So, in this
topic, you'll back up sensitive data, test your ability to restore it at a later time, and then verify
that the data was not tampered with.

BACKUP TYPES
A backup is a copy of data that exists in another logical or physical location than the original
data. Backups facilitate the recovery process in case of data loss. The process of recovering data
from a backup varies depending on the backup types that were included in the original backup
plan.

There are three main types of backups: Full backup, Differential backup, and Incremental
backup

BACKUP STORAGE METHODS


Full, differential, and incremental all describe the frequency of data backups. But there are also
different ways to go about storing backup data.

Linux LPIC-1 925


There are three main types of backups.

Backup Type Description

All selected files, regardless of prior state, are backed up.


Numerous full backups can consume a great deal of storage
Full backup
space, and the backup process can be slow. However, full backups
are fast and reliable when it comes to recovering lost data.
All selected files that have changed since the last full backup are
backed up. When differential backups are used, you must restore
Differential backup the last full backup plus the most recent differential backup.
Differential backups require less storage space and backup time
than full backups, but are slower to recover.
All selected files that have changed since the last full or
incremental backup (whichever was most recent) are backed up.
When incremental backups are used, you must restore the last full
Incremental backup backup plus all subsequent incremental backups. An incremental
backup typically takes less time to perform than a differential
backup because it includes less data, but it is also slower when it
comes time to recover the data.

Linux LPIC-1 926


BACKUP STORAGE METHODS
Full, differential, and incremental all describe the frequency of data backups. But there are also
different ways to go about storing backup data.

Backup Storage Method Description

Snapshots record the state of a storage drive at a certain point in


time and usually exist on the same drive. They are "checkpoints"
Snapshot
that you can restore the drive to rather than true copies of data
that exist elsewhere.
You can back up data as individual files or as collections of files,
but you can also create one-to-one copies of entire systems.
Image Image-based backups save the state of an operating system in an
image file format like ISO. You can use this image to restore a
system to the state it was in when the image was captured.
Cloning is the process of copying all of the contents of a storage
drive to another storage medium. Technically, an image backup is
Clone a clone of a drive. However, cloning operations often go one step
further by using the image file to reconstruct the original drive on
a second drive.

Linux LPIC-1 927


THE tar COMMAND
The tar command enables you to create archives of data. It's commonly used to create an
archive file from a directory that contains the data you want to back up. You can also use the
command on previously created archives to extract files, store additional files, update files, and
list files that were already stored. File archives made with tar frequently have the .tar file
extension. The tar command can also direct its output to available devices, files, or other
programs using pipes.

SYNTAX
The syntax of the tar command is tar [options] {file names}

RESTORING FILES WITH THE tar COMMAND


The command tar -xvf will restore the entire contents of the source file or directory structure.
To restore a portion of a tar file, use the path and name of the file you wish to extract. You must
use the exact path and name that was used when you created the tar file. You can also make
restores interactive by using the command tar -wxvf [destination] [source]

THE dar COMMAND


The dar ("disk archiver") command is intended to replace tar by offering more backup and
archiving functionality. It is especially useful at creating full, differential, and incremental
backups. The following command creates a full backup of the mydata directory and outputs a
backup file named full.bak:

Linux LPIC-1 928


dar -R mydata -c full.bak

To create a differential backup (diff1.bak), you can reference the full backup using the
-A option:
dar -R mydata -c diff1.bak -A full.bak

You can then create more differential backups as needed by referencing the full
backup with the -A option. However, to perform incremental backups instead, you
need to reference the previous incremental backup, like so:
dar -R mydata -c incr1.bak -A full.bak
dar -R mydata -c incr2.bak -A incr1.bak

The -x (extract) option is used to recover a backup. If you performed differential


backups, you need to first extract the full backup, then the latest differential backup:
dar -x full.bak
dar -x diff1.bak -w

The -w option automatically overwrites changes to files; otherwise, you will be


prompted to confirm.
To recover an incremental backup, you need to first extract the full backup, then each
incremental backup, in order:
dar -x full.bak
dar -x incr1.bak -w
dar -x incr2.bak -w

Linux LPIC-1 928


Creating an archive from multiple files.

Linux LPIC-1 929


THE cpio COMMAND
The cpio command copies files to and from archives. The cpio command has three operating
modes.

Operating Mode Command Used To

Copy files into an archive. It reads the standard


Copy-out cpio –o input to obtain a list of file names and then copies
those files to the standard output.
Copy files from an archive. It extracts files from the
Copy-in cpio -i
standard input. This option is used in data recovery.
Copy files from one directory tree to another. It
reads the standard input to obtain the list of file
Copy-pass cpio -p
names that are created and copied into the
destination directory.

SYNTAX
The syntax of the cpio command depends on its mode. In all modes, the command reads from
standard input. The following copy-out example archives all contents of a directory by piping ls
to cpio and sending the archive output to dir_arch:
ls | cpio -o > dir_arch

Linux LPIC-1 930


In copy-in mode, you can extract an archive as follows:
cpio -i < dir_arch

In copy-pass mode, you can pipe find to cpio to copy one directory tree to another:
find . -depth -print | cpio -p new_dir

Linux LPIC-1 930


THE dd COMMAND
The dd command copies and converts files to enable them to be transferred from one type of
media to another. The dd command has various operands, or actions, to perform.

Operand Used To
if={file name} Specify the file from which data will be read.
of={file name} Specify the file to which data will be written.
Specify the total block size to read and write, in bytes. Bytes can also be
bs={bytes} formatted in a more human-friendly way, such as 50M to specify 50
megabytes and 10G to specify 10 gigabytes.
Specify the number of blocks to be written to the output file from the input
count={blocks}
file.
Specify the level of information to print to standard error:
• none to suppress everything except error messages.
status={level}
• noxfer to suppress total transfer statistics.
• progress to display transfer statistics periodically.

SYNTAX
The syntax of the dd command is dd [options] [operands]

Linux LPIC-1 931


USING dd FOR BACKUPS
You can use dd to perform a full backup of a storage partition. The following example
copies data from /dev/sda1 to /dev/sdb2:
dd if=/dev/sda of=/dev/sdb

Using dd, you can also create an image of a drive and then clone a second drive with
it:
dd if=/dev/sda of=drive_image.iso
dd if=drive_image.iso of=/dev/sdb

Linux LPIC-1 931


THE mirrorvg COMMAND
The mirrorvg command creates copies, or mirrors, of all logical volumes in a specified logical
volume group. By default, the command will create the mirrors on the same drives that are
associated with the volume group. You can also specify other drives to mirror the volumes to, if
desired. The -c option can be used to create two or three copies of a logical volume, rather than
the default of just a single copy.

SYNTAX
The syntax of the mirrorvg command is mirrorvg [options] {volume group}

OTHER WAYS TO MIRROR LOGICAL VOLUMES


Other than using mirrorvg to mirror all volumes in a group, you can also use the mklvcopy
command to mirror individual logical volumes in a volume group. You can also use the -m#
option with lvcreate to create one or more mirrors of a logical volume. For example, the
following command creates one 10 GB mirror called mirrorlv that copies from the volgr volume
group:
lvcreate -L 10G -m1 -n mirrorlv volgr

Linux LPIC-1 932


OFF-SITE BACKUP
An off-site backup is a physical location outside of the main site that stores copies of data. Off-
site backups are a component of disaster recovery processes, as they are often necessary to
reconstruct data in the event of a major disruption to the main site.

There are several ways to copy data from the main site to the backup site. Rather than
physically move backup storage devices from one location to the other, it's usually more
convenient to connect both sites by a network, such as in a VPN, and transfer data over that
network.

Linux LPIC-1 933


DATA TRANSFER TOOLS
The following data transfer tools are useful in facilitating the off-site backup process.
Data
Transfer Description
Tool
This tool is used to copy data to or from a remote host over SSH. Because it uses SSH, data you
send to an off-site backup will be encrypted in transit, protecting its confidentiality. Like SSH, scp
scp
uses TCP port 22 by default. The following is an example of copying a file to a remote host:
scp file.txt user@host:/home/dir
This command is the implementation of the Secure File Transport Protocol (SFTP). SFTP uses SSH
tunnel as a transportation mechanism to encrypt data. Whereas scp is used purely for transferring
files, sftp can transfer files and manage files and directories. So, you can list, create, and remove
directories on the remote system. The sftp command also supports resuming file transfers,
sftp
whereas scp does not.
Just like with the standard ftp command, you can use sftp interactively or non-interactively. For
example, to retrieve a file non-interactively:
sftp user@host:file.txt
This tool is used to copy files locally and to remote systems. Its real power lies in its efficient use of
network bandwidth; instead of copying all files, it only copies differences between files. So, if you
use rsync on all files in a directory, it will check the destination directory to see if those exact files
already exist. Only files that aren't already in the destination will be copied.
rsync The rsync command can copy files over SSH, or it can use the rsyncd daemon if you set it up on the
remote system.
The following is an example of synchronizing the files in a local directory to a remote directory
over SSH:
rsync -a /home/mydir/ user@host:/home/mydir/

Linux LPIC-1 934


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 935


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 936


COMPRESSION
Compression is a procedure in which data is encoded to reduce the amount of bits that are
used to represent that data. The compression process can significantly reduce the size of a file
or collection of files to make the storage and transfer of data more efficient. Although the file
takes up less space, it still contains the requisite information so that only redundant data is
removed (lossless compression) or so that only non- critical data is lost (lossy compression).

Compression is commonly used to reduce the storage and transmission burden involved with
creating, maintaining, and recovering from backups. Rather than backing up data one-to-one,
you can compress that data and then store it.

Linux LPIC-1 937


THE gzip COMMAND
GNU zip (gzip) is a compression utility that reduces the size of selected files. Files compressed
with gzip frequently have the .gz file extension. The gzip command has several options. These
command options are described in the following table.
Option Used To
-d Reverse file compression (decompression).
Force compression or decompression of a file even if it has multiple links or if the file
-f
exists.
-n Omit saving the original file name and timestamp.
-N Save the original file name and timestamp.
-q Suppress all warnings.
-r Enable directory recursion during compression or decompression.
-v Display the name and percentage reduction of the compressed or decompressed file.
-t Perform an integrity check on the compressed file.

SYNTAX
The syntax of the gzip command is gzip [options] [file names]

THE gunzip COMMAND


The gunzip command is equivalent to issuing gzip -d at the command-line.

Linux LPIC-1 938


Compressing an archive file with gzip.

Linux LPIC-1 939


THE xz COMMAND
The xz command is a data compression utility, similar to gzip, that reduces the size of selected
files and manages files in the .xz file format. The xz command has several options.

Option Used To
-d Decompress files.
Force compression or decompression of a file even if it has multiple links or if
-f
the file exists.
-q Suppress all warnings.
Display the name and percentage reduction of the compressed or
-v
decompressed file.
-t Perform an integrity check on the compressed file.

SYNTAX
The syntax of the xz command is xz [options] [file names]

Linux LPIC-1 940


Compressing an archive file with xz.

Linux LPIC-1 941


THE bzip2 SUITE
The bzip2 command and its related commands manage file compression. Files compressed
with bzip2 frequently have the .bz2 file extension. The bzip2-related commands are described
in the following table.
Command Used To
bzip2 Compress a file.
bunzip2 Decompress a file.
bzcat Decompress a file to standard output.
bzdiff Run the diff command on compressed files.
bzip2recover Recover data from damaged .bz2 files.
bzless Run the less command on compressed files.
bzmore Run the more command on compressed files.

SYNTAX
The syntax of the bzip2 command is bzip2 [options] {file names}

For example, to compress files file1 and file2: bzip2 file1 file2

Linux LPIC-1 942


Compressing an archive file with bzip2.

Linux LPIC-1 943


THE zip COMMAND
The zip command is another compression utility, but unlike gzip, xz, and bzip2, it also features
file archiving functionality. In fact, zip is a combination of an older compression utility called
compress and the tar archive command. Files compressed with zip frequently have the .zip file
extension. The zip command has several options.

Option Used To

-d Delete entries in a .zip archive.

-e Encrypt the contents of an archive.

-F Fix a corrupted .zip archive.

-r Enable recursion.

-T Perform an integrity check on the archive file.

SYNTAX
The syntax of the zip command is zip [options] [file names]

Linux LPIC-1 944


WHICH COMPRESSION METHOD SHOULD YOU CHOOSE?
Which compression tool to use will often depend on your own particular needs, but some
generalities can be made about each. The most important factors are the speed/ time of
compression and decompression and the compression ratio, which is the size of the
uncompressed file divided by the size of the compressed file (e.g., a 5 MB uncompressed file
that becomes 1 MB when compressed has a ratio of 5:1).

For compression speed, tests tend to show that gzip is slightly faster than bzip2, and both are
significantly faster than xz when the applied compression level increases. For decompression
speed, gzip tends to be the fastest again, with xz and bzip2 as second and third fastest,
respectively. When it comes to compression ratio, xz tends to perform the best, followed by
bzip2, with gzip having the worst ratio.

Ultimately, consider using:


• gzip if you just care about compressing and decompressing files as fast as possible and are
less concerned with storage space.
• xz if storage space is at a premium, and time is not as much of a factor.
• bzip2 to strike a balance, and for data that rarely needs to be decompressed.

Linux LPIC-1 945


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 946


INTEGRITY CHECKING
Integrity checking is the process of verifying that data has not been modified, whether
intentionally or unintentionally, in any way. In other words, an integrity check can validate the
security goal of integrity. It is good practice to perform integrity checking after you finish
compressing and archiving a backup file to confirm that the data has not changed. This will help
you avoid storing corrupted and inaccurate archives for future recovery, only to find out too
late that the data was not properly backed up.

There are several methods that enable you to check data integrity, each of which may vary
based on its security requirements or goals. One of the most common and secure methods of
checking data integrity is through the use of hashing. By calculating the hash of a file like a
backup archive, you can compare that hash to past values, and if both are the same, you can be
reasonably sure the data has not changed in the meantime.

Linux LPIC-1 947


HASH FUNCTIONS
A hash function is an algorithm that performs a hashing operation. There are many different
hash functions, each of which may have its own security strengths and weaknesses. The two
most common hash functions for checking data integrity on Linux systems are MD5 and SHA.

The Message Digest 5 (MD5) algorithm produces a 128-bit message digest. It was created by
Ronald Rivest and is now in the public domain. MD5 is no longer considered a strong hash
function and should be avoided for sensitive operations like storing passwords; however, it is
still used in integrity checking.

The Secure Hash Algorithm (SHA) algorithm is modeled after MD5 and is considered the
stronger of the two. Common versions of SHA include SHA-1, which produces a 160-bit hash
value, while SHA-256, SHA-384, and SHA-512 produce 256-bit, 384-bit, and 512-bit digests,
respectively. SHA-1 is being deprecated due to some security weaknesses.

Linux LPIC-1 948


THE md5sum COMMAND
The md5sum command is used to calculate the hash value of a file or standard input using the
MD5 hash function. You can also use the -c option to specify a file containing MD5 hashes and
the file names they apply to; md5sum will calculate the hashes of the files listed, and then
compare them to the hash values listed. The results will let you know if each file passed, failed,
or could not be found.

MD5 hashes are 128-bits in length. Like many other hash values, they are typically represented
in hexadecimal format (32 characters for MD5). The following is the hash value of the string
"Linux": edc9f0a5a5d57797bf68e37364743831

SYNTAX
The syntax of the md5sum command is md5sum [options] [file name]

Linux LPIC-1 949


SHA COMMANDS
There are several different commands that you can use to calculate SHA hash values. These
commands are functionally identical to md5sum, but use the SHA function with the applicable
bit size:
• sha1sum
• sha256sum
• sha384sum
• sha512sum

SYNTAX
The syntax of the sha#sum commands is sha#sum [options] [file name]

Linux LPIC-1 950


Calculating the hash value of a file.

Linux LPIC-1 951


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 952


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 953


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 954


Writing and using scripts are skills that are absolutely essential to being a Linux® administrator.
Scripts greatly improve efficiency by minimizing the amount of repetitive typing you need to do
at the CLI, and they also enable you to get more work done in a shorter amount of time. While
the idea of scripting and programming in general may seem daunting to some administrators,
Bash makes it surprisingly easy to work with scripts. In this topic, you'll harness the power of
scripts to make you much more productive on the job.

Linux LPIC-1 955


In this topic, you will:

• Customize the Bash shell environment for script execution.


• Identify concepts fundamental to both scripting and programming.
• Write a simple Bash script and then execute it.
• Write more complex Bash scripts that incorporate flow control like conditional statements
and loops.

Linux LPIC-1 956


Linux LPIC-1 957
You've been using the Bash shell, the default Linux shell, all throughout this course. Up until
now, Bash has merely been a means of working at the CLI. However, there is much more you
can do with Bash—for example, you'll start this lesson off by customizing the shell itself.

SHELL ENVIRONMENT
The shell environment is the mechanism by which Bash, or any other shell, maintains settings
and other behavioral details about the shell. The shell creates this environment when starting a
session and uses the environment's settings to determine how to interact with the user.

The process of creating a new session is called shell spawning. This new session is a copy, and
is called the child process. For example, the shell spawns a child process when the user enters a
command. This child process becomes the new process and can also create more processes,
which result in multiple generations of processes. Each process calls upon the shell
environment and passes its details onto the next generation.

Linux LPIC-1 958


Using the Bash shell to spawn a child process.

Linux LPIC-1 959


SCRIPTS
A script is any computer program that automates the execution of tasks for a particular runtime
or shell environment. Scripts are written in scripting languages, which are a subset of
programming languages. Scripts typically do not have the feature set of a full-fledged program,
but instead integrate with other programs and operating system components to achieve
automation. However, the terms are sometimes used interchangeably, and some languages can
be used to write both scripts and full- featured programs.

Linux LPIC-1 960


VARIABLES
Variables refer to entities whose values change from time to time. Most variables are set either
by the operating system when you log in, or by the shell when it is initially invoked. Variables
are the key components that comprise the shell environment. When you want to change the
details of an environment, you change its variables and their values.

In Linux, variables can be categorized as shell variables or environment variables. Shell


variables, by default, do not have their values passed onto any child processes that spawn after
them. Environment variables, on the other hand, do get passed on.

VARIABLE SETTING AND REFERENCING


To set a shell variable, simply enter VAR=value such as MYVAR=123
In order to reference a variable, you must type it in the format ${VARIABLE NAME}
To retrieve the value of a variable, you can enter echo ${VARIABLE NAME} at the CLI.
For example, echo $SHELL will print your default shell (e.g., /bin/bash).

Linux LPIC-1 961


ENVIRONMENT VARIABLES
An environment variable is a variable that is inherited from parent shell processes and is
subsequently passed on to any child processes. An environment variable consists of a name,
usually written in uppercase letters, and a value, such as a path name.
Within the environment, variables are referenced as key–value pairs in the format KEY=value
and KEY=value1:value2 for variables with multiple values.

DEFAULT ENVIRONMENT VARIABLES


Some of the default environment variables and their functions are provided in the following
table.
Environment Variable Specifies
HOSTNAME={hostname} The hostname of the system.
SHELL={shell path} The shell path for the system.
MAIL={mail path} The path where mail is stored.
HOME={home directory} The home directory of the user.
PATH={user path} The search path.
HISTSIZE={number} The number of entries stored in the command history.
USER={user name} The name of the user.

Linux LPIC-1 962


LOCALIZATION ENVIRONMENT VARIABLES
Environment variables can also be used to configure localization options, typically by editing
the /etc/locale.conf file and assigning the appropriate locale to the variable. Some of these
variables are described in the following table.

Environment Variable Specifies


A collection of localization environment variables, including, but
not limited to:
• LC_ADDRESS to set the postal address format.
LC_*={locale} • LC_MONETARY to set the format of monetary
• values.
• LC_MEASUREMENT to set the measurement system (e.g.,
metric vs. imperial).
The locale to use for all LC_* variables that aren't explicitly
LANG={locale}
defined.
The locale to use for all options, overriding any LANG and LC_*
LC_ALL={locale}
values. Typically used for troubleshooting purposes.
The system time zone. This is an alternative to using commands
TZ={time zone}
like date or timedatectl to set the time zone.

Linux LPIC-1 963


THE export COMMAND
You can effectively change a shell variable into an environment variable by using the export
command. For example, if you have a shell variable SHL_VAR, you can enter export SHL_VAR to
make it an environment variable.

You can also change the value of a variable while exporting it, including existing environment
variables. You can do this by entering something similar to export SHL_VAR="New value" at
the CLI. This will set the value for all child processes spawned from this shell.

In order to set the value of an environment variable for all future Bash sessions, you can add an
export statement to your .bash_profile file. To automate this process for new users, and to
ensure those with a similar job roles have the same environment variable settings, you can
modify the .bash_profile file in the /etc/skel/ directory. To set the value of an environment
variable system-wide, add an export statement to the appropriate file in the /etc/profile.d/
directory.

SYNTAX
The syntax of the export command is export [options] [NAME[=value]]

Linux LPIC-1 964


Changing the value of a shell variable.

Linux LPIC-1 965


THE env COMMAND
The env command is used to run a command with modified environment variables. By
supplying the name of a variable and a value in the key–value pair format, as well as supplying
a command to run, you can change the value of the specified variable for that particular
command session. If the variable does not exist, it will be added to the environment. Likewise,
you can use the -u option to remove the specified variable from the environment in which the
specified command runs. Consider using env if you want to override values in child processes or
add new ones.
Issuing the command without any arguments will display all variables in the environment as
well as their corresponding values.
SYNTAX
The syntax of the env command is env [options] [NAME=value] [command]

PRINTING ALL VARIABLES


You can use the set command without any arguments to print all shell variables, environment
variables, and shell functions. This command can also enable the use of options in a shell script
to change its behavior.
COMPARING export, env, AND set
To summarize the difference between these three commands:
• export —Change the value of a variable for all child processes.
• env —View environment variables or change the value of a variable for a specified
command.
• set —View shell variables or change the value of shell attributes

Linux LPIC-1 966


Listing environment variables and their values.

Linux LPIC-1 967


SEARCH PATHS
A search path is a sequence of various directory paths that is used by the shell to locate files.
Paths can be assigned to the PATH environment variable. The PATH variable comprises a list of
directory names separated by colons. You can add a new path to an existing group of path
names, modify a path, or delete a path.

Usually, directories that contain executable files are assigned to the PATH variable. This enables
you to enter the name of an executable at the CLI without needing to specify its full directory
path. This is because the PATH variable searches its directories for the name of the executable.

Linux LPIC-1 968


HISTFILESIZE
HISTFILESIZE is an example of a shell variable that enables you to set the maximum number of
lines contained in the command history file. It also enables you to specify the number of lines
to be displayed on running the history command. For example, by assigning a value of 20 to this
variable, the history file gets truncated to contain just 20 lines. The default value of this variable
is 1000.

Linux LPIC-1 969


THE alias COMMAND
The alias command is used to customize the shell environment by generating command-line
aliases. Aliases are shorthand for longer expressions. Using aliases, you can create a short string
that represents a longer command with various options and arguments. For example, you can
create an alias called myls that executes the ls - al command.
The Bash shell maintains a list of aliases that you can view by using the alias command by itself.
You can also remove aliases using the unalias command. By default, aliases are only maintained
for the current shell and for the user that created them. To have them persist, add the
appropriate alias command to .bashrc or .bash_aliases, which is called by .bashrc.

SYNTAX
The syntax of the alias command is alias [alias name[='command with options']

Linux LPIC-1 970


Creating an alias for a command expression.

Linux LPIC-1 971


THE time COMMAND
The time command is used to gather information about how long it took to execute a
command, as well as some additional statistics about the I/O and memory used in command
execution. You provide the command you want to time as an argument to the time command.
By default, the command outputs the following time statistics:
• The real time that elapses between the command's invocation and its termination.
• The user CPU time; i.e., the time spent running code in user space.
• The system CPU time; i.e., the time spent running code in kernel space.

By finding out how long it takes a command to run, you can get a better idea of how to
optimize frequent tasks. Some commands may complete the same task faster than other
commands.

SYNTAX
The syntax of the time command is time [options] {command}

Linux LPIC-1 972


Timing a command.

Linux LPIC-1 973


ENVIRONMENT AND SHELL TROUBLESHOOTING
You may encounter some issues when using or customizing the Bash shell environment. The
following are some troubleshooting tips.
• When adding an alias, check the syntax. For example: ls='ls -la'
• When executing scripts or other programs, if they are not stored in the normal
• locations for executable files, then add their location to the PATH variable or execute them
with a ./ preceding the command.
• Use the export command to set a variable for all shell child processes.
• Configure environment variables in the ~/.bash_profile file to make the variable available to
all shells. For example, if a service account requires certain environment variables, you can
set them in the ~/.bash_profile for that account.
• Edit the ~/.bash_profile file to change default variables.
• Ensure values are set for any environment variables that a software package has a
dependency on. For example, if a Java application relies on the Java runtime environment, it
may only be able to find and access that runtime environment if it is referenced in the PATH
variable.

Linux LPIC-1 974


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 975


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 976


Linux LPIC-1 977
Before you dive into scripting with Bash specifically, you need to familiarize yourself with some
basic concepts that are shared by many scripting and programming languages used today.
These concepts will lay the groundwork for writing your own scripts.

BASH SCRIPTING
Not only is Bash the default shell in Linux, but it is also a powerful scripting language. Creating
Bash scripts is incredibly useful in increasing the efficiency and productivity of your Linux
administration tasks. Bash scripts can make Linux system calls and leverage existing tools in the
user space. Essentially any program, tool, utility, or system function that you can call at the
command-line you can also invoke in a Bash script. Likewise, Bash scripts support modern
programming elements like loops and conditional statements to enhance the logic of the
task(s) being automated.

Linux LPIC-1 978


SYNTAX
Just as commands at the CLI have a syntax, so too do scripting languages. A language's syntax
are the rules that define how you write the code. Each language has its own syntax, but many
share a few commonalities. Because of its association with the underlying Linux operating
system, the syntax of a Bash script is very similar to what you'd input line-by-line at a CLI.

Linux LPIC-1 979


VARIABLE ASSIGNMENT
Variable assignment is the act of defining a variable as having a certain value. In code, you
assign values to variable names. The values in a variable may change throughout the script's
execution, but this is not required. The purpose of variables is to store values for later use, and
to enable you to reference these values without explicitly writing them out in the code.

Many programming languages, like C, require you to define the type of variable before you
assign it to a value. Examples of types include integers, floats, strings, and more. Essentially,
these types define exactly what kind of information the variable holds. However, you don't have
to declare variable types in Bash. Instead, all Bash variables are treated as strings.

BASH VARIABLE ASSIGNMENT


Bash variables are assigned as follows.
my_str='Hello, World!'
Note the lack of whitespace around the equals sign—this is a strict rule in Bash.

Linux LPIC-1 980


VARIABLE SUBSTITUTION
The act of referencing or retrieving the value of a variable is called substitution or parameter
expansion. After you assign a value to a variable, you reference that variable later in the code
so that you don't need to hard-code values into the script's logic.

BASH VARIABLE SUBSTITUTION


When referencing variables in Bash, you need to add a dollar sign ($) at the beginning of the
variable name:
my_str='Hello, World!'
echo $my_str

This will print "Hello, World!" to the console.

Linux LPIC-1 981


COMMON OPERATORS
Operations enable you to perform some sort of task on the variables and values that you
specify in your code. In most cases, this task is the evaluation of an expression. Operators are
the objects that can evaluate expressions in a variety of ways. Operands are the values being
operated on. There are many different kinds of operators that apply to most languages,
including:
• Arithmetic operators. These include addition, subtraction, multiplication, division, and more
advanced mathematical operations.
• Comparison operators. These include checking if operands are equal, if one operand is less
than or greater than another operand, and more.
• Logical operators. These operators connect multiple values together so they can be
evaluated, and include AND, OR, and NOT.
• String operators. These are used in operations that manipulate strings in various ways,
including concatenating strings, returning a specific character in a string (slicing), verifying if
a specific character exists in a string, and more.

Many languages find common ground when it comes to representing operators in code. For
example, in many languages, the == comparison operator evaluates whether or not the
operands have equal values. Therefore, the expression 1 == 2 outputs to false. Note that this
particular operator is distinct from a single equals (=), which is used in assigning values to
variables.

Linux LPIC-1 982


However, some languages do not use the traditional symbols for comparison
operators. Instead, they use a letter-based syntax. For example, consider that the >=
operator evaluates whether the left operand is greater than or equal to the right
operand. In letter-based syntax, the operator is -ge. So, 1 -ge 2 outputs to false.

BASH OPERATIONS
The following is an example of an arithmetic operation in Bash. Note that expressions
are evaluated when wrapped in double parentheses: $((var1 + var2))
An example of a comparison operation in Bash. Note the use of square brackets and a
letter-based operator: [ $var1 -ge $var2 ]
An example of a logical operation (AND) in Bash: [ $var1 -ge $var2 ] && [ $var3 -le
$var4 ]
An example of a string operation (concatenation) in Bash: $var1$var2

Linux LPIC-1 982


STRING LITERALS
A string literal is any fixed value that represents a string of text within source code.
String literals are enclosed in single (') or double (") quotation marks. As long as you are using
them consistently, using either single or double quotation marks is acceptable for basic string
output. However, there are circumstances where double quotes won't preserve the literal value
of all characters within the quotes.

For example, say you've defined the my_str variable mentioned previously. You then want to
substitute this variable into a larger string literal, like so:
echo "My variable is $my_str”
echo 'My variable is $my_str’

The first line, because it is using double quotes, will print "My variable is Hello, World!" The
second line, because it uses single quotes, will literally print "My variable is $my_str".
Therefore, you must be careful to use the correct type of quotation mark depending on what
your intent is.

WHEN TO USE STRING LITERALS


It's not always necessary to use a string literal. If you don't wrap the previous echo example in
quotation marks, then it will by default produce the same output as if you had wrapped it in
double quotes. However, it's still good practice to wrap strings of text in quotes just to be sure.
When you assign values with spaces in them to variables, you are required to use quotes.

Linux LPIC-1 983


ESCAPE CHARACTER
In any language, Bash included, certain characters have special meaning. An escape character is
used to remove that special meaning so the character can be used literally rather than
interpreted as something else by the system. This is similar to using a string literal, but in the
case of an escape character, you're only removing the special meaning from one character at a
time.

In Bash, the escape character is a single backlash (\). For example, let's say you want to print a
string to the command-line that actually contains a dollar sign. The dollar sign, as you know, has
a special meaning—it is used in variable substitution. You can handle this by using single
quotation marks, as so:
echo 'This $var is escaped’

Alternatively, if you wanted to use double quotes or no quotes at all, you could enter either of
the following:
echo "This \$var is escaped"
echo This \$var is escaped

Notice how the backslash escape character precedes the dollar sign, which is the character you
want to be interpreted literally.

Linux LPIC-1 984


ARRAYS
An array is a collection of values. In other words, an array enables you to store multiple values
in a single variable. This can make your code much easier to read and maintain. For example,
you might want to perform a single mathematical operation on dozens of different values.
Instead of creating a variable for each value, you can create an array to simplify your code.
Another benefit of arrays is that you can easily update their values throughout the code.
Arrays are ordered based on their indices. Most languages start an array with an index of 0.
When you assign values to an array, you can usually perform a compound assignment to assign
all values at once. The order you place each value in the compound assignment will determine
its index—i.e., the first value will be at index 0, the second at index 1, and so on. Languages like
Bash can also use individual assignment to assign specific values to each index one-by-one.
BASH ARRAYS
Compound assignment in Bash arrays uses parentheses with each value separated by a space:
my_arr=(1 "Hello" 3.1)
Individual assignment adds a value to a specific index in brackets:
my_arr[0]=1 my_arr[1]="Hello" my_arr[2]=3.1
You can reference an array by wrapping it in curly braces. You can reference a specific index of
the array:
echo ${my_arr[0]}
This will print "1". You can also reference all of the values in an array by using the asterisk (*) or
at symbol (@) in place of the index:
echo ${my_arr[*]}

Linux LPIC-1 985


FUNCTIONS
A function is a block of code that you can reuse to perform a specific task. This is useful in
writing efficient code, as calling a function can save you from having to write out the same or
similar code over and over. You can define your own functions that you can call in other parts of
the script, or even call from other scripts.
Like variables, you define a function with a unique identifier. You use this identifier to reference
the reusable code within the function.

BASH FUNCTIONS
In Bash, there are two ways of writing functions. Both involve placing the desired code in
between curly braces. The first method is:
function my_func {
code...
}
If you're familiar with object-oriented programming languages like C, you might be more
comfortable with the second method:
my_func() {
code...
}
However, note that the open and closed parentheses are just there for visual clarity. In Bash,
you don't pass in arguments to a function like you would with other programming languages.
Instead, you pass in arguments similar to how you would at the command-line.

Linux LPIC-1 986


COMMENTS
In the world of programming, comments are a method of annotating source code so that it is
easier for the author and other programmers to understand. In most languages, comments are
ignored by the system that compiles, interprets, or otherwise executes the program. They
therefore exist as a way to document various elements of the code within the code itself.
In Bash, the number sign (#) indicates that every character after it on that line is part of a
comment, and not to be executed. Although you are free to comment your code how you want,
it's usually good practice to include one or more comment lines at the top of the script that
explain what that script does, and to comment each line or code block that may require
explanation. You should refrain from commenting on a line of code whose purpose is obvious,
as too many comments can clutter the source code and can actually make it harder to
understand.

BASH COMMENTS
The following is an example of a short script with comments:

# This script determines how many files are remaining to process in a directory.

num_files=432 # current number of files processed


total_files=512 # total number of files to process

echo "There are $((total_files - num_files)) files remaining."

Linux LPIC-1 987


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 988


Linux LPIC-1 989
Now you're ready to begin writing and executing your own Bash scripts. In this topic, you'll
implement some fundamental components of Bash scripting in order to create a simple
working executable.

#!/bin/bash
Bash scripts contain shell-specific instructions that may not be compatible with other Linux
shells. This will result in a Bash script running on Bash shells correctly, while failing on other
non-Bash shells in Linux. To specify that your script is written for the Bash shell, you need to
add the line #!/bin/bash at the beginning of each script. This line will instruct the operating
system to use the Bash shell interpreter when executing a script on an incompatible Linux shell.

Linux LPIC-1 990


METACHARACTERS
Metacharacters are special characters that the Bash shell will, by default, interpret in a certain
way. These are characters you must escape or enclose in quotes in order for them to be
interpreted literally. The metacharacters in Linux are described in the following table. Several of
these should look familiar.

Metacharacter Used In
> Output redirection.
>> Output redirection (append).
< Input redirection.
<< Input redirection (here documents).
| Piping.
" Defining weak string literals.
' Defining strong string literals.
` Breaking out of string literal to run command between backticks.
\ Escaping characters.
= Variable assignment.

Linux LPIC-1 991


Metacharacter Used In
$ Variable substitution and other types of shell expansion.
# Commenting.
|| Logical OR operations.
&& Logical AND operations.
* Wildcard matching (any number of characters).
? Wildcard matching (single character).
[] Wildcard matching (any characters between brackets).
{} Parameter substitution and arrays.
() Grouping commands.
& Running processes in the background.
; Separating multiple commands on same line.
! Referencing command history.

Linux LPIC-1 992


EXIT CODES
An exit code, or exit status, is a value that a child process passes back to its parent process
when the child process terminates. In the Linux world, a status code of 0 indicates that the
process executed successfully. The exit code 1 or any number higher indicates that the process
encountered errors while executing.
Many Bash scripts call upon other scripts or enable the user to leverage system commands with
the script. Exit codes are useful because they can help these external entities detect whether or
not initial script execution was successful, and then potentially change their behavior based on
this exit code.
By default, a Bash script will generate an exit code of the last command that was run. You can
also specify exit code behavior yourself. The exit code of the last run command is represented
by the $? special variable. You can, for example, redirect the exit code to standard output
(stdout) and/or standard error (stderr). For example:
#!/bin/bash
chmod 888 file
echo $? >&2
This will redirect the exit code 1 to stderr. Likewise, you can use input redirection to take an exit
code from standard input (stdin) into a Bash script.

THE exit COMMAND


You can use the exit command in a script to force the shell to terminate with whatever exit
code you provide. For example, exit 1 will cause the script to terminate with a failure status. If
you don't provide a number, exit will terminate with the exit code of the last command that
was run.

Linux LPIC-1 993


REDIRECTION AND PIPING
Just as you can take advantage of redirection and piping at the CLI, so too can you incorporate
them in your scripts. Other than redirecting exit codes to stdout/stderr/stdin, you can also
redirect data to and from files. For example, the following script uses the read command to
prompt a user for input, assigns that input to a variable, then appends the data to a file:
#!/bin/bash
echo 'What is your name?’
read name
echo $name >> name_list.txt

Likewise, you can pipe to other commands from within a script. The following example reads a
text file of names (cat), pipes that text to search for a particular name (grep) , then pipes that
to a command that identifies the total count of that name (wc).
#!/bin/bash
cat name_list.txt | grep 'John' | wc -l

Linux LPIC-1 994


SHELL EXPANSION
When a command is issued at the Bash shell, it is split into tokens, or words. Shell expansion is
the process by which the shell identifies special tokens that it substitutes values for. Variable
substitution is a type of shell expansion by which the shell identifies the $ special character and
then expands a variable into its actual value. In other words, in echo $var, the echo command
doesn't "see" a variable; it sees whatever the value of that variable is when Bash expands it.
ORDER OF EXPANSIONS
There are actually several more types of expansions—eight in total. Bash performs these
expansions in a defined order, similar to an order of operations in a mathematical expression.
That order is:
1. Brace expansion
2. Tilde expansion
3. Same time:
• Parameter expansion/variable substitution
• Arithmetic expansion
• Command substitution
• Process substitution
4. Word splitting
5. File/path name expansion

For the four expansions that happen at the same time, the expansion is done in left-to-right
order as each appears.

Linux LPIC-1 995


VARIABLE SUBSTITUTION WITH BRACES
As you've seen, the format $var is an expansion that will substitute a variable with its value.
However, let's say you have the following code:
word=computer
echo "The plural of $word is $words."
This will print: The plural of computer is . This is because Bash expects a variable that is exactly
named $words even though you just intended to add a letter to the actual value. You can get
around this by enclosing the variable in braces, as such:
word=computer
echo "The plural of $word is ${word}s."
So, this will print: The plural of computer is computers.

Linux LPIC-1 996


COMMAND SUBSTITUTION
Command substitution is a method of shell expansion in which the output of a command
replaces the command itself. This is useful when you want to include a command's output
within an existing string of text. For example:
echo "The current directory is `pwd`."
Notice that the command pwd is enclosed within backticks (`). Depending on what the CWD
actually is, the output might be something like: The current directory is /root.

You can also use the format $(command) to perform command substitution, as in the
following:
echo "The current directory is $(pwd). "

Linux LPIC-1 997


GLOBBING
Globbing is another name for file/path name expansion. This method of shell expansion is used
to replace a specific wildcard pattern with values that match the pattern. There are three
special characters used in globbing: the asterisk (*) used to match any number of characters;
the question mark (?) used to match a single character; and characters within square brackets ([
]) to match any of the characters listed.
The following are three examples of globbing:
cp *.txt ~/dest
cp ?.txt ~/dest
cp [abc].txt ~/dest

The first example copies any and all files with a .txt extension. This is because the wildcard
character appears before the period, indicating that Bash should expand any possible
combination of characters. The second example will only copy .txt files with a single character
as a name, like a.txt and b.txt, but not ab.txt. The third example will only copy files named
a.txt, b.txt, or c.txt.

Linux LPIC-1 998


POSITIONAL PARAMETERS
A positional parameter is a variable within a shell script that is assigned to an argument when
the script is invoked. For example, you can invoke a script myscript.sh like so:
myscript.sh arg1 arg2 arg3
The arg1 argument corresponds to the positional parameter $1, arg2 corresponds to $2, arg3
corresponds to $3, and so on. Note that the space between arguments is used to separate
positional parameters.
You can reference positional parameters directly in your scripts like you would any other
variable:
#!/bin/bash
echo "The first argument is $1"
echo "The second argument is $2"
echo "The third argument is $3"
This is useful because your script can perform various operations on any arguments that are
passed to it, as most scripts and commands do.
SETTING POSITIONAL PARAMETERS
You can also set positional parameters directly in your scripts by using the set command. For
example:
#!/bin/bash
set -- arg1 arg2 arg3
echo "The first argument is $1"
echo "The second argument is $2"
echo "The third argument is $3"

Linux LPIC-1 999


When this script is invoked without any arguments provided by the user, it will still
have positional parameters $1, $2, and $3, because they were set manually.

Linux LPIC-1 999


THE exec COMMAND
The exec command is used to execute another command, replacing the current shell process
with this new program's process (no new process is created). This can be useful when you want
to prevent the user from returning to the parent process if an error is encountered. For
example, you may want to terminate a privileged shell if a command fails.

You can also use the exec command without a command as an argument to redirect all output
in the shell to a file. This is commonly used in scripts to suppress stdout at the CLI and instead
send it only to one or more files. For example:
#!/bin/bash
exec > out.txt
pwd
ls -al

The current working directory and directory listing will output to out.txt and not the CLI.

Linux LPIC-1 1000


THE source COMMAND
The source command is used to execute another command within the current shell process. In
this sense, it performs the opposite functionality of the exec command. This is useful when
you'd like to stay within your current shell when executing a script. One example is sourcing a
script that performs a change of directory (cd). After the script executes, your location will be
whatever directory was changed to, whereas executing the script normally would keep you
where you are.

Another situation where you might want to source a script is when your script changes or
defines environment variables. For example, the following script (export.sh) exports a custom
environment variable named MYVAR:
#!/bin/bash
export MYVAR=1

If you execute this script normally and issue the env command, you'll see that MYVAR is not
listed. This is because the script spawned a new shell process, and once it terminated, its
changes to the shell environment were destroyed. However, if you enter the command source
export.sh then the environment variable will be maintained because the script executes in your
current shell.

Linux LPIC-1 1001


SCRIPT FILE EXTENSIONS
For the most part, file extensions in Linux are optional. Linux checks a file's metadata to
determine what type of file it is. This goes for Bash scripts as well—you don't need to name
your scripts with an extension. However, many developers have adopted the convention of
adding .sh as an extension to their shell scripts, such as myscript.sh. While this does not imbue
the script with any special meaning, it can make it easier for a person to identify that a file is
indeed a script at a glance. Including a file extension can also help search operations in which
you only want to look for or within shell scripts.

Linux LPIC-1 1002


SCRIPT PERMISSIONS
Remember, your ability to use any file, including a script, is constrained by the permissions
assigned to that script. Even though you created the script, you won't automatically have
permission to run it. You need to make sure two permissions are set for each user that needs to
run the script:
• The execute (x) bit on the script itself.
• The write (w) and execute (x) bits on the directory containing the script.

You can set these permissions using chmod just as you would with any other file.

Linux LPIC-1 1003


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1004


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1005


Linux LPIC-1 1006
Some scripts can remain simple, but the true power of scripting comes from being able to
control the flow of logic as it executes. In this topic, you'll augment your scripting skills through
the use of conditional statements and loops.

LOGIC AND CONTROL STATEMENTS


A script's logic determines how it will process written code during execution. In Bash, as in
most languages, there are various ways to design the logic of the code to essentially accomplish
the same results in execution. Logic is therefore important in maximizing the efficiency and
readability of code.
One of the most important components for implementing programming logic is a control
statement. A control statement begins a section of code that will define the order in which
instructions are executed. By controlling the flow of these instructions, you can write scripts to
follow one or more paths based on certain circumstances.

Linux LPIC-1 1007


CONDITIONAL STATEMENTS
A conditional statement is a control statement that tells the program it must make a decision
based on various factors. If the program evaluates these factors as true, it continues to execute
the code in the conditional statement. If false, the program does not execute this code.

Conditional statements are fundamental to most programs and scripts, as they help you control
the flow of executed code. For example, if a user enters some input, you might want to process
that input differently based on a number of factors. The user might supply one argument and
not another. Rather than executing the script as if all possible arguments were intended, you'd
only execute the script with the argument the user supplied.

Linux LPIC-1 1008


The basic flow of a conditional statement.

Linux LPIC-1 1009


THE if STATEMENT
In most languages, including Bash, the primary conditional statement is the if statement. An if
statement contains a condition to be evaluated and one or more actions to be performed, if the
condition is satisfied. If the condition is not satisfied, the actions are skipped and the next
statement in the script is executed. In Bash, the end of the set of instructions is indicated by the
fi statement.

The following is an example of a simple if statement:


var=5
if [ $var -gt 1 ]
then
echo "$var is greater than 1!"
fi

Linux LPIC-1 1010


The if statement includes, between two square brackets, a condition to be evaluated. In this
case, it's whether or not the $var variable is greater than 1. On the next line is the then
statement, within which is the code that will be executed if the prior condition is true. Lastly,
the fi statement indicates the end of the entire if statement.

Because 5 is greater than 1, the message will echo to the screen. If it were not true, then
nothing would happen.

SYNTAX
The basic syntax of an if statement is as follows:
if [ <condition to be evaluated> ]
then
<code to execute if condition is true>
fi

Linux LPIC-1 1011


THE if...else STATEMENT
The if...else statement enables a choice between two actions based on the evaluation of a
condition. If the condition is satisfied, the first action is performed; otherwise, the action
following the else segment is performed. If there are more than two sets of instructions, one or
more elif statements may be used to specify alternative sequences of action.

The following is an example of a simple if...else statement:


var=1
if [ $var -gt 1 ]
then
echo "$var is greater than 1!"
else
echo "$var is less than or equal to 1!"
fi

Linux LPIC-1 1012


The value of $var has changed since the previous example, which means that the first echo
command won't execute. Rather than nothing happening, the else statement specifies what
will happen if the condition is false: in this case, it is to print a different message to the screen.

SYNTAX
The basic syntax of an if...else statement is as follows:
if [ <condition to be evaluated> ]
then
<code to execute if condition is true>
else
<code to execute if condition is false>
fi
The basic syntax of an if...elif statement is as follows:
if [ <condition to be evaluated> ]
then
<code to execute if condition is true>
elif [ <other condition to be evaluated> ]
then
<code to execute if other condition is true>
fi

Linux LPIC-1 1013


THE case STATEMENT
There may be times when you want to evaluate numerous conditions, such as a variable that
can hold many different values, and each value requires its own action. You could define
multiple elif branches in an overall if statement, but this can make your code difficult for a
human to parse. The case statement helps you avoid this issue.

SYNTAX
The basic syntax of a case statement is as follows:
case <variable> in
<first condition>)
<code to execute if first condition is true>
;;
<second condition>)
<code to execute if second condition is true>
;;
esac

Linux LPIC-1 1014


The following is an example of a simple case statement:
var=blue

case $var in
red)
echo "Your color is red.”
;;
green)
echo "Your color is green."
;;
blue)
echo "Your color is blue."
;;
*)
echo "Your color is neither red, green, nor blue."
;;
esac

Linux LPIC-1 1015


The first line in the case statement defines what variable it is that you're evaluating. Below that
is the first condition, red, which has a closing parenthesis to indicate the end of the condition.
On the next line is the action that will be performed if the color is indeed red—a message will
display on the screen saying as much. The double semicolons (;;) indicate the end of the action.

This pattern is repeated, and can go on for as many conditions as you'd like. In this case, the
last condition uses a wildcard (*) to indicate that if the variable doesn't match any of the
conditions above, then the following action will execute. The esac statement ends the case
statement.
THE test COMMAND
The test command is used to check conditional logic and perform comparisons. You can use the
test command in your shell scripts to validate the status of files and perform relevant tasks. It
evaluates a conditional expression or logical operation and displays an exit status. The exit
status is 0 if the expression is true and 1 if the expression is false.
For example:
var=/etc
if test -d $var;
then
echo "The $var directory exists!"
fi
This example uses the -d option to test if a directory exists. There are many such conditional
options you can use. Consult the man page for the test command to see them all.

Linux LPIC-1 1016


LOOPS
Aside from conditional statements, another useful way to control the flow of logic in a script's
code is by implementing loops. A loop is any control statement that executes code repeatedly
based on a certain condition. In general, loops are a great way to keep a certain block of code
active until no longer needed. There are three types of loops supported by Bash: the while
loop, the until loop, and the for loop. All three types of loops are enclosed within the do and
done statements.

Linux LPIC-1 1017


The basic flow of a loop.

Linux LPIC-1 1018


THE while LOOP
The while loop enables you to repeat a set of instructions while a specific condition is met. The
expression is evaluated, and if the expression is true, the actions in the loop are performed. The
execution returns to the beginning of the loop and the expression is evaluated again. If the
expression becomes false at any point, the execution breaks out of the loop and continues to
the next block of code in the script.

The following is an example of a simple while loop:


var=1
while [ $var -le 5 ]
do
echo "The current number is $var."
((var++))
done

SYNTAX
The basic syntax of a while loop is as follows:
while [ <condition to be evaluated> ]
do
<code to execute while condition is true>
done

Linux LPIC-1 1019


In this case, the condition being tested is whether or not the variable $var is less than or equal
to 5. As long as it is (i.e., the expression is true), then the code under do will execute. Below the
echo command is an iterator, which simply adds 1 to the variable. This is common in any kind of
loop, as without it, $var will always equal 1 and will therefore never break out of the loop.

Linux LPIC-1 1020


THE until LOOP
The until loop is similar to the while loop, except that the code is executed when the control
expression is false.
For example:
var=1
until [ $var -ge 5 ]
do
echo "The current number is $var."
((var++))
done
The condition in this loop is whether or not $var is greater than or equal to 5. So, the code will
execute until $var becomes 5, at which point it will break out of the loop.
SYNTAX
The basic syntax of an until loop is as follows:
until [ <condition to be evaluated> ]
do
<code to execute while condition is false>
done

Linux LPIC-1 1021


THE for LOOP
The for loop executes a block of code as many times as specified by a numerical variable that is
within the conditional part of the statement. Unlike a while or until loop, a for loop does not
depend upon a condition being evaluated to false or true for it to stop or never begin in the
first place. So, for loops are meant to always execute code a given number of times. This makes
them ideal for processing iterable objects like arrays.
The following is an example of a simple for loop:
var=("Carla" "Robert" "Mary")
for i in ${var[*]}
do
echo "$i is a member of the team."
done

SYNTAX
The basic syntax of a for loop is as follows:
for i in <variable to loop through>
do
<code to execute a specific number of times>
done

Linux LPIC-1 1022


The for statement evaluates every value in the $var array. In this case, each value is
represented by the iterator i, though you can call this whatever you want. It's common to name
it something similar to the variable you're looping through, or to simply call it i for iterator.

Then, the loop itself will execute three times—one for each value in the array. So, each person's
name will be echoed to the screen.

LOOPING THROUGH RANGES


The for loop is also used to step through a range of numbers. These ranges are enclosed in
curly braces, with the range itself indicated by two periods (..).
For example:
for i in {1..5}
do
echo "The current number is $i."
done
So, this loop will iterate exactly five times.

Linux LPIC-1 1023


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1024


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1025


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1026


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1027


Bash scripting goes a long way toward automating your administrative duties on Linux®. But
there are plenty more methods of automating the tasks you perform every day. These methods
can further improve your productivity and lead to an overall boost in task accuracy and
usefulness. As time goes on, you'll rely less and less on manual administration.

Linux LPIC-1 1028


In this topic, you will:

• Run jobs on a set schedule.


• Implement version control for files using Git.
• Identify concepts fundamental to orchestration.

Linux LPIC-1 1029


Linux LPIC-1 1030
Some tasks need to be performed repetitively on a set schedule. By scheduling these tasks, you
won't need to remember to execute them manually, and you won't need to be able to access
the system at the given times.

THE at COMMAND
The at command is used to run a task once, at a specified time. It is not designed for repetitive
or regularly scheduled tasks. The at command is very flexible. Users can specify a particular
date and time, or cause the scheduled command to run after a given period of time.

The command is typically used in an interactive manner, where the at command and time
interval are specified, then a task is defined in an interactive prompt. This enables the user to
enter a path to a script or a command to be run. Pressing Ctrl+D exits the interactive mode.

SYNTAX
The syntax of the at command is at [options] {time}

Linux LPIC-1 1031


at COMMAND OPTIONS
Some of the at command options are described in the following table.
Option Used To
-m Send mail to the user when the job completes, regardless of output.
-M Prevent mail from being sent to the user.
-f { file name} Read a job from a file rather than standard input.
-t {time} Run the job at the specified time value.
-v Display the time the job will be executed.

TIME SPECIFICATIONS
The at command takes several possible arguments for specifying time. Examples include:
• noon to specify 12 P.M.
• teatime to specify 4 P.M.
• midnight to specify 12 A.M.
• now + 3 minutes to specify the time three minutes from now.
• now + 1 hour to specify the time one hour from now.

RELATED COMMANDS
The atq command can be used to view the current queue of tasks scheduled by the at
command. The atrm command can be used to delete a scheduled task.

Linux LPIC-1 1032


CRON JOBS
Administrators and users may want to have scripts or commands execute on a regular basis.
Automation of these kinds of tasks is efficient and consistent. The cron daemon is used to
manage these scheduled tasks called cron jobs.

The cron daemon checks its crontab configuration file each minute to discover whether there
are any tasks to be accomplished. If there are, it executes them. If there are not, it goes back to
sleep until the next minute.

Cron jobs can be used to specify tasks each minute, hour, day, month, and any day of the week.
This makes them extremely flexible.

Linux LPIC-1 1033


THE crontab COMMAND
The cron daemon is controlled using the crontab command. The command assumes the
current user unless the -u option is specified. You can create, view, and delete crontab files
using the crontab command.

SYNTAX
The syntax of the crontab command is crontab [options] [file/ user]

Some of the options of the crontab command include:

Option Used To
-e Edit the crontab file for the current user.
-l View the crontab file for the current user.
-r Delete the current crontab file.
-u Create a crontab file on behalf of the specified user.

Linux LPIC-1 1034


Viewing a user's crontab file.

Linux LPIC-1 1035


THE crontab FILES
The crontab files are referenced by the cron daemon to determine what scheduled tasks might
exist. The crontab files are managed using the crontab -e command. This command opens a
text editor (Vim by default on most systems), enabling users to specify when they want a task
run, and what task it is.

Linux LPIC-1 1036


The format of crontab entries.

The following are examples of lines in a crontab file that schedule tasks at certain times:
* 20 * * 1-5 /path/to/command —executes the command at 8 P.M., Monday through Friday.
15 2 * * * /path/to/command —executes the command at 2:15 A.M., daily.
30 4 1 * * /path/to/command —executes the command at 4:30 A.M. on the first day of each
month.

Linux LPIC-1 1037


CRON DIRECTORIES
The crontab files that contain scheduled task information can be found in
the /etc/cron.d/ directory and in the /var/spool/cron/ directory. The root user can schedule
system-wide tasks by using the /etc/cron.d/ directories. Services may also add scheduled tasks
at this location. The root user can add tasks to the directory or can add tasks to the
/etc/crontab file.

Regular users are not allowed to populate the /etc/cron directories, so each standard user can
schedule their own tasks in a personal directory located at /var/spool/cron. Any tasks listed
here will execute with the standard user's credentials.

The /etc/ directory also contains several default cron directories that administrators can use to
place scripts to be executed on a regular basis. These directories
are /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly,and /etc/cron.monthly. Link or copy a
script into these directories to use their schedule to run your commands.

Some Linux distributions pre-populate the /etc/crontab file with particular tasks. You may find
that logrotate, tmpwatch, rkhunter (Rootkit Hunter), etc., may already be present. The
installation of these kinds of services may also include the creation of /etc/crontab entries.

Linux LPIC-1 1038


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1039


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1040


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1041


Linux LPIC-1 1042
If you or your colleagues are developing software, they'll need some place to store and manage
the source code. This can quickly become an overwhelming task, especially when many
versions of the code are involved. In this topic, you'll automate code management and version
control through a program called Git.

GIT
Git is a distributed version control system primarily used by developers who are collaborating
on projects. Git was developed by Linus Torvalds, the same person who created Linux. Git is the
standard version control program in the development world today. It is often integrated with
development editors.

The core component of Git is the Git repository. This is a storage area where versions of code
and related files are stored. Version control is managed within this local directory. The
repository may be stored on a single developer's workstation, or this repository may be
centrally stored and then cloned to the developer's workstation. Organizations may choose to
have a centralized Git repository on premise, or to use an online solution like GitHub. A
centralized repository is not required, however.

To get started with Git, use an available package manager to install the git package.

Linux LPIC-1 1043


THE git COMMAND
The git command is used to manage Git repositories. Using git you can create a repository, add
files to the repository, commit changes to the repository, pull down files from another
repository, and much more. You can perform these tasks by issuing various subcommands
within the larger git command.

SYNTAX
The syntax of the git command is git [options] {subcommand}

Linux LPIC-1 1044


git SUBCOMMANDS
The following are some of the major subcommands that you can use with the git command.
Subcommand Used To
config Set options for a repo, Git users, or global.
init Create or reinitialize a repo.
clone Create working copy of a repo.
add Add files to be tracked by repo.
commit Update repo with your changes.
status Display status of repo.
branch Manage branches (pointers to specific repo snapshots).
merge Integrate changes from one branch into "master" branch.
pull Acquire and merge changes made to other repos and branches.
push Upload local working copy of a repo to a remote repo.
log Display changes made to local repo.
checkout Switch to specific branch.

Linux LPIC-1 1045


EXAMPLE GIT PROCESS FOR LOCAL REPOSITORIES
The following is an example process flow for creating a local repository and committing
changes to it:
1. Configure global settings, including a user name, email address, etc.:
a. git config --global user.name 'User’
b. git config --global user.email '[email protected]'
2. Create a directory where your project will reside. Change into that directory, and then
initialize it with Git to designate it as a Git repository:
a. mkdir /dev-project
b. git init /dev-project
3. Add project files to the repository. These are the files that make up the actual development
project you are storing and controlling with Git. Just as you have seen with Linux
configuration files, in development projects you want to work with copies of the project,
not the original file itself. That makes it far easier to roll back to the original project in the
event of a mistake. In Git, you create a working copy by using the clone subcommand:
git clone /dev-project
4. Add project files to the Git tracking system:
git add myfile
5. Commit the changes to take a snapshot of your project. At this stage, you can also enter a
message that summarizes what changes you made. Make sure these messages are clear:
git commit -m 'Initial commit'
6. Retrieve the current status of changed files. If three files were being worked on for a

Linux LPIC-1 1046


particular step in the project, but only two were ready to be committed at this
time, they would show up here as "added" but not yet committed. The commit
process could be executed once edits to all three files are complete:
git status

BRANCHING
Optionally, you can work with Git branches:
1. Create a branch of the master copy of the code:
git branch newbranch
2. Make changes, and then integrate (merge) those changes back into the master
branch. This integrates the changes, creating a new-and-improved version of the
original. At this point, the branch that was being used to create the changes can
be removed. The changes are now in the master branch:
git merge newbranch

Linux LPIC-1 1046


EXAMPLE GIT PROCESS FOR COLLABORATION
The following is an example process flow for collaborating with other developers using Git:
1. Pull other developers' proposed changes and merge them into the local repository (the
local working copy):
git pull otherbranch
2. Push your own changes to a remote repository. A development environment will usually
include a central repository, perhaps in the cloud, and each developer has their own local
copy of the repository. Changes made locally can then be uploaded to the central repository
using the Git push command:
git push <remote repository> mybranch
3. See what changes were merged and what other actions were taken on the repository. Run
the git log command inside the project directory. For example, enter git log --since=10.days
to see all of the commits in the last 10 days. You can use this information to troubleshoot
any issues introduced in configuration files, scripts, or any other data tracked by the
repository.
4. Navigate or switch between branches of a project by using the Git checkout command. This
enables developers to focus their attention on different branches of the same project:
git checkout specificbranch

Linux LPIC-1 1047


An example Git process flow.

Linux LPIC-1 1048


GIT FILES
The .gitignore file exists within the repository. The purpose of the file is to identify files that
should be ignored during a commit action. For example, you may have a README.txt file or a
project To-Do.txt list that does not need to be committed as part of the project, but does
reside in the project directory for convenience. These files are identified in the project's
.gitignore file.

The *.git/ directory contains all the files Git uses to manage version control for your project. It
is a single location where Git stores all of its information. The directory resides in the project
directory and is created with the git init command.

Linux LPIC-1 1049


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1050


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1051


Linux LPIC-1 1052
So far, you've implemented automation on a relatively small scale. However, you may be in
charge of hundreds, or even thousands, of systems in a large corporate infrastructure.
Automation alone is not enough to manage the deployment and maintenance of all of these
systems. This is where orchestration comes into play.

ORCHESTRATION
Orchestration enables the automation of multiple related tasks—an entire workflow. One
example of orchestration might be the deployment of a web app. The deployment may include
the installation and configuration of the web server, the installation and configuration of a
MySQL™ database server, and the installation and configuration of an application server, as well
as all supporting software. Orchestration would manage each of the steps involved, even
though there may be different operating systems and configuration requirements involved.
Orchestration is used in both on-premise and cloud-based solutions.

Linux LPIC-1 1053


INFRASTRUCTURE AUTOMATION
Automation is the process of accomplishing a configuration task without human intervention.
This is different than orchestration. Automation refers to a single task, whereas orchestration
manages a larger scale series of tasks. For example, one system administrator might automate
the installation of the Python® package in a Linux deployment, while another administrator
might orchestrate the setup of a combined web and database server with all necessary
configurations. Orchestration may be thought of as a series of automation tasks to accomplish
a large-scale deployment of applications, virtual machines, or entire inter-related
infrastructures.

Linux LPIC-1 1054


BUILD AUTOMATION
Build automation specifically emphasizes the initial operating system deployment. One
example of build automation is the use of Kickstart files with Red Hat-derived distributions.
These files can be referenced by the installation procedure and the operating system is then
deployed according to the instructions in the Kickstart file.

Linux LPIC-1 1055


INFRASTRUCTURE AS CODE
Infrastructure as code is a name for orchestration tools that manage the entire deployment
and configuration process through scripting and code files, rather than through traditional
software tools. Infrastructure as code relies on a single configuration specification to deploy the
supporting infrastructure (the operating system) and the necessary applications.

Linux LPIC-1 1056


ORCHESTRATION TOOLS
The following table lists some common tools used to implement orchestration.
Tool Description
Ansible uses YAML files to create repeatable "playbooks" that define a desired
Ansible configuration state. Ansible is an agentless solution that delivers files over SSH
connections. Red Hat emphasizes the use of Ansible.
Puppet uses manifest files (written in Ruby) to define infrastructure as code for
Puppet® application, cloud, and infrastructure orchestration. Puppet uses an agent on the
target nodes.
Chef uses "cookbooks" to deliver configuration declarations to cloud and on-
Chef™
premises managed systems.
Kubernetes is an open source solution that provides container deployment and
Kubernetes application orchestration for cloud and on-premises container environments. You
define a desired state and Kubernetes configures containers to match that state.
OpenStack was originally a joint Rackspace and NASA project, usually deployed as
OpenStack® an IaaS solution to manage cloud resources. OpenStack can orchestrate the
deployment of a Linux, Apache, MySQL, PHP (LAMP) service, for example.

AGENT-BASED VS. AGENTLESS ORCHESTRATION


Agent-based orchestration tools require that a software component reside on the managed
device. Agentless tools do not require additional software to exist ahead of time on the
managed system.

Linux LPIC-1 1057


PROCEDURES
Orchestration procedures will vary by which solution is used, but in general, orchestration steps
involve defining a desired configuration and then delivering that configuration file to the
destination system. The configuration definition is then processed, setting the system's
configuration to match the definition file.

The following is an example of Chef orchestration procedures:


1. Administrators configure and test a Chef "cookbook" of configurations.
2. The cookbook is delivered to the specified destination client systems.
3. The Chef client processes the cookbook, configuring the node appropriately.

Linux LPIC-1 1058


ATTRIBUTES
Orchestration attributes define tasks to be managed by the orchestration process.
Administrators can use these attributes to identify specific configurations that need to be set by
the orchestration process. OpenStack orchestration relies on attributes, for example.

Linux LPIC-1 1059


INVENTORY MANAGEMENT
Inventory management of hardware, virtual machines, operating systems, applications, and
configurations may all be managed through orchestration tools. Different tools offer different
features for inventory management, including reporting. Inventory is crucial because
administrators cannot manage what they don't know about.

Linux LPIC-1 1060


AUTOMATED CONFIGURATION MANAGEMENT
The benefits of configuration management include consistently configured systems and a more
efficient build process. Ensuring that all systems meet a given configuration baseline helps to
enforce security requirements and service-level agreements, and makes change management
more efficient.

Linux LPIC-1 1061


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1062


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1063


In many cases, the Linux® systems you'll work on will have already been built for you. But
sometimes, you'll need to build a system from scratch. You must be able to install Linux in a
way that meets your organization's business needs, whatever they may be. So, you'll wrap
things up by configuring a Linux installation to your desired specifications.

Linux LPIC-1 1064


In this topic, you will:

• Prepare to install the Linux operating system.


• Perform the installation of Linux.

Linux LPIC-1 1065


Linux LPIC-1 1066
Before you actually begin installation, it's important that you take some steps to prepare. You'll
need to do some research and gather the appropriate information that will help guide you
during the installation process.

SYSTEM REQUIREMENTS
It's important to think of system requirements as more than just what hardware components
are necessary to get a system up and running—they also specify what is necessary to keep that
system operational and able to perform its assigned function. So, you may be able to install
Linux on a computer just fine, but that doesn't mean it will perform optimally.
The system requirements for a Linux system will vary greatly based on a number of different
factors:
• The Linux distribution you're using. Different distros have different recommendations and
baseline requirements as far as CPU speed, RAM, storage space, and more. Some distros are
specifically designed to be lightweight; i.e., they consume much fewer resources than a
standard enterprise or consumer distro.
• Hardware compatibility. Even if a CPU, GPU, etc., is more than powerful enough to run a
Linux distro, that doesn't mean the distro (or the Linux kernel) supports it. You need to
choose hardware that has available, stable drivers
• The general category of the system. Is the system a server? A workstation? Something else?
Each category lends itself to different types of components. For example, CPUs like the Intel®
Xeon® are designed for servers, as they place emphasis on error correction and reliability, as
well as having many cores per processor. A desktop CPU, on the other hand—like an Intel®

Linux LPIC-1 1067


Core™ i7—is designed for single-user scenarios and is typically less powerful than a
server CPU.
• The intended function of the system. Beyond whether or not the system is a
server, workstation, etc., what role does it actually play in the organization? Is the
server a web server? A database server? Does the workstation need to be used for
graphic design? Does it need to be used for word processing? Ultimately, the more
demanding an application is, the more resources you'll need to give it. A web
server might need to handle thousands of network connections per day, and
should therefore be running on adequate networking infrastructure.
• The specific applications that need to run on the system. You might be able to
estimate that a workstation used for graphic design needs a discrete video card.
However, you might not know the exact video card to choose until you know what
application the user will be working with. Some software works best with certain
hardware.
• Price. No organization's budget is limitless, and you should expect to not always be
able to purchase the most powerful hardware. You need to choose solutions that
are the right fit for your organization, while at the same time within your assigned
budget. Prioritizing resources is a crucial skill in helping you make these decisions.

Linux LPIC-1 1067


PARTITIONING STRATEGY
Prior to the installation process, you must be careful to plan an appropriate partitioning
strategy. Servers have different storage needs than individual workstations. If the partition
where the root of the file system is mounted fills up, the system will crash. User home
directories and log files are both examples of directories that can unexpectedly increase in size
very rapidly. By isolating these directories to their partitions, you can prevent a server crash.

Linux usually uses a dedicated partition for virtual memory storage (i.e., swap space). This
partition is unusable for any other kind of storage and has its own file system. It is important to
plan for the swap partition at the same time you plan for data storage partitions. A general
guideline is that the size of the swap partition should be two times the quantity of RAM,
though this number will vary.

Linux LPIC-1 1068


PARTITIONING EXAMPLES
The following is a general partitioning strategy for a Linux server:
• Single partition as / (the root file system).
• Single partition as /home to isolate user home directories from the rest of the storage
space.
• Single partition as /var to isolate log files from the rest of the storage space.
• Single partition dedicated to swap space, typically twice the quantity of RAM.

And a general partitioning strategy for Linux workstations:


• Single partition as / (the root file system).
• Single partition dedicated to swap space, typically twice the quantity of RAM.

Linux LPIC-1 1069


An example partitioning strategy.

Linux LPIC-1 1070


HARDWARE COMPATIBILITY
The first thing you should do before purchasing any hardware component is to check whether it
is compatible with the relevant Linux distribution. Some distros maintain a hardware
compatibility list (HCL) to help you with this effort. An HCL is a database that stores the
vendors and models of all hardware devices that a distro supports in some capacity. Each distro
may maintain its own HCL, which is usually published online. There is no standard format for an
HCL, and many distros don't even have an authoritative HCL.

So, before you install Linux, you should gather hardware information about your system. Much
of this information is available in your system documentation, whether it's the printed manual
that came with a component or it's documentation you can find on the manufacturer's website.
You can also gather hardware device data from a low- level interface like BIOS/UEFI. Failing
either of those options, you may need to open the hood and look inside. Many components
have vendor and model information printed on them.

Linux LPIC-1 1071


QUESTIONS TO ADDRESS WHEN CHOOSING HARDWARE
Some of the questions that you should address before purchasing a hardware component are
listed in the following table. Note that the questions "Who is the manufacturer?", "What is the
model?", and "Is there driver support?" apply to pretty much all component types.

Linux LPIC-1 1072


INSTALLATION METHODS
In most cases, installing an operating system will require you to boot into a special installation
environment. Therefore, the different boot methods you learned about earlier can also be used
to boot installation media, including:
• Booting from removable installation media like DVDs and USB thumb drives. This method
typically requires you to "burn" the installation files onto the DVD, or use a program to
prepare the files on the USB drive. Adding the files to the USB drive normally, like you would
when storing data, won't make it bootable. Installation files are often packaged in a system
image format like ISO or IMG. By default, most BIOS/UEFI environments enable booting from
removable media, but you may need to enable this manually on some systems.

• Booting from media installed on the local drive. For example, you can download an ISO of a
different distro of Linux onto your existing Linux system. You can then configure GRUB 2 to
boot from this ISO, as long as it is placed on a partition that doesn't currently contain a
bootable OS.

• Boot from media that is delivered over a network. You can use protocols like PXE and NFS to
service installation media to a client, who can use that media to boot into the installation
environment.

Linux LPIC-1 1073


The different media used to install Linux.

Linux LPIC-1 1074


GUIDELINES FOR PREPARING TO INSTALL LINUX
Use the following guidelines when preparing to install Linux.

PREPARE TO INSTALL LINUX


When preparing to install Linux:
• Consider the different factors that go into identifying system requirements, such as cost,
system role, and Linux distribution to install.
• Consider partition strategies based on the role of the Linux system. Linux servers may play
many roles and the partition strategies will vary depending on those roles. Linux
workstations do not usually require a complex partition strategy.
• Check an HCL or other online resource to see if your hardware is supported by the relevant
distro.
• Address various questions pertaining to each hardware component before purchasing them.
• Choose an installation method that is most efficient for you and your organization.

Linux LPIC-1 1075


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1076


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1077


MANUAL INSTALLATION STEPS
Although you can automate the installation and deployment of a Linux system— including as
part of a larger orchestration effort—there may be times when you need to perform a step-by-
step manual installation. The actual steps will differ widely depending on the distro you're
installing, as each will have its own installer program. However, most installer programs feature
a GUI and enable you to configure some common settings to install Linux with.

Linux LPIC-1 1078


Installing CentOS 7.

Linux LPIC-1 1079


General installation steps can include, but are not limited to:
• Configure the system language and keyboard layout to use. This step almost always comes
first to set a baseline for understanding the rest of the installation process.
• Configure the time zone and other date and time settings for the system to use. There may
be an option to synchronize with a Network Time Protocol (NTP) server.
• Choose the installation media to use. Even though you booted into the installer using
installation media, some installers enable you to choose a different source to continue with
the installation. For example, if you started the installer with an ISO prepared on a USB
thumb drive, you can configure the installation to use a network repository instead.
• Choose which software environment and components to install. Many distros offer a choice
of one of several base environments. A base environment might be a minimal install without
a GUI and with few user space programs; a full-fledged GUI install with all available
programs; and everything in between. Depending on the distro, you may be able to get more
granular and choose specific software to install.
• Partition and configure logical volumes on one or more available storage drives. You can
design the structure of the root file system here (its size, file system type, etc.), as well as
any other file systems to add on installation.
• Configure the system's networking identity. You can configure one or more available
interfaces with IP addresses, hostnames, and other networking information.
• Configure user accounts. Typically you'll configure the root user's password, and/or a specific
administrator account or other standard users.
• Configure security policies. Some installers enable you to apply security profiles and policies
to the system upon installation.

Linux LPIC-1 1080


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1081


Linux LPIC-1 1082
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1083


_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Linux LPIC-1 1084

You might also like