Skip to content
ImagineWorld

Intermediate Linux

node_idnode-book_the-linux-devops-handbook_chapter-03-intermediate-linux
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleIntermediate Linux
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we’re going to continue with the introduction to the Linux shell. The topic itself is vast and warrants a book of its own. We will be coming back to the topics from the previous chapter and introducing new ones.

In this chapter, we will cover the following topics:

  • Globs
  • Automating repetitive tasks
  • Software installation
  • Managing users
  • Secure Shell (SSH) protocol

It is highly recommended that you have a Linux system installed and ready for use. We recommend it be a virtual machine or a laptop that you can safely reinstall from scratch in case something goes horribly wrong. This will let you follow the examples in this book and perform any kind of exercise that we give you.

We are not going to cover an installation. Every distribution may use its own installer, be it graphical or text (depending on the distribution and which variant you’ve picked). You’ll need to note down or remember the name of your user (conveniently called username or login) and password. There are ways to get into the system if you have physical access and you don’t know either the login or password or both, but they are way outside the scope of this book.

Our main distribution in this book is Debian. However, you should be okay with any of the major ones we covered in the previous chapter, so long as it isn’t Alpine.

There is a lot that a shell can do for you to make your life easier. One of them is allowing for a level of uncertainty when typing in arguments on the shell. To that end, the shell defines several special characters that are treated like symbols for something, not like literal input. These are called global patterns, or globs. The characters that are used in globs are sometimes referred to as wildcards.

Do not confuse globs with regular expressions (regexps). While globs are quite a powerful tool on their own, they are no match for regexps. On the other hand, regexps are not evaluated by bash when it performs pattern matching.

The following table describes shell globs and their meaning. We’re going to explain their exact meaning through several examples:

GlobMeaning
*Matches any number of any characters (also zero)
?Matches exactly one character
[...]Matches any one character from a set inside the brackets

Table 3.1 – Shell globs

The preceding table may be unclear to you, so let’s cover some examples:

ExampleMeaning
*This will match any string of any length.
* test*This will match anything that has the word test inside it: test.txt, good_test.txt, test_run, and simply test (remember, it matches nothing too).
test*txtThis will match anything that has a name starting with test and ending in txt, so test.txt, testtxt, test_file.txt, and so on.
test?This will match any occurrence of test plus one character: test1, test2, testa, test, and so on.
test.[ch]This will match one of two things: test.c or test.h and nothing else.
*.[``ab]This will match any string that ends in a dot and either a or b.
?[``tf]This will match exactly one character of any kind followed by either t or f.

Table 3.2 – Shell globs – examples

The true power of globs emerges once you start writing some more complicated strings of commands (so-called one-liners) or scripts.

Some examples of simple commands that get on an entirely new level when combined with globs are find, grep, and rm. In the following example, I am using globs to remove all files that start with anything, then have test followed by a dot, and then log followed by anything. So, the weirdtest.log, anothertest.log1, and test.log.3 files will be matched, but not testlog and important_test.out. First, let’s list all the files that contain the word test in their name:

admin@myhome:~$ ls -ahl *test*
-rw-r--r-- 1 admin admin 0 Sep 17 20:36 importat_test.out
-rw-r--r-- 1 admin admin 0 Sep 17 20:36 runner_test.lo
-rw-r--r-- 1 admin admin 0 Sep 17 20:36 runner_test.log
-rw-r--r-- 1 admin admin 0 Sep 17 20:36 test.log
-rw-r--r-- 1 admin admin 0 Sep 17 20:35 test.log.1
-rw-r--r-- 1 admin admin 0 Sep 17 20:35 test.log.2
-rw-r--r-- 1 admin admin 0 Sep 17 20:35 test.log.3
-rw-r--r-- 1 admin admin 0 Sep 17 20:35 test.log.4
-rw-r--r-- 1 admin admin 0 Sep 17 20:35 test.log.5
-rw-r--r-- 1 admin admin 0 Sep 17 20:35 test.log.6
-rw-r--r-- 1 admin admin 0 Sep 17 20:35 test.log.7

You will notice that I have used a wildcard (*) to achieve my goal. Now, it’s time for the actual removal:

admin@myhome:~$ rm *test.log*
admin@myhome:~$ ls -ahl *test*
-rw-r--r-- 1 admin admin 0 Sep 17 20:36 importat_test.out
-rw-r--r-- 1 admin admin 0 Sep 17 20:36 runner_test.lo

As demonstrated here, it worked. You will also notice that a properly executed command doesn’t print any messages.

In this section, we explained how to use globs – special characters that allow us to match names in the system with some level of uncertainty. In the next section, we are going to introduce mechanisms to automate repetitive tasks.

There are times when you’ll want to make some tasks repetitive. You may write a script that will create a backup of a database, check users’ home directory permissions, or dump current operating system preformance metrics into a file. Modern Linux distributions provide you with two ways of setting these up. There is a third method that allows you to run a task once, at a delayed time (the at command), but here, we’re interested in repetitive tasks.

Cron is a traditional way of running tasks that need to be executed regularly at specified intervals. Usually, they should be obsolete by systemd timers, but a lot of software provides repeatability through the use of cron jobs and Alpine Linux won’t have this in the name of the minimal-sized distribution.

Cron jobs are essentially commands that are run at predefined intervals. The command and their trigger timers are defined in configuration files that live in the /etc/ directory. The exact number of files and directories differ by distribution. All of them will have a /etc/crontab file. This file usually contains an explanation of the fields within it and several actual commands that you can use as templates. In the following code block, I have pasted explanations from the default / etc/crontab file:

# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
17 * * * * root cd / && run-parts --report /etc/cron.hourly

Normally, there are two ways to set up a cron job. One of them is to put a script that will run your command in one of four directories: /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, or /etc/cron.monthly. They should suffice for normal operations. The /etc/crontab file specifies when those will be run.

The second option is to use the crontab command. The crontab command lets a given user create an entry in their crontab file. However, there’s a difference between a system-wide crontab file (living in the /etc/ directory) and a per-user one. The user cron file doesn’t specify the user field. All entries are run with the user’s permission. Let’s look at the differences:

  • crontab -l lists all cron jobs that the user has defined in their crontab file
  • crontab -e lets the user edit the crontab file to add, remove, or modify the jobs

We are not going to cover systemd timers here in detail and will only mention why they may be a better option.

Systemd timer units are newer versions of cron daemon jobs. They can do everything that cron can. However, they offer some additional capabilities:

  • You can specify the job to run at some time after a system boots.
  • You can specify that the job has to run at some interval after some other job has run.
  • The dependency on the timer unit can even be a service unit – the normal system service task.
  • The granularity is much better. Cron jobs only go down to every minute. Systemd timers can trigger with accuracy defined to a second.

In this section, we have covered cron jobs and mentioned systemd timers as the two most important ways to automate tasks that have to occur regularly. In the next section, we are going to introduce managing software.

Depending on which distribution you’ve chosen and the type of installation you’ve decided on, your system may lack software that’s essential for your everyday work. It may also be that you one day require a piece of software that isn’t installed by default.

Linux distributions pioneered something that other operating systems mirrored later on. The common way of installing software on the Linux operating system is by running an appropriate command that will fetch a binary, put it properly on the system, add some configuration if required, and make it available to users. Today, this may not sound revolutionary at all. After all, we’re living in a world of Apple App Store, Google Play, and Microsoft Apps. But back in the day when Windows and macOS users had to navigate the internet to find a suitable installer for their software, Linux users could install most of it with a single command.

This is important in the automated environments that DevOps would strive to set up for several reasons:

  • The installable software (distributed in packages) is held in repositories maintained by the distribution team. This means that you don’t need to know the software’s location on the internet; you just need to know its package name and ensure it’s in the repository.
  • The package standards that we’ll cover here (rpm and deb) know dependencies. This means that if the software you’re trying to install depends on another not-yet-installed software, it will automatically get pulled and installed.
  • The distributions that we’ll cover here have security teams. They work with package maintainers to keep them patched against any known vulnerabilities. However, this does not mean that they will actively research vulnerabilities in said packages.
  • The repositories are mirrored over the internet. This means that even if one of them fails (goes offline or is DDoS-ed or for any other reason), you can reach its mirror copies from all over the world. This is not necessarily true for commercial repositories.
  • You can create a local repository mirror in your LAN if you wish. This will give you the fastest download times at the cost of a lot of hard drive space. Package repositories can be huge.

The amount and versions of the software depend on the distribution in many ways:

  • The policy distribution has to distribute software with different types of licenses: Some distributions will forbid any software that isn’t strictly open and free as defined by the Open Source Initiative. Other distributions will give the user a choice of adding repositories that may contain software that is more restrictive in its licensing.
  • The number of maintainers and maintainership models: It is quite obvious that distributions can only do as much work as they have man hours to spare. The smaller the team, the less software they can package and maintain. Part of the work is automated, but a lot will always need to be manual. With Debian being a non-commercial distribution, it relies solely on the work of volunteers. Ubuntu and Fedora do have commercial backing and part of the team is even employed by one of the companies: Canonical and Red Hat. Red Hat Enterprise Linux (RHEL) is entirely built and maintained by Red Hat employees.
  • The type of repositories you decide to use: Some software makers distribute their packages in separate repositories, after which you can add them to your configuration and use them as if they were regular distribution repositories. However, if you do so, there are some things to keep in mind:
    • The software in the third-party repository is not part of the quality effort made by the distribution: This is solely at the discretion of the repository maintainer – in this case, the software vendor. This will include security fixes.
      • The software in the third-party repository may not be updated at the same time as the core distribution repositories: This means that sometimes, there will be conflicts in package versions required by the software and delivered by the distribution. Moreover, the probability of conflict rises with the number of third-party repositories you add to your server.

The Debian distribution and its derivative, Ubuntu, use the DEB package format. It was created solely for Debian. We won’t be going into its history here, and we will only touch on technical details as required.

The command that works directly with package files is dpkg. It is used to install, remove, configure, and, importantly, build .deb packages. It can only install packages that exist on the filesystem and doesn’t understand remote repositories. Let’s look at some of the possible actions for dpkg:

  • dpkg -i package_file.deb: Installs the package file. This command will go through several stages, after which it will install the software.
  • dpkg –unpack package_file.deb: Unpacking means it puts all important files in their respective places but does not configure the package.
  • dpkg –configure package: Note that this requires the package name, not the package filename. If, for some reason, packages have been unpacked but not configured, you can use the -a or –pending flag to work on them.
  • dpkg -r package: This action removes the software but does not delete configuration files and eventual data it will contain. This can be useful if you plan to reinstall the software in the future.
  • dpkg -p package: This action purges the package and removes everything: software, data, configuration files, and caches. Everything.

In the following example, we’re installing a nano-editor from a package that was physically downloaded to the system, possibly by clicking a download button on a web page. Note that this is not a very usual way of doing things:

root@myhome:~# dpkg -i nano_5.4-2+deb11u1_amd64.deb
(Reading database ... 35904 files and directories currently installed.)
Preparing to unpack nano_5.4-2+deb11u1_amd64.deb ...
Unpacking nano (5.4-2+deb11u1) over (5.4-2+deb11u1) ...
Setting up nano (5.4-2+deb11u1) ...
Processing triggers for man-db (2.9.4-2) ...

More often than not, you’ll need to install and remove software using the apt suite of tools:

  • apt-cache search NAME will search for a package that contains the given string. In the following example, I’m looking for a package that contains the vim string (vim is one of several popular command-line text editors). The output has been shortened by me for brevity:
root@myhome:~# apt-cache search vim
acr - autoconf like tool
alot - Text mode MUA using notmuch mail
[...]
vim - Vi IMproved - enhanced vi editor
[...]
  • apt-get install NAME will install the package whose name you specify. You can install several packages in one line. In the following example, I am installing a C compiler, a C++ compiler, and a Go language suite. Note that the output also contains a list of packages that are required for my desired software to work and that they will be installed to provide that functionality:
root@myhome:~# apt-get install gcc g++ golang
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
gcc is already the newest version (4:10.2.1-1).
The following additional packages will be installed:
bzip2 g++-10 golang-1.15 golang-1.15-doc golang-1.15-go golang-1.15-src golang-doc golang-go golang-src libdpkg-perl libfile-fcntllock-perl libgdbm-compat4 liblocale-gettext-perl libperl5.32 libstdc++-10-dev perl perl-modules-5.32
pkg-config
Suggested packages:
bzip2-doc g++-multilib g++-10-multilib gcc-10-doc bzr | brz git mercurial subversion debian-keyring gnupg patch bzr libstdc++-10-doc perl-doc libterm-readline-gnu-perl | libterm-readline-perl-perl libtap-harness-archive-perl dpkg-dev
The following NEW packages will be installed:
bzip2 g++ g++-10 golang golang-1.15 golang-1.15-doc golang-1.15-go golang-1.15-src golang-doc golang-go golang-src libdpkg-perl libfile-fcntllock-perl libgdbm-compat4 liblocale-gettext-perl libperl5.32 libstdc++-10-dev perl
perl-modules-5.32 pkg-config
0 upgraded, 20 newly installed, 0 to remove and 13 not upgraded.
Need to get 83.9 MB of archives.
After this operation, 460 MB of additional disk space will be used.
Do you want to continue? [Y/n]

The installer stops here and waits for our input. The default action is to accept all the additional packages and follow the installation. By typing in n or N and pressing Enter, we can stop the process. The -y switch for the install action will skip that question and automatically proceed to the next step:

  • apt-get update will refresh the package database with new available packages and new versions.
  • apt-get upgrade will upgrade all installed packages to the newest versions listed in the database.
  • apt-get remove NAME will remove the package of the given name. In the following example, we are uninstalling the C++ compiler:
root@myhome:~# apt-get remove g++
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following packages were automatically installed and are no longer required:
g++-10 libstdc++-10-dev
Use 'apt autoremove' to remove them.
The following packages will be REMOVED:
g++
0 upgraded, 0 newly installed, 1 to remove and 13 not upgraded.
After this operation, 15.4 kB disk space will be freed.
Do you want to continue? [Y/n]
(Reading database ... 50861 files and directories currently installed.)
Removing g++ (4:10.2.1-1) ...

The other popular group of distributions uses the RPM package format. The basic tool to interact with packages is rpm. The main distribution that uses this format is RHEL, which is made by the Red Hat company. The packages always have the .rpm file extension.

They use the dnf command to manage packages. There is also the yum command, which is the original package manager for the RHEL distribution (and, by extension, the Fedora and CentOS distributions), but it has been removed. dnf is a next-generation rewrite of yum, with many improvements underneath to make it more robust and modern:

  • dnf install package_name will install a package of a given name, along with its dependencies.
  • dnf remove package_name will remove the package.
  • dnf update will update all packages to the latest versions in the package database. You can specify a package name, after which yum will update that package.
  • dnf search NAME will search for package names containing the NAME string.
  • dnf check-update will refresh the package database.

With that, let’s take a look at another Linux distribution that is widely used, especially as a base for Docker images – Alpine Linux.

Alpine Linux is loved especially by engineers working mainly with Docker and Kubernetes. As the main web page of the distribution claims, Small. Simple. Secure. There are no bells and whistles you can find in Debian-based or Red Hat-based distributions, but the output Docker image is really small and due to their focus on security, you can presume there are no major security vulnerabilities if you’ve updated all packages to the recent version.

Alpine Linux’s main downside (and an upside, depending on your viewpoint) is that it’s compiled with the use of the musl libraries instead of the widely spread libc libraries, although it does use the GNU C Compiler (GCC), just like most other Linux distributions. Most of the time, it’s not going to bother you, except when you’re installing applications written in Python. That’s because some Python packages use extensions written in C, and naturally, pre-built packages are compiled with libc, so you will need to carry out extra steps to ensure you have your compile-time dependencies installed before installing any Python dependencies.

The command to interact with packages is Alpine Package Keeper (apk). Alpine has two types of releases: stable (with a proper version; for example 3.16) and edge, which is a rolling release (it always has the latest available version of packages).

Additionally, there are three repositories you can use to install packages: main, community, and testing.

You will find officially supported packages in the main repository; all tested packages are placed inside the community repository, and testing is used, well, for testing, which means that there can be some broken or outdated packages or some with security flaws.

Before searching for or installing any package, it’s advisable to download the latest package cache. You can do this by invoking the apk update command:

root@myhome:~# apk update
fetch https://dl-cdn.alpinelinux.org/alpine/v3.16/main/x86_64/APKINDEX.tar.gz
fetch https://dl-cdn.alpinelinux.org/alpine/v3.16/community/x86_64/APKINDEX.tar.gz
v3.16.2-376-g3ff8974e73 [https://dl-cdn.alpinelinux.org/alpine/v3.16/main]
v3.16.2-379-g3c25b38306 [https://dl-cdn.alpinelinux.org/alpine/v3.16/community]
OK: 17037 distinct packages available

If you’re building a Docker image for later use, it’s a good idea to remove this cache on the final step of the build process using the apk cache clean command.

Sometimes, we don’t know the exact name of the package while we’re working on creating a new Docker image. The easiest way to find whatever you’re searching for in this case is just using the web interface: https://pkgs.alpinelinux.org/packages.

Using the CLI, you will be able to search for partial library names and binary names, though you can specify that what you’re searching for is a library using the so: prefix. Other useful prefixes are cmd: for commands and pc: for pkg-config files:

root@myhome:~# apk search libproc
libproc-3.3.17-r1
libksysguard-5.24.5-r0
process-cpp-3.0.1-r3
samba-dc-libs-4.15.7-r0
procps-dev-3.3.17-r1
root@myhome:~# apk search vim
neovim-doc-0.7.0-r0
gvim-8.2.5000-r0
vim-tutor-8.2.5000-r0
faenza-icon-theme-vim-1.3.1-r6
notmuch-vim-0.36-r0
kmymoney-5.1.2-r3
faenza-icon-theme-gvim-1.3.1-r6
meson-vim-0.62.1-r0
runvimtests-1.30-r1
graphviz-3.0.0-r0
neovim-0.7.0-r0
py3-pynvim-0.4.3-r3
nftables-vim-0_git20200629-r1
vim-doc-8.2.5000-r0
vim-editorconfig-0.8.0-r0
apparmor-vim-3.0.4-r0
geany-plugins-vimode-1.38-r1
vimdiff-8.2.5000-r0
vimb-3.6.0-r0
neovim-lang-0.7.0-r0
u-boot-tools-2022.04-r1
fzf-neovim-0.30.0-r7
nginx-vim-1.22.1-r0
msmtp-vim-1.8.20-r0
protobuf-vim-3.18.1-r3
vimb-doc-3.6.0-r0
icinga2-vim-2.13.3-r1
fzf-vim-0.30.0-r7
vim-sleuth-1.2-r0
gst-plugins-base-1.20.3-r0
mercurial-vim-6.1.1-r0
skim-vim-plugin-0.9.4-r5
root@myhome:~# apk search -e vim
gvim-8.2.5000-r0
root@myhome:~# apk search -e so:libproc*
libproc-3.3.17-r1
libksysguard-5.24.5-r0
process-cpp-3.0.1-r3
samba-dc-libs-4.15.7-r0

Installing, upgrading, and uninstalling packages

Section titled “Installing, upgrading, and uninstalling packages”

You can perform basic operations on packages by using the add (installing), del (uninstalling), and upgrade commands. While installing, you can also use special prefixes that are available during search operations, but it’s recommended to use the exact name of the package instead. Please also note that when adding a new package to the system, apk will choose the latest version of the package:

root@myhome:~# apk search -e postgresql14
postgresql14-14.5-r0
root@myhome:~# apk add postgresql14
(1/17) Installing postgresql-common (1.1-r2)
Executing postgresql-common-1.1-r2.pre-install
(2/17) Installing libpq (14.5-r0)
(3/17) Installing ncurses-terminfo-base (6.3_p20220521-r0)
(4/17) Installing ncurses-libs (6.3_p20220521-r0)
(5/17) Installing readline (8.1.2-r0)
(6/17) Installing postgresql14-client (14.5-r0)
(7/17) Installing tzdata (2022c-r0)
(8/17) Installing icu-data-en (71.1-r2)
Executing icu-data-en-71.1-r2.post-install
*
* If you need ICU with non-English locales and legacy charset support, install
* package icu-data-full.
*
(9/17) Installing libgcc (11.2.1_git20220219-r2)
(10/17) Installing libstdc++ (11.2.1_git20220219-r2)
(11/17) Installing icu-libs (71.1-r2)
(12/17) Installing gdbm (1.23-r0)
(13/17) Installing libsasl (2.1.28-r0)
(14/17) Installing libldap (2.6.3-r1)
(15/17) Installing xz-libs (5.2.5-r1)
(16/17) Installing libxml2 (2.9.14-r2)
(17/17) Installing postgresql14 (14.5-r0)
Executing postgresql14-14.5-r0.post-install
*
* If you want to use JIT in PostgreSQL, install postgresql14-jit or
* postgresql-jit (if you didn't install specific major version of postgresql).
*
Executing busybox-1.35.0-r17.trigger
Executing postgresql-common-1.1-r2.trigger
* Setting postgresql14 as the default version
OK: 38 MiB in 31 packages

You can also choose to install a specific version of a package instead of the latest version. Unfortunately, it’s impossible to install older versions of the package from the same repository because when a new version is deployed, the old version is removed. You can, however, install older versions of packages from other repositories:

root@myhome:~# apk add bash=5.1.16-r0 --repository=http://dl-cdn.alpinelinux.org/alpine/v3.15/main
(1/4) Installing ncurses-terminfo-base (6.3_p20220521-r0)
(2/4) Installing ncurses-libs (6.3_p20220521-r0)
(3/4) Installing readline (8.1.2-r0)
(4/4) Installing bash (5.1.16-r0)
Executing bash-5.1.16-r0.post-install
Executing busybox-1.35.0-r17.trigger
OK: 8 MiB in 18 packages

You can also install a custom package you’ve prepared beforehand using the following command:

root@myhome:~# apk add --allow-untrusted your-package.apk

To upgrade all available packages in your system, you can simply invoke the apk upgrade command. However, if you want to upgrade only a specific package, you will need to add its name after the upgrade option. Remember to refresh the package cache beforehand:

root@myhome:~# apk update
fetch https://dl-cdn.alpinelinux.org/alpine/v3.16/main/x86_64/APKINDEX.tar.gz
fetch https://dl-cdn.alpinelinux.org/alpine/v3.16/community/x86_64/APKINDEX.tar.gz
v3.16.2-376-g3ff8974e73 [https://dl-cdn.alpinelinux.org/alpine/v3.16/main]
v3.16.2-383-gcca4d0a396 [https://dl-cdn.alpinelinux.org/alpine/v3.16/community]
OK: 17037 distinct packages available
root@myhome:~# apk upgrade
(1/2) Upgrading alpine-baselayout-data (3.2.0-r22 -> 3.2.0-r23)
(2/2) Upgrading alpine-baselayout (3.2.0-r22 -> 3.2.0-r23)
Executing alpine-baselayout-3.2.0-r23.pre-upgrade
Executing alpine-baselayout-3.2.0-r23.post-upgrade
Executing busybox-1.35.0-r17.trigger
OK: 8 MiB in 18 packages

You can find all other possible operations by invoking apk without any other options. One of the most useful operations is the apk info command. It will print out information about a package or repository (the following output has been abbreviated):

root@myhome:~# apk info --all bash
bash-5.1.16-r2 description:
The GNU Bourne Again shell
bash-5.1.16-r2 webpage:
https://www.gnu.org/software/bash/bash.html
bash-5.1.16-r2 installed size:
1308 KiB
bash-5.1.16-r2 depends on:
/bin/sh
so:libc.musl-x86_64.so.1
so:libreadline.so.8
bash-5.1.16-r2 provides:
cmd:bash=5.1.16-r2.

In this section, we introduced package managers – the standard way to manage software in Linux distributions. In the next section, we are going to cover managing user accounts.

The user in a Linux system is defined by a set of three files:

  • /etc/passwd: This file contains information about the user – that is, the user’s name, unique numerical ID (UID) in the system, the primary group the user belongs to GID, the path to the home directory, and the shell that is loaded when the user logs in. A typical entry looks like this:
admin:x:1000:1000:Debian:/home/admin:/bin/bash

Each line describes exactly one user. Fields are separated by a colon. The second field will only contain anything other than x in very exotic cases. Here, x means that the password is stored separately in the /etc/shadow file. The reason is that permissions for the /etc/passwd file have to be a bit more relaxed so that the login process can work. /etc/shadow can only be read by root and root group and written to only by root:

root@myhome:~# ls -ahl /etc/passwd
-rw-r--r-- 1 root root 1.6K Aug 22 18:38 /etc/passwd
root@myhome:~# ls -ahl /etc/shadow
-rw-r----- 1 root shadow 839 Aug 22 18:38 /etc/shadow
  • /etc/shadow -: This file contains an encrypted password. As mentioned in the preceding bullet, for security reasons, this file can only be read and written to by the root user.
  • /etc/group -: This file contains information about user groups that the user belongs to. Groups are exactly that: accounts that have been grouped together so that their permissions can be managed.

You should never have a reason to modify these files by hand and that goes especially for the /etc/shadow file. The only way to properly change its contents is by using the passwd command. We encourage you to read the man page for more information.

Three commands take part in user modification and there are three for managing groups: useradd, userdel, usermod, groupadd, groupdel, and groupmod.

useradd adds a user account to the system. Various switches modify the behavior of this command. One of the most common versions of calling the useradd command will add a user, create its home directory, and specify the default shell:

root@myhome:~# useradd -md /home/auser -s /bin/bash auser

-m tells the command to create a home directory, -d (here, it’s been passed with one minus sign alongside the m) tells the command what the home directory should be (notice the absolute path), and -s specifies the default shell. More parameters can be specified and, again, we encourage you to read the man page for more details.

usermod modifies existing user accounts. It can be used to change the group membership of the user, home directory, lock the account, and more. One interesting option here is the -p flag, which lets you non-interactively apply a new password. This is useful in automation, when we may want to update a user password from a script or a tool, not from the command line. However, there is a security risk associated with this: during the command’s execution, anyone in the system can list running processes with their parameters and see the password entry. This does not automatically compromise the password as it must be provided as encrypted through the use of the crypt (3) function. However, if an attacker has the encrypted version of the password, they can run a password-cracking program against it and, finally, brute force its clear text version:

root@myhome:~# usermod -a -G admins auser

The preceding command will add the auser user to a group called admins. The -a option means that the user will be added to the supplementary group (it won’t be removed from other groups it’s a member of).

The userdel command is used to remove a user from a system. It can only remove user entries from system files and leave the home directory intact or delete users with home directories:

root@myhome:~# userdel -r auser

The preceding command will remove the user, along with its home directory and all files. Note that if the user is still logged in, it will not be removed.

Similarly to managing users, you can add, remove, and modify groups within your Linux system. There are equivalent commands to accomplish this:

  • groupadd: Creates a group in the system. Groups can later be used to group users together and specify their execution, directory, or file access rights.
  • groupdel: Removes the group from the system.
  • groupmod: Changes the group definition.

You can also check which users are currently logged into the system by using the who command:

admin@myhome:~$ who
ubuntu tty1 2023-09-21 11:58
ubuntu pts/0 2023-09-22 07:54 (1.2.3.4)
ubuntu pts/1 2023-09-22 09:25 (5.6.7.8)
trochej pts/2 2023-09-22 11:21 (10.11.12.13)

You can also find the UID and GID of the user you’re currently logged into using the id command:

admin@myhome:~$ id
uid=1000(ubuntu) gid=1000(ubuntu)
groups=1000(ubuntu),4(adm),20(dialout), 24(cdrom),25(floppy),27(sudo),29(audio), 30(dip),44(video),46(plugdev),119(netdev),120(lxd),123(docker)

By executing this command without any options, it will show your user ID and all the corresponding groups the user is in. Alternatively, you can provide a name you’d like to view the UID or GID of:

admin@myhome:~$ id dnsmasq
uid=116(dnsmasq) gid=65534(nogroup) groups=65534(nogroup)

To view the primary group’s ID and UID, you can use the -u and -g options, respectively:

admin@myhome:~$ id -u
1000
admin@myhome:~$ id -g
1000

In this section, we introduced commands that are used to manage user accounts and groups in Linux systems. The next section will explain securely connecting to remote systems using SSH.

In the DevOps world, almost nothing runs locally on your laptop or PC. There is one golden standard among ways to reach remote systems and it’s the SSH protocol. SSH was developed in 1995 as a secure, encrypted remote shell access tool that would replace plaintext utilities such as telnet or rsh. The main reason for this is that in distributed networks, it is too easy to eavesdrop on communication and anything that is being transmitted in open text can easily be intercepted. This includes important data such as login details.

The most commonly used SSH server (and the client) in the Linux world is OpenSSH (https://www.openssh.com/). Other open source servers that are still maintained at the time of writing are lsh (http://www.lysator.liu.se/~nisse/lsh/), wolfSSH (https://www.wolfssl.com/products/wolfssh/), and Dropbear (https://matt.ucc.asn.au/dropbear/dropbear.html).

SSH is mainly used to log into a remote machine to execute commands. But it’s also capable of transferring files (Secure File Transfer Protocol (SFTP)), forwarding ports, and creating X Window System (X11), a graphical user interface) connections. It’s also capable of acting as a socket secure (SOCKS) proxy. Typically, an SSH server listens for connections on TCP port 22.

After installing the OpenSSH server, your distribution will place a basic configuration inside the /etc/ssh/sshd_config file. The most basic configuration looks like this:

AuthorizedKeysFile .ssh/authorized_keys
AllowTcpForwarding no
GatewayPorts no
X11Forwarding no
Subsystem sftp /usr/lib/ssh/sftp-server

Let’s investigate each of them before moving option:

  • AuthorizedKeysFIle tells our server where to look inside the user directory for the file where you will store all public keys that can be used to connect to this machine as a specified user. So, if you put your public key inside the AlphaOne home directory, /home/AlphaOne/.ssh/authorized_keys, you will be able to connect as this user using a counterpart private key (more about keys will be covered in the Creating and managing SSH keys subsection).
  • AllowTCPForwarding will enable or disable the ability for all users to forward TCP ports. Port forwarding is used to access remote machines that are not available directly on the internet, but you have access to another machine that can connect. This means you’re using an SSH box as a so-called jump host to connect to a private network, similar to using a VPN.
  • GatewayPorts is another option that’s connected directly to the port forwarding feature. By allowing GatewayPorts, you can expose forwarded ports not only to your machine but also to other hosts within the network you are connected to. Setting this option to yes is not recommended for security reasons; you can accidentally expose a private network to a network you happen to be connected to, for example, in a coffee shop.
  • X11Forwarding has a very specific use case. Usually, you don’t want to have a full-fledged GUI on your servers, but if you have that need, by enabling this option, you will be able to log into the remote machine and start a remote graphical application, which will appear to run on your local host.
  • Subsystem enables you to extend the OpenSSH server with additional features, such as SFTP in this case.

A very important option that is not specified in the preceding command block is PermitRootLogin, which, by default, is set to prohibit-password. This means that you will be able to log in as a root user, but only if you need to authenticate using a public and private pair of keys. We recommend setting this option to no and allowing access to the root user only via the sudo command.

That’s all. You can, of course, add more advanced configurations, such as using Pluggable Authentication Modules (PAMs), only allowing logging into specific users or groups, or closing users in a specific directory after logging in (the ChrootDirectory option). You can find all available options for the OpenSSH server by invoking the man sshd_config command.

In the same way, you can find out how to configure your SSH client – that is, by running man ssh_config.

Some very useful options for the client are shown here:

# Show keys ascii graphics
VisualHostKey yes
# Offer only one Identity at a time
Host *
ForwardAgent yes
IdentitiesOnly yes
IdentityFile ~/.ssh/mydefaultkey
# Automatically add all used keys to agent
AddKeysToAgent yes

VisualHostKey, when set to yes, will show ASCII graphics for the public key of the server. Every server you will be connected to will have a unique key, so it’s going to be unique graphics. It’s useful because, as humans, we’re very good at spotting patterns, so if you are connecting to the 1.2.35.2 server but you intend to get into a different system, chances are that you will figure out something is not right just by seeing different graphics than what you expected.

Here’s an example:

root@myhome:~# ssh user@hosts
Host key fingerprint is SHA256:EppY0d4YBvXQhCk0f98n1tyM7fBoyRMQl2o3ife1pY
+--[ED25519 256]--+
| .oB++o |
| +o*o .. |
| +..o*.+ . |
| .o +.= . + |
| ..o.S.= = . |
| .ooooE. . |
| .o.o |
| |
| |
+----[SHA256]-----+

The host option allows you to set specific options for one or multiple servers. In this example, we’re enabling forwarding SSH agent and disabling password logins for all servers. Also, we’re setting a default private key we will be using to connect to any server. This leads us to SSH keys and ciphers.

The final option, AddKeysToAgent, means that whenever you use (and unlock) a key, it will also be added to the SSH agent for future use. That way, you won’t need to specify a key to use while connecting and you won’t have to unlock the key on every connection attempt.

SSH consists of three components: the transport layer (Transmission Control Protocol (TCP)/ Internet Protocol (IP)), the user authentication layer, and a connection layer, which can effectively be multiple connections transferring data independently.

In terms of the different authentication options, you have a basic form of password authentication, which has proved to be not enough. There’s also public-key authentication, which we’ll talk about here. The two remaining ones are keyboard-interactive and Generic Security Service Application Programming Interface (GSSAPI).

Public-key authentication requires us to generate a key that will have two counterparts: private and public. You will put the public key on the server inside authorized_keys; the private key will be used to authenticate.

At the time of writing this book, RSA keys are standard for use with SSH. It is secure, but it’s recommended to use bigger keys that are 4,096 bits long, but 3,072 bits (the default) are considered sufficient. Bigger keys mean slower connections.

Currently, a better choice is using the ed25519 type of key, which has a fixed length.

Additionally, all keys can be secured with a password.

The following code shows how to generate both key types:

root@myhome:~# ssh-keygen -b 4096 -o -a 500 -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa
Your public key has been saved in /root/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:eMu9AMUjpbQQ7DJIl4MB2UnpfiUqwZJi+/e9dsKWXZg root@614bbd02e559
The key's randomart image is:
+---[RSA 4096]----+
|o=+++.. . |
|.o++.o = |
|o+... + + |
|*o+ o .+ . |
|+o.+ oo S o |
|..o . + o E . |
| ... = + . |
| . . .B + |
| . ..oo= |
+----[SHA256]-----+
root@myhome:~# ssh-keygen -o -a 100 -t ed25519
Generating public/private ed25519 key pair.
Enter file in which to save the key (/root/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_ed25519
Your public key has been saved in /root/.ssh/id_ed25519.pub
The key fingerprint is:
SHA256:EOCjeyRRIz+hZy6Pbtcnjan2lucJ2Mdih/rFc/ZnthI
root@614bbd02e559
The key's randomart image is:
+--[ED25519 256]--+
| . =.. |
| * o . |
| o B . |
| * o . |
| + o S |
| B o + E |
| o +.*=B o . |
| ...ooB*+= .. + |
| ..oo=o=o .=.. |
+----[SHA256]-----+

Now, to put this newly created key on a server, you will need to either copy it manually to the authorized_keys file or use the ssh-copy-id command, which will do this for you if you already have other means of access, such as password authentication:

root@myhome:~# ssh-copy-id -i ~/.ssh/id_ed25519 user@remote-host

You can only perform the next login to this server by using a key.

At this point, you should have a good understanding of how SSH works and how to use its most used features. You now know how to create your keys and where to save them on the remote system.

This chapter concludes our introduction to the basic Linux operations you will need in your daily work. It has by no means been comprehensive enough to explain everything that you need to know to manage your Linux system, but it is enough to get you started and should be enough to help you manage your system. In the next chapter, we are going to cover writing shell scripts from the very beginning and guide you through basic and more advanced topics.

Try out the following exercises to test your knowledge of this chapter:

  1. In Debian/Ubuntu, install the vim package.
  2. Create a cron job that will create a file called /tmp/cronfile every Saturday at 10:00 A.M.
  3. Create a group called admins and add an existing user to it.