You are on page 1of 25

ADMIN

Network & Security


In Partnership with

10 ToolsTerrific
FOR THE BUSY ADMIN
2021 EDITION
Discover a free
tool to help you:
• Enforce stronger
passwords
• Manage multiple
databases with a
single app
• Add QR stickers to
your hardware for
easy inventory
And much more!
Bonus articles
• Two-Factor Authentication • Ugrep
www . admin - magazine . com US$ 7.95
AUTOMATE LINUX
AVAILABILITY AND
SECURITY
HAPPY SYSADMIN DAY!
As a SysAdmin, you have been putting out users’ fires since 1946. You are the heroes. Silently guarding
companies of all sizes, keeping watch on the five nines, and tirelessly performing countless patching cycles
all year round, sometimes through the night and on weekends. Now you can sit back and relax. Let TuxCare
take care of Linux support and security for you!

We are TuxCare, and we are automating the Linux maintenance


routine so you have more time to do what you love: solve
complex riddles, learn about new technologies and maybe
even build some LEGO!

TuxCare Live patching services TuxCare Linux Support Services


eliminate maintenance windows with maintain and prolong the life of your
automated updates for Linux kernels, current or end-of-life Linux distributions,
shared libraries, VMs, databases, and giving you time to migrate to the newest
embedded devices used in the office. version. Unload your sysadmin workload
No more Friday night security updates! and keep Linux secure without all the fuss.

Learn more

tuxcare.com
Welcome 10 TERRIFIC TOOLS – 2021

Dear Readers,
Experts know that every task has a tool. Commands
10 Tools Terrific
FOR THE BUSY ADMIN

systems up and ready. We round up another list of


2021 EDITION
like ping and top are well known to system admins, little-known gems in this year’s lineup of Terrific
but the experts have many other powerful utilities Tools for the Busy Admin.
for managing the daily challenge of keeping

ADMIN Special Table of Contents


Editor in Chief – Joe Casad
Copy Editors – A
 my Pettle, Aubrey Vaughn
Layout / Graphic Design – Dena Friesen, Lori White pwquality . . . . . . . 4 find and fd. . . . . . . 11
Advertising Strong passwords for each Discover lost treasures in the
Brian Osborn, bosborn@linuxnewmedia.com individual service provide more filesystem in next to no time.
Phone: +49 8093 7679420 protection.
Publisher – Brian Osborn asciinema. . . . . . . 12
Customer Service / Subscription vnStat. . . . . . . . . . 5 Asciinema lets you record events
For USA and Canada:
VnStat measures the network at the command line and publish
Email: cs@linuxnewmedia.com
Phone: 1-866-247-2802
throughput on an interface and the resulting terminal movie.
(toll-free from the US and Canada) provides a history.
www.admin-magazine.com Zint. . . . . . . . . . . . 14
While every care has been taken with the content Tuptime. . . . . . . . . 6 Use QR code stickers to simplify
of the m
­ agazine, the publishers cannot be held How long has the Linux server hardware inventory.
responsible for the accuracy of the information
contained within it or any c­ onsequences arising been running without rebooting?
from the use of it. Usql. . . . . . . . . . . . 15
Copyright & Trademarks © 2021 Linux New Media rss2email. . . . . . . 8 Manage many different databases
USA, LLC
This handy tool sends the most from one prompt.
Cover Illustration © route55, 123RF.com
No material may be reproduced in any form
important RSS feeds directly to
whatsoever in whole or in part without the written your mailbox. Shell History . . . . 17
permission of the p­ ublishers. It is assumed that all Avoid wear on your fingertips with
correspondence sent, for example, letters, email,
faxes, photographs, articles, drawings, are s­ upplied dstask. . . . . . . . . . 9 these shell history tricks.
for publication or license to third parties on a non- A personal tracker that lets you
exclusive worldwide basis by Linux New Media
manage your to-do list from the
unless otherwise stated in writing.
All brand or product names are trademarks of their
command line.
respective owners. Contact us if we haven’t
credited your copyright; we will always correct any As a special bonus, we’re also including two more articles
oversight.
describing other great tools for the busy admin’s toolkit:
Printed in Nuremberg, Germany by hofmann info-
com GmbH.
Distributed by Seymour Distribution Ltd, United
2FA. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Kingdom Protect your system from unwanted visitors with two-factor authentication.
ADMIN is published by Linux New Media USA, LLC,
4840 Bob Billings Parkway, Ste 104, Lawrence, KS ugrep. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
66049, USA. Searching for text in files or data streams is a common and important function. Ugrep
Published in Europe by: Sparkhaus Media GmbH,
Bialasstr. 1a, 85625 Glonn, Germany
tackles this task quickly, efficiently, and even interactively if needed.

WWW.ADMIN-MAGAZINE.COM 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE 3
Xxx
10 TERRIFIC TOOLS – 2021 pwquality

Strong Passwords
Regular password changes are a thing of the past: Strong passwords for
each individual service provide more protection. Charly pimped his Ubuntu
accordingly with a suitable PAM module. By Charly Kühnast

Changing the password regularly,


about every 60 or 90 days, is now
considered obsolete. It is better to
use a separate strong password
for each service and each login.
The requirement for how strong
(i.e., how complicated) a password
must be is something that – at least
on your own systems – you can
define yourself.
On my test machine with Ubuntu, Figure 1: After the change, the system rejects overly simple passwords.
I can use almost any simple pass-
word I want – that has to change. After restarting the system, the instead of an I, because I need a
To make sure it does, I first have to new password rule takes effect. digit according to the new pass-
install the pwquality PAM library: To test it, I changed the password word rule. The system accepted the
of the user bob (Figure 1). In do- password without complaint. n
$ sudo apt install libpam‑pwquality ing so, I intentionally entered a
password that was too short in the
Then I have to add a line to the first round and one that can be Info
/etc/pam.d/common‑password con- found in common dictionaries in [1] “Call me Ishmael. Some years ago –
figuration file. On Ubuntu 18.04 the second. The system categori- never mind how long precisely …”:
“Bionic Beaver,” the default looks cally rejected both – and that’s the [http://​­www.​­online‑literature.​­com/​
like this (this may be slightly dif- way it should be. ­melville/​­mobydick/​­2/]
ferent on other systems): As my third attempt, I entered a
new password that complied with Author
password [success=1 default=ignore] U the modified rules: Cm1.Sya‑n. Charly Kühnast manages Unix systems in
pam_unix.so obscure sha512 This seems complicated, but it is a data center in the Lower Rhine region of
mnemonic. It’s the first letters and Germany. His responsibilities include ensuring
This line can remain as a fallback, punctuation of the first words of the security and availability of firewalls and
but in front of it – and this is im- Melville’s Moby Dick [1], with a 1 the DMZ.
portant – I need to insert the line
from Listing 1. This is a single line, Table 1: pwquality Parameters
which I just wrapped for Listing 1 Parameter Meaning
to improve readability. With the in- retry Number of incorrect attempts
dividual parameters (Table 1 breaks minlen Minimum password length
them down), the password require- difok Number of characters that can match the old password
ments can be easily controlled. lcredit Minimum number of lowercase letters
ucredit Minimum number of uppercase letters
Listing 1: Password Requirements
dcredit Minimum number of numbers
password requisite pam_pwquality.so \
retry=4 minlen=9 difok=4 lcredit=‑2 \ ocredit Minimum number of non-standard characters
ucredit=‑2 dcredit=‑1 ocredit=‑1 \ reject_username Password and username cannot be identical
reject_username enforce_for_root enforce_for_root Rules also apply for root

4 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
vnStat 10 TERRIFIC TOOLS – 2021

Lean Bookkeeper
Tools that measure the network throughput on an interface and provide
a history are not easy to find. VnStat manages this balancing act and
finds favor with Charly. By Charly Kühnast

There are many small tools that parameter is used to delete a da- load. The ‑h, ‑d, ‑w, and ‑m param-
measure and display the network tabase if necessary. eters help me to display the data
throughput on an interface, and The ‑i parameter is used to track traffic history for an hour, a day, a
I have already introduced some the load on an interface (line 8) week, or a month.
of them here. If you also want a in live (‑l) operation. If you The ‑t parameter stands for “Top
history of the data traffic volume, interrupt the output by pressing 10” and returns the 10 days with
you have many choices, but then Ctrl+C, an easily understand- the most traffic. Another handy pa-
these tools are often not exactly able overview of the measured rameter is ‑‑oneline, which gives
lightweight. There is one, though, values appears (Figure 1). When you minimal output that can be
that manages the balancing act: displaying the network through- parsed easily for rehashing in your
VnStat [1]. put, I prefer to read the values own scripts, for example.
After installing vnStat on my test in bits per second rather than Finally, vnStat has a colorful
computer, which runs Ubuntu, in bytes. You can do this by ap- counterpart named vnStati,
vnStat automatically created a pending the ‑ru 1 parameter which illustrates the results in
database for each interface found to the command (ru stands for easily understandable diagrams.
(Listing 1, lines 1 to 4). If the tool “rate unit”). I have never looked at it before,
does not do this automatically, The databases mentioned at the because the monochrome ver-
the databases can be created beginning are used to provide the sion has always been fine for my
manually (line 6). The ‑‑delete desired history about the network needs. n

Info
[1] vnStat: [https://​­humdi.​­net/​­vnstat/]

Listing 1: Monitoring an Interface

01 charly@glas:~$ ls ‑l /var/lib/vnstat
02 total 8
03 ‑rw‑r‑‑r‑‑ 1 vnstat vnstat 2272 Jun 8 14:30 enp1s0
04 ‑rw‑r‑‑r‑‑ 1 vnstat vnstat 2272 Jun 8 14:30 enp2s0
05
06 charly@glas:~$ vnstat ‑‑create ‑i eth0
07
08 charly@glas:~$ vnstat ‑i enp1s0 ‑l
09 Monitoring enp2s0... (press CTRL‑C to stop)
10
11 rx: 204 kbit/s 351 p/s
Figure 1: VnStat lets you monitor the throughput on a network interface in real time. Exiting the 12 tx: 34 kbit/s 39 p/s
tool by pressing Ctrl+C displays a practical summary of the measurement results.

WWW.ADMIN-MAGAZINE.COM 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE 5
Xxx
10 TERRIFIC TOOLS – 2021 Tuptime

Measure system runtime


with tuptime Stopwatch
How long has the Linux server been running without rebooting? And how often has the
system rebooted without you noticing? These questions and more are answered by the
tuptime tool. By Tim Schürmann

If a Linux system has been run- Installation Time Measurement


ning for a long time, this is defi-
nitely proof of its stability, but – While uptime is available on al- After setting up the program, query
depending on the distribution – most every system, you need to the current status via tuptime in the
some updates might be waiting to install tuptime separately. Some terminal. The tool already provides
install. Conversely, if the system distributions, such as Debian and some basic information (Figure 1):
reboots very frequently, there may Ubuntu, already have the tool in At the very top it shows the num-
be a configuration error – or maybe their repositories. Arch Linux users ber of system starts (at System
a hardware component is slowly will find tuptime in the AUR and Startups), as well as the time and
deteriorating. Such restarts are CentOS users in the EPEL reposi- date since the software started
quickly noticed on a workstation tory. On any Linux system, you can counting the starts. Tuptime doesn’t
computer, but not necessarily on a install the tool with the following: capture events before this date. To
remote server that is running qui- get a complete picture, set up the
etly and well away from the action. $ curl ‑Ls https://git.io/tuptime‑install. program as soon as possible after
How long a system has been run- sh | sudo bash system installation.
ning continuously can be deter- Next, tuptime tells you how often
mined at the command line by a Tuptime itself consists of a Python the system has been shut down
call to uptime. But you might also script and requires Python 3 with (System Shutdowns). Pay special
want to try tuptime [1], a similar the modules sys, os, optparse, attention to the number of uncon-
tool whose name is based on a sqlite3, locale, platform, date‑ trolled shutdowns labeled bad. If
contraction of “total uptime.” It time, and logging. These modules this figure increases rapidly, there
outputs far more information, should be preinstalled on most is a major problem, such as an
including valuable information in distributions. For more informa- unstable power supply. System life
the form of the number of reboots tion about installation, see the box indicates how long tuptime has
and the kernel version used. “In the Background.” been monitoring the system. If
you installed tuptime directly after
In the Background the installation of the distribution,
The system calls tuptime briefly during the boot and shutdown processes. In each case, this value corresponds to the time
the tool notes the system time. It is from the timestamps collected in this way that since the first boot.
tuptime ultimately calculates the total runtime and all other values. This is followed by the total system
To make tuptime start automatically at boot and shutdown time, tuptime‑install.sh uptime (System Uptime) and the
sets up some startup scripts. For example, it sets up a corresponding service unit on a total time the computer was pow-
system with systemd. Besides systemd, the installation script also supports SysVinit and ered off (System Downtime). If the
OpenRC. When using the installation script, tuptime also always runs under its own user percentage of downtime exceeds
account, named _tuptime. 50 percent, the computer was off
If at some point the power should suddenly fail, tuptime would not notice anything. As a longer than in operation. How long
consequence, the timestamp for the shutdown would be missing, and this would prevent the system was in operation on av-
the tool from calculating the correct total runtime. For this reason, the installation erage is indicated by the value fol-
script additionally sets up a cron job, which in turn ensures that tuptime is launched at lowing Average Uptime. Similarly,
regular intervals. All timestamps noted by tuptime end up in a small SQLite database,
Average Downtime indicates how
which is located below /var/lib/tuptime/tuptime.db by default.
long the computer was switched

6 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
Tuptime 10 TERRIFIC TOOLS – 2021

The ‑‑tsince A Question of Format


and ‑‑tuntil
parameters If so desired, tuptime ‑csv will
each expect deliver all the information in CSV
a timestamp format. If you append a ‑t, you
that is calcu- are given a table that you can re-
lated by date. direct to a file and then open with
Tuptime also a spreadsheet program.
outputs these If you don’t like the date and time
Figure 1: Shortly after the install tuptime cannot give you very much timestamps format in the output, you can
information, but over time the data starts to give you a better impression with the ‑s change it using
of the computer’s behavior. parameter.
Alternatively, $ tuptime ‑d '%H:%M:%S %m‑%d‑%Y'
off on average. The final value you can limit the output to very
listed is the time since the last sys- specific startup operations. For Tuptime replaces the placehold-
tem start (Current Uptime). example, if you are interested in ers beginning with a % with the
how long the system ran from corresponding values. %H stands
Display Options the very first to the fifth logged for the hours, %M for the minutes,
startup, use the following: %S for the seconds. Similarly, %m
The tuptime ‑l command returns returns the month as a number,
a list with all startup operations. $ tuptime ‑‑since 1 ‑‑until 5 %d the day, and %Y the year. De-
In the list, you can see in detail tails of other placeholders are
when the system was in operation More Details explained in the tuptime docu-
and for how long. If the list seems mentation, which you will find
too confusing, tuptime ‑t converts If you append the ‑k parameter on GitHub in the tuptime‑manual.
the data to tabular form, shown to the call, tuptime will tell you txt file [1]. n
in Figure 2. The additional ‑r pa- the kernel version used at each
rameter reverses the order; the last startup; if you add the ‑b op-
system start appears at the top. tion, it will also provide the Info
If you still feel overwhelmed by the unique identification numbers [1] tuptime:
volume of information, the display of the individual boot processes [https://​­github.​­com/​­rfrail3/​­tuptime]
can be limited to a certain period (Figure 3). The parameter ‑p
of time. For example, if you want to tells tuptime to show you how The Author
know when and for how long the long the system slept in each case Tim Schürmann is a freelance computer
system was active between July 27 (after Sleeping). Similarly, the ac- scientist and author. Besides books, Tim
and July 28, 2020, just call tuptime tive time is noted after Running. has published various articles in magazines
with the command: These values are only available on and on websites.
systems that
$ tuptime ‑‑tsince=$(date have Python
‑‑date="2020‑07‑27" +%s) ‑‑tuntil=$(date 3.6 or higher
‑‑date="2020‑07‑28" +%s) in place.

Figure 2: Tuptime offers different display formats. Here, there has been a Figure 3: This system used the same Linux kernel for both system starts.
reboot since the tool was installed, so two system starts have been counted. After the first start, it ran for 35 minutes without going to sleep.

WWW.ADMIN-MAGAZINE.COM 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE 7
Xxx
10 TERRIFIC TOOLS – 2021 rss2email

Sorting the Harvest


In order to keep up to date with security, Charly uses RSS feeds, among
other things. He lets rss2email send the most important feeds directly to
his mailbox to ensure that nothing is overlooked. By Charly Kühnast

RSS feeds are still an essential approach is


part of my daily information re- very clear-
fueling plan. I sort my feeds in cut. If there
Miniflux, a web-based RSS ag- is no folder
gregator, which I wrote about in named .con‑
this column back in 2014 [1]. I am fig/ in your
happy to say that Miniflux is still home direc-
being actively developed. tory, you
I have a very small number of have to cre-
RSS feeds emailed to me directly. ate one and
These are feeds that warn me of cd to it:
acute security problems. By hav-
ing them delivered directly to my $ cd
inbox, I can avoid the risk of miss- $ mkdir .config Figure 1: Charly uses rss2email to deliver information from RSS feeds about
ing an important article – Miniflux $ cd .config/ acute vulnerabilities directly to his mailbox.
can handle between 200 and 250
feeds, most of which I just skim. When you get there, use the editor action worked can be verified us-
I use rss2email – a very logical of your choice to create the rss2e‑ ing r2e list (line 2). It worked in
choice of name – to email me mail.cfg configuration file with my example.
the feeds. It can be found in the the content from Listing 1; the The r2e run command traverses
package sources of almost all the force‑from = True entry is of spe- the feeds and dispatches the
popular distributions. On Ubuntu, cial importance here. Normally, emails. Now all I need to do is
for example, I installed it with the rss2email would use a sender ad- write a crontab entry to run the
following call: dress from the RSS feed if it found command at specified intervals
one there. However, on many mail (e.g., every 30 minutes). To do
$ sudo apt install rss2email systems, this leads to the spam so, I type crontab ‑e and add the
filter rightly becoming suspicious. crontab line from Listing 3.
Listing 1: rss2email.cfg Before using The force‑from = True entry now Sure enough, the first messages
[DEFAULT] rss2email for causes rss2email to always use start to slowly arrive in my mail-
from = rss@mydomain.com the first time, the address stored in the from line. box (Figure 1). The important
force‑from = True you have to Whether you set html‑mail to True thing here is to be careful about
html‑mail = False
create a config- or False is a matter of taste. the rss2email feeds you choose;
to = charly@mydomain.com
uration file; the Now it’s time to choose one or otherwise you might flood your
more RSS feeds that you want inbox – just staying with Miniflux
Listing 2: Enter and check RSS feed rss2email to check out regularly. would be preferable to that. n
01 $ r2e add DFNCert https://adv‑archiv.dfn‑cert.de/rss/latest The syntax for this is:
02 $ r2e list Info
03 0: [*] DFNCERT (https://adv‑archiv.dfn‑cert.de/rss/latest
r2e add <title> <URL> [1] “The sys admin’s daily grind: Miniflux”
‑> charly@mydomain.com)
by Charly Kühnast, Linux Magazine,
For the DFN Certificate RSS feed, issue 164, July 2014, p. 50, [https://​
Listing 3: Cron job for rss2email which informs admins of current ­www.​­linux‑magazine.​­com/​­Issues/​
*/30 * * * * /usr/bin/r2e run > /dev/null 2>&1 security problems, look at the first ­2014/​­164/​­Charly‑s‑Column‑Miniflux/​
line in Listing 2. Whether the add ­(language)/​­eng‑US]

8 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
dstask 10 TERRIFIC TOOLS – 2021

Best Laid Plans


The dstask personal tracker lets you manage your to-do list
from the command line. By Tim Schürmann

The dstask personal tracker can create a new task, which


help you prioritize tasks and track is described in the fol-
completion. With a short, succinct lowing brief summary
command, you can add a new task (clean up basement).
or mark off a completed one. On Dstask adds all words
request, dstask provides a list of all that follow a plus sign
pending tasks, sorted by urgency. (+) to the task as key-
Filters help you stay on track. As words (i.e., basement and
an added benefit, you can use your private in Listing 2).
task list to show customers or your These tags will help you
boss your completed work. Under later on when searching
the hood, dstask stores the pending for a specific task. You
tasks in the Git version manage- can also add the tags to Figure 1: Dstask removes the tags from the task name. To see
ment system, letting you sync tasks the summary, as shown an individual task’s detailed information (including tags), enter
across all your devices. in line 2 of Listing 2. dstask followed by the task number (1). (You can ignore the
And you can set the messages in light gray from Git.)

Kickstart task priority, shown by


the number following P. Dstask sup- to change the status. This
To get dstask up and running, first ports priority levels P3 to P0, with P0 switches the task to the active
install Git using your package man- for urgent tasks and P2 for normal state, signifying that the task is in
ager. Then go to the dstask project priority tasks. In Listing 2, I’ve set progress. If you take a break, stop
page on GitHub [1] and click on my basement cleanup task to P2 processing with
the current version number. Under because it’s not time critical. Dstask
Assets, download the version for automatically defaults to P2 if you dstask stop clean up basement
Linux, dstask‑darwin‑amd64. don’t include the priority level.
Rename the resulting program which toggles the task back to the
dstask and make it executable. Roll Up Your Sleeves pending state.
You do not have to actually install Once the basement is finally clean,
dstask, but the developer does To see what dstask has on your mark the task as done by entering
recommend storing dstask in /usr/ to-do list, just call dstask. The
local/bin, which lets all of the sys- program assigns a consecutive ID dstask done clean up basement
tem’s users call the program directly to each task. Entering dstask 1
by typing dstask. shows detailed information about Even though dstask is done re-
After that, you still have to create the task (Figure 1). Dstask ignores minding you about this task, it
the Git repository where dstask case sensitivity in the tags.
stores all the tasks and becomes The detailed information also Listing 1: Creating a Git Repository
acquainted with Git (Listing 1). shows the task status. Immedi- $ mkdir ~/.dstask && git ‑C ~/.dstask init
ately after creation, the task will $ git config ‑‑global user.email "editorial@linux‑user.en"
$ git config ‑‑global user.name "Tim Schürmann"
Come On In be shown as pending. When you
head down to the basement and
To add a task to dstask, use the call pick up the first box, call Listing 2: Adding Tasks
shown in line 1 of Listing 2. The 01 $ dstask add clean up basement +basement +private P2
add command tells the program to dstask start clean up basement 02 $ dstask add +private basement +clean up basement P2

WWW.ADMIN-MAGAZINE.COM 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE 9
10 TERRIFIC TOOLS – 2021 dstask

Listing 3: Organizing Tasks in Projects the spring clean‑ As shown in Figure 3, modify
ing project specified the project name to the right of
01 $ dstask add clean up garage +private P3 project:spring cleaning
02 $ dstask add declutter shoe closet +Private P1 project:Spring Cleaning
after the project: the project: parameter. When
03 $ dstask modify 1 ‑Private +Books P1 project:Spring cleaning parameter. (Note you are done, save your adjust-
again that dstask is ments and exit the editor (in
Listing 4: Templates not case sensitive.) nano, press Ctrl+O followed by
01 $ dstask template clean up desk +Private P3 project:administration As shown in Fig- Ctrl+X).
02 $ dstask add template:4 sort pencils ure 2, a call to
dstask reveals that Templates
will still store the task, thereby the original task clean up basement
creating a record of your com- does not yet belong to any project. You probably need to clean up
pleted tasks for your boss or cli- To change this, you can quickly your desk far more often than your
ent. (See Table 1 for more "Dis- modify the information by typing basement. For recurring tasks, tem-
play Formats and Commands.") plates can save you some typing
To get a report on all completed dstask modify 1 project:Spring cleaning (Figure 4). Templates are initially
tasks, enter conventional tasks, but you create
The number again stands for the them using the template keyword
dstask show‑resolved corresponding task ID (where 1 is (Listing 4, line 1). n
the basement cleanup task). You
Dstask automatically sorts the tasks can use modify to adjust the priority,
by weeks. If you want to remove a keywords, and the project itself; a Info
task from the dstask repository, use minus sign removes the tag in ques- [1] dstask: [https://​­github.​­com/​­naggie/​­dstask]
the following command: tion (Listing 3,
line 3). Table 1: Display Formats and Commands
dstask remove clean up basement Action Function
Targeted next List of major tasks
Project Work Intervention show-projects List of all projects including the resolved tasks
show-tags List of all assigned tags
While you’re cleaning up the base- Use the dstask show-active List of all started tasks
ment, you might as well tackle edit 1 com- show-paused List of all tasks that were started and then
the garage and declutter the shoe mand to make paused
closet. All three cleaning tasks a correction in show-open List of all tasks not yet finished
could be grouped together to create a note. Dstask show-resolved List of all completed tasks
a spring cleaning project. then opens all show-templates List of all templates
Dstask lets you add individual the details of the show-unorganised List of all tasks that do not have a tag or are
tasks to a project by adding another specified task not assigned to a project
parameter when you create a task. in a text editor
The tasks in Listing 3 are part of (Figure 3).

Figure 2: When you call dstask, you see a list of pending tasks. Dstask Figure 3: The editor shows you how dstask stores the task under the
displays any existing notes in light gray in the Summary column. hood: a text file in YAML format.

10 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
find and fd 10 TERRIFIC TOOLS – 2021

Eureka!
Fd is an uncomplicated find replacement that discovers lost treasures
in the filesystem in next to no time. Charly would love to deploy an
amazing tool like this in the analog world of his office. By Charly Kühnast

I’m not very good at sorting less, but one that is more intuitive Listing 1: Crontab Entry
things sensibly and then finding to use. This is where fd [2] jumps
find /test/* ‑mtime +365 ‑exec rm {} \;
them again – both in my office into the breach. The compact
and on my computers’ filesystems. younger sibling of find, fd has al-
For the latter, at least I have elec- ready made its way into many dis- In Figure 1, I told fd to search the
tronic help in the form of tools tributions, but often only recently. root directory \ for rng. As you
like find and, more recently, fd. In Ubuntu, it is available starting can see, it also found PatternGram‑
The find command existed on with version 19.04, for example. mar.txt (at the very bottom). This
Unix systems long before Linux After installing fd on my test is because fd is not case-sensitive
was invented – in fact, it’s older Ubuntu, I now have an fdfind by default. However, if an up-
than most of the people who use command. But the developers percase letter is stipulated as the
it. On many of my systems, there make it quite clear that their tool search term, it switches its behav-
is a directory named /test where is named fd and use this name ior and only returns case-specific
I try things out. Anything that in all the examples. In order to results.
proves useful is sent to Git; the permanently teach my system the You can search for file extensions
rest just hangs around gathering short form, I just added an alias with the ‑e parameter. For ex-
dust until the cron job in Listing 1 fd=find entry to my .bashrc. ample, to find all PNG images in
sweeps it away without write ac- Quickly perusing the man page and below the current directory,
cess after 365 days. reveals that fd can definitely just type:
While doffing a hat to the now do less than find, but it does
impressive power of the GNU what it does well, intuitively, fd ‑e png
implementation of find [1], you still and quickly. Typing fd without
sometimes find yourself wishing for any further parameters returns I use regular expressions for fine
a tool that can perhaps do a little the current directory’s contents tuning. By way of an example, the
including all its command
subfolders, but
without the hid- fd '^a.*png$'
den files and di-
rectories – like ls, finds file names that start with
but recursively. If a and end with png. The GitHub
the environment page [2] for the tool explains
variable LS_COLOR many more applications and pa-
is set (which is rameters.
the default on Now all I really need is a physi-
most systems), the cal fd counterpart to tidy up my
output will be in office … n
color.
Things become Info
more interesting if [1] GNU find:
you are searching [https://​­www.​­gnu.​­org/​­software/​
Figure 1: Without concrete instructions, fd ignores the case, but it for a file name or ­findutils/​­manual/​­html_mono/​­find.​­html]
can even handle regular expressions if necessary. name component. [2] fd: [https://​­github.​­com/​­sharkdp/​­fd]

WWW.ADMIN-MAGAZINE.COM 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE 11
Xxx
10 TERRIFIC TOOLS – 2021 asciinema

Shell Screencasts
Asciinema lets you record events at the command line and publish
the resulting terminal movie on the web. By Christoph Langner

A screencast (i.e., a movie of what least give you asciinema 2.0.0. More When you’re recording, keep in
is happening on screen) helps information about the installation, mind that asciinema records the
developers demonstrate their pro- such as for the Python package events on the command line un-
grams to users and is useful for manager Pip, can be found in the changed. It not only stores the
people seeking a way of explaining application documentation [3]. commands and their output, but if
their problems to a support spe- After the install, the easiest way you correct input at the command
cialist. On Linux, there are many to start recording is to type the line, this is also shown in the
different solutions for this, such as asciinema rec command. Doing asciinema video. Similarly, if you
recordMyDesktop and OBS Studio, so opens a new shell in which do nothing during the recording
or – as in the case of Gnome – the asciinema records everything you (e.g., because you need to look
feature is integrated into the desk- type, and the system displays it up the details of a command) the
top environment. But if you only on the screen. It continues until video pauses.
want to record shell commands you stop recording by typing exit To avoid what are often invol-
and their output, you’re using or pressing Ctrl+D. You can then untary and (for the viewer)
a sledgehammer to crack a nut. either press Enter to upload the boring breaks, add the
Asciinema [1] can be a good, lean video to asciinema.org, or save ‑‑idle‑time‑limit=<seconds> op-
alternative for these cases. it locally in the /tmp/ directory tion or the shortcut ‑i<seconds>
Asciinema consists of three compo- using Ctrl+C. The file name is to the call to record the asciinema
nents. The first is the actual record- always tmp<random code>‑ascii. video. This limits the timeout
ing tool for the command line. The cast. Alternatively, you can pass to the number of seconds speci-
second is a web-based hosting plat- a file name and path directly to fied in the option. For example,
form for asciinema videos, which is asciinema at startup: asciinema rec ‑i1 gives you a
similar to YouTube or image hosts maximum timeout of one second.
such as Imgur.com or Gfycat.com. $ asciinema rec <example>.cast
The third component is a JavaScript Managing Shell Videos
player that plays the asciinema vid- To play the locally saved record-
eos [2]. You only need the recorder, ing, call asciinema again, this Alternatively, you can upload
unless you want to host your time with the play option and the the terminal video directly to
asciinema videos on the web your- movie file as a parameter. A typi- asciinema.org on the web without
self. In that case, you would have to cal call looks something like this: any detours. You don’t have to
set up the server components on a register with the service to do this;
web server. $ asciinema play /<path>/<to>/ <example>.cast the video is uploaded automati-
cally if you do not press Ctrl+C
And … Action Asciinema plays the screencast to cancel the action at the end of
directly in the shell, but without the recording.
Most current distributions in- executing the recorded commands Asciinema’s terminal recorder
clude the screencast recorder for locally – it is in fact a video, not then displays a URL in the style
asciinema in their package sources. a script. If necessary, you can use of https://asciinema.org/a/
The application version counter is the space bar to pause playback or jl0[...]2wN, where you (or others)
currently at 2.0.2. Ubuntu 18.04, press “.” to skip through the video can play back the movie in a web
Debian 10 “buster” (sudo apt in‑ frame. Press Ctrl+C if you want browser (Figure 1). The link re-
stall asciinema), and Fedora 28 to stop the playback of the termi- mains active for seven days, after
(sudo dnf install asciinema) at nal movie completely. which the system automatically

12 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
asciinema 10 TERRIFIC TOOLS – 2021

archives the recording, and access selected terminal Listing 1: asciinema-Enriched Website
to the movie is lost. video into any
<!DOCTYPE html>
If you want to keep the movie ac- website, such as <html>
cessible for a longer period of time, your own Word- <head>
you have to authenticate against Press blog or the <title>Hello World</title>
asciinema.org on each computer GitHub page of </head>
where you want to create and up- one of your proj- <body>
<h1>Included as script</h1>
load recordings. To do this, enter the ects. The page
<script id="asciicast‑jl0NXr88Lm7c7DGOIf8Jh92wN" src="https://asciinema.org/
asciinema auth command and then automatically a/jl0NXr88Lm7c7DGOIf8Jh92wN.js" async></script>
open the link displayed in the termi- generates HTML <h1>Included as image</h1>
nal in a browser. You are then given or Markdown <ahref="https://asciinema.org/a/jl0NXr88Lm7c7DGOIf8Jh92wN" target="_blank">
the option to create an account on tags that display <img src="https://asciinema.org/a/jl0NXr88Lm7c7DGOIf8Jh92wN.svg" /></a>
the asciinema website or to log in an image in the </body>
</html>
with an existing account. Asciinema web page linked
will then automatically assign the to the video on
terminal videos previously uploaded asciinema.org. You will also find a of embedding external resources
from this computer to your account. short script snippet below, which into your own website (the script
The web portal lets you manage can be used to embed the video and the data loaded by asciinema
your recordings. For instance, you directly into a website (if the or the embedded image). To
can change the metadata (such as content management of the site avoid external data connections,
the title) or insert a description. allows it). download the image of the ter-
The terminal theme and the pre- Listing 1 demonstrates an minal movie, upload it locally to
view image can also be modified. asciinema-enriched website. The your website, and then link only
Settings | Make public lets you pub- first section uses the script; the to the asciinema video. n
lish your video on a list [4] acces- second uses the universal image.
sible to all users. With the default Figure 2 shows the resulting and
setting, however, your uploads re- still very rudimentary website in Info
main private. Unsuccessful movies, the browser. The asciinema movie [1] asciinema: [https://​­asciinema.​­org]
or ones you no longer want, can be played back in the web browser [2] asciinema project on GitHub:
deleted from the overview. supports copy and paste actions at [https://​­github.​­com/​­asciinema]
any point, so that the viewers can, [3] Installation instructions: [https://​
Embedding asciinema for example, copy commands from ­asciinema.​­org/​­docs/​­installation]
the video directly into the terminal. [4] Public list of all asciicasts:
The Share button gives you infor- However, both variants have the [https://​­asciinema.​­org/​­explore/​­public]
mation on how to integrate the disadvantage

Figure 1: In the default configuration, asciinema automatically uploads the Figure 2: The terminal videos hosted by asciinema can be easily
recorded movies to its in-house “YouTube alternative” for terminal movies. integrated into your own web pages, such as a blog or GitHub page.

WWW.ADMIN-MAGAZINE.COM 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE 13
Xxx
10 TERRIFIC TOOLS – 2021 Zint

Checklist
Doing a hardware inventory in a data center is anything but a piece of cake. In order to
quickly assign devices to the appropriate database entry, Charly provides each newly
acquired system with a QR code sticker with the help of Zint. By Charly Kühnast

When you need to manage large generate im- Listing 1: QR Code with Zint
numbers of devices, there is no ages. Those who
$ zint ‑o ~/qr/linmagurl‑qr.png ‑b 58 ‑d https://linux‑magazine.com
avoiding centralized data manage- now want to
ment. In the simplest case, this can generate codes
be a wiki, with one entry per sys- are spoiled for
tem. This will include, for example, choice: Zint
the date of purchase, the length knows dozens
of the warranty period or main- of variants Figure 2: PDF417 is the format often used in the transportation industry.
tenance contract, any repairs that (Figure 1). With
have already been made, and the zint ‑t, I can display their names. ples of the other types of code.
rack number where the device is I know a few of these codes, like For inventory purposes, I use a clas-
installed (finding the hardware in a EAN and QR, from everyday life. sic QR code. I can encode all ASCII
larger data center can be time-con- PDF417 (Figure 2) and its rela- characters in it, but I have to avoid
suming). I then encode the URL of tives can be found on the boarding nonstandard characters like accents
the wiki entry as a barcode or QR passes of many airlines. And there and umlauts. Using the call from
code, print it on self-adhesive film, just happens to be a cold medicine Listing 1, I create a QR code as a
and stick it on the device. bottle on the table in front of me PNG that reveals the URL for Linux
I generate the codes for this with that has a PZN barcode. I can see Magazine‘s website (Figure 3).
Zint [1]. Many distributions have from a web page [2] for generating In Listing 1, I use ‑b 58 to select QR
Zint on board; if not, it is quickly barcodes that this is used on phar- as the code type. The parameter ‑d
compiled from the GitHub re- maceuticals in Germany. On the for data always has to be at the end:
pository. You must have libpng same website – funnily enough, it Zint blithely ignores all the options
in place; otherwise, Zint will not uses Zint itself – there are exam- that follow. As long as I stick to
this, the barcode generation routine
works like clockwork, which gives
me one less excuse to put off the
pesky inventory process. n

Info
[1] Zint: [https://​­github.​­com/​­zint/​­zint]
[2] Barcode generator:
[http://​­www.​­barcode‑generator.​­org]

Figure 1: Zint can generate these codes. Figure 3: The Linux Magazine URL as a QR code.

14 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
Usql 10 TERRIFIC TOOLS – 2021

Databases
Usql is a useful tool that lets you manage many different
databases from one prompt. By Marco Fioretti

Linux offers many tools for cre- convenient way that will simplify website is that the dependencies
ating, populating, and querying your database experience and are not documented.
databases. I will introduce you to lower the learning curve for add- Another option for obtaining usql is
usql, a little tool that is a lifesaver ing new database systems to your to build it yourself in Go.
for many users who work with repertoire. Usql is a clone of psql,
databases. the standard command-line client Getting Started
The most ubiquitous and flexible for PostgreSQL databases. The goal
way to work with any database is of usql is to “support all standard Usql provides two sets of com-
in a text-based interface. Inside a psql commands and features” and mands: a big family of “normal”
client application, you type queries to extend those commands to in- commands, plus the internal
at a prompt. The syntax might vary clude other database systems. “meta” commands of usql itself.
depending on the implementation If you try to access 10 different The normal commands are nothing
of Standard Query Language (SQL) databases with usql, you will still more than standard SQL queries
[1] the database is using. Depend- need to know all the SQL dialects that you would use in other clients
ing on the database type, the client and how they differ from each to insert, edit, or fetch data. I won’t
either executes the query directly other. With usql, however, you will describe the syntax of those queries
or, much more frequently, forwards be able to query all those databases in this article because this is not a
it to a server that actually handles in the same session of the same general introduction to SQL, and
the data. The result of the query terminal, and you’ll have access to the commands vary depending on
is then printed out, usually in a some extra features built into usql, the database. (You will find many
tabular format. Alternatively, you such as syntax highlighting. good SQL tutorials online.)
can store sequences of queries or The usql meta commands are
commands in a text file and pass it Installing usql all prefixed by a backslash, and
to the client that will execute them the first two commands to learn
automatically, possibly saving the Usql is written in the Go lan- are the ones that tell you what is
result to a file. guage. The easiest way to use it available in your usql installation.
If you always work with one type on Linux is to download the tar The \drivers command first lists
of database (for example, only archive for amd64 systems from all the database drivers that were
SQLite), you can just choose a cli- the release page [3] (version compiled into your copy of usql.
ent for that specific database and 0.7.8 at time of writing). Uncom- The backslashed question mark \?
get good at using it. However, if press the tarball and place the re- lists the available meta commands
you frequently switch back and sulting binary file, unsurprisingly if typed without arguments. Add
forth between different database called usql, in a directory of your the name of a command to learn
clients, each with its own personal- path. At this point, you should be what it does, or use the options
ity and feature set, it can get very able to type usql at a command and variable keywords to view
confusing. prompt and start using the pro- available options and variables.
Usql [2] is a single database client gram. If your Linux system has a
that works with several different version of a library that is older Configuration
database systems. Although the than what usql expects, it won’t
syntax of the actual queries might run. Of course, many Linux ap- It is possible to define the general
vary slightly depending on the plications fail to execute if the li- configuration and start-up behavior
database, other commands for op- braries are out of sync. The prob- of usql by writing the meta com-
erating the client are unified in a lem with the usql binary from the mands in the $HOME/.usqlrc file.

WWW.ADMIN-MAGAZINE.COM 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE 15
10 TERRIFIC TOOLS – 2021 Usql

Usql will also execute all the com- command. In general, DSNs that make usql create a new, empty
mands contained in a file passed to connect to multi-user database SQLite3 database and save it into
it with the ‑f or ‑file switches: servers like PostgreSQL or MariaDB a file with the specified name,
have the following structure: you must use the first command,
#> usql ‑f some‑database‑script.txt which includes a recognizable
driver+transport://user:pass@host/dbname driver name.
You might be wondering what To close an open connection from
happens if the file loaded using The driver part is the name of the inside usql, just type \Z. In any
the ‑f switch contains commands driver you wish to use (which cor- moment, you can also verify the
and settings that conflict with the responds to the type of database) or parameters of the connection you
general $HOME/.usqlrc configura- any of its aliases allowed by usql. are using by typing \conninfo.
tion file. This issue is important, When connecting to a PostgreSQL
especially if you want to prepare database, for example, the driver Editing and Reusing
reusable usql scripts. Luckily, may be postgres or pg, whereas
usql offers an easy solution: with MySQL, you should use mysql
Queries
Just add the ‑X or ‑‑no‑rc op- or just my. Once you are connected to a da-
tion when launching usql at the To connect to a database from the tabase from inside a usql session,
prompt, and usql will completely Linux command line, use the fol- you can communicate with it just
ignore (for that session only!) the lowing command: as if you were using a native cli-
default configuration file. During ent. Usql also keeps the current
an interactive session, you can #> usql my://marco:mypassword@localhost/U query in a dedicated buffer that
load and execute a command file customers you can edit and reuse. Use the \e
as follows: meta command to edit the buffer
or, after launching usql, from its and the \w command to write a
\i FILE own prompt: query into the buffer. The \p com-
\ir FILE mand shows the buffer contents
\c my://marco:mypassword@localhost/customers and \r resets the buffer.
\i executes the contents of FILE, Use the \g command to re-
and \ir is similar except it looks The steps are slightly different if execute the query in the buffer.
for the file in the directory of the you want to connect to a server- If you also want to execute every
current script. \ir is helpful be- less, file-based database such as value of the result, type \gexec.
cause, if you use usql on a regular SQLite3. In this case, the DSN has The \gset command stores the re-
basis, sooner or later you will end a much simpler structure: sult of the query in usql variables
up creating your own library of for further reuse. n
usql scripts that could be orga- driver:/path/to/file‑on‑disk
nized in several folders and might
even call each other. where the driver could be sqlite3, Info
sq, or file, or the command might [1] Introduction to SQL:
Connecting to Databases not specify a driver. Either of the [http://​­www.​­w3schools.​­com/​­sql/]
following commands would open [2] Usql: [https://​­github.​­com/​­xo/​­usql]
Usql opens a database connection an already existing SQLite3 data- [3] Usql release page:
by parsing a string and passing its base contained in the single file [https://​­github.​­com/​­xo/​­usql/​­releases]
content to the appropriate data- $HOME/my‑sqlite‑db.sqlite3:
base driver. Database connection Author
strings (aka “data source names” #> usql sqlite3://$HOME/my‑sqlite‑db.sqlite3 Marco Fioretti is a freelance author, trainer,
or DSNs) can be passed to usql #> usql $HOME/my‑sqlite‑db.sqlite3 and researcher based in Rome, Italy, who
directly on the command line or at has been working with Free and Open Source
any moment during an interactive The second command will work Software since 1995 – and on open digital
session. In an interactive session, without errors only if the $HOME/ standards since 2005. Marco is a Board Mem‑
you can pass all the necessary pa- my‑sqlite‑db.sqlite3 file already ber of the Free Knowledge Institute ([http://​
rameters (driver, database name, exists and is, indeed, an SQLite3 ­freeknowledge.​­eu]), and he blogs about digi‑
etc.) separately via the \c meta database. If your intention is to tal rights at [http://​­stop.​­zona‑m.​­net].

16 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
Shell History 10 TERRIFIC TOOLS – 2021

History Lesson
For admins like Charly, who try to avoid typing at all costs, the shell
offers an excellent opportunity to avoid wear on your fingertips in the
form of built-in history. By Charly Khünast

There are commands that I type


several dozen times a day – grep
<something> /var/log/syslog is Figure 1: Interactive search with Ctrl+R.
such a classic. The shell keeps a
history of all my entries; thanks n Type !! Occasionally, however, I find
to the history command, I can al- n Type !‑1 the history’s length problem-
ways see in a numbered list which Sometimes using relative address- atic, as it only stores 1,000
commands I typed last. ing backwards through history entries on my test system.
The history command is not a proves helpful. In the example This is not enough for me, so
separate tool; typing which his‑ from Figure 2, I reran the third-to- I added a HISTSIZE=10000 line
tory at the command line just last command from the history by to the /.bashrc file to multiply
drops you into a black hole. typing !‑3. If you wanted to repeat the history size by 10. I also
Instead, history is a part of the the last command that started added HISTCONTROL=erasedups to
shell, a built-in keyword. histo‑ with echo, you would just need to /.bashrc. This means that the
ry‘s killer feature, for which lazy type !echo. history command, which I type
people like me are eternally grate- You can also access the param- several times, is only saved once –
ful, is the interactive search. You eters from previous commands. this saves space and gives a bet-
enable it with Ctrl+R, changing If you just typed ls .bashrc, you ter overview. n
the command-line prompt to can enter vim
(reverse‑i‑search)`':. !!:$ to open
If you start typing now, for ex- .bashrc in the
ample, the word net, the shell will editor. If you
show you the last command typed have a command
containing net. When you press that requires
Ctrl+R again, the history feature root privileges,
shows you an increasing number sudo !! does
of older commands that contain the trick. In the
net (Figure 1). meantime, I de-
There are a number of other ways fined but as an
to execute commands stored in alias (Figure 3). Figure 2: Going back three commands.
the history one more time. To
repeat just the last command
entered, you can do any of the
following:
n Press the up arrow
n Press Ctrl+P (“previous” on
keyboards without arrow keys) Figure 3: No? But! Oooh…

WWW.ADMIN-MAGAZINE.COM 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE 17
10 TERRIFIC TOOLS – 2021 2FA

Smartphone-based two-factor authentication

Double Your Security


Protect your system from unwanted visitors with two-factor authentication. By Charly Kühnast

If the only protection between For Open Authentication (OATH) Time (UTC) [1] – exists on the two
an attacker and a user account is and has been an Internet Engi- systems involved (smartphone
a password, security-conscious neering Task Force (IETF) stan- and computer console). Reply
administrators start to get ner- dard since 2011. yes since all systems today use
vous – and rightly so. Although Network Time Protocol (NTP) to
strong passwords can be enforced, Getting Started synchronize their time.
carelessness cannot be ruled out. Next a QR code (Figure 1) ap-
Two-factor authentication (2FA) For this article, I am using Ubuntu pears, which you scan with a One-
provides additional protection 20.04, but the procedure is very time password (OTP) app that
against unwanted visitors, even if similar on other distributions. You you install on your smartphone;
a user chooses a weak password. have a Linux client and a server. an OTP is only valid for a single
While the user’s password remains On the server, which goes by the
as the first authentication factor, a name of influx in this example, I
six-digit numerical code with a lim- have an account belonging to user
ited validity period generated by a bob. Bob has been logging in with
smartphone authenticator app adds a password only. However, his
a second factor. organization now wants to switch
In this article, I will show how to Bob’s account to 2FA.
require a one-time code at login I’ll start by installing the authen-
(in addition to the user’s pass- tication module on Bob’s client
word) by creating an app on the (Listing 1, line 1) and then log
user’s smartphone. This procedure in as bob and start the module
was developed by the Initiative (line 2)
Photo by Scott Webb on Unsplash

The module first prompts you to


Listing 1: Installing Authentication Module decide whether the authentication
01 $ sudo apt install libpam‑google‑authenticator should be time-based. It wants Figure 1: The QR code generated by Google
02 $ google‑authenticator to know if the identical time – in Authenticator can be scanned using an OTP app
terms of Coordinated Universal like FreeOTP.

18 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
2FA 10 TERRIFIC TOOLS – 2021

Listing 2: Modifying /etc/​s sh/​s shd_config


UsePAM yes
[...]
ChallengeResponseAuthentication yes

Listing 3: Editing /etc/​p am.d/​s shd


[...]
@include common‑auth
Figure 2: Unlike Google Authenticator, Red Hat’s FreeOTP is an open source application. auth required pam_google_authenticator.so
[...]

use. There are plenty from which You need to complete these steps
to choose; you can use any app for each user on the system who Next, edit the /etc/pam.d/sshd file,
that uses the Time-based One- will be using 2FA. On the client again working as root. After the @
time Password (TOTP) protocol. side, all the work is done; time to include common‑auth line at the top
TOTP generates time-limited, work on the server. of the file, add the following line:
one-time passwords based on the
Hash-based Message Authentica- Modifying PAM auth required pam_google_authenticator.so
tion Code (HMAC). For example,
Google Authenticator is a very To enable 2FA access, you need to The file should now look like
popular OTP app, although it is modify two configuration files, for Listing 3.
not open source. which you need root privileges. Now type the command
For this example, I will install the First, modify the /etc/ssh/sshd_
FreeOTP app developed by Red config file (Listing 2). Find the systemctl restart ssh
Hat, which is available for both two lines that begin with UsePAM
iOS [2] and Android [3], on the and ChallengeResponseAuthentica‑ to start the SSH service. At the
smartphone (Figure 2). After you tion and make sure that both end next login attempt via SSH (Fig-
scan the code, a new button will with yes. ure 4), the server now not only
appear in the app that lets you
generate a one-time password on
demand with a validity period of
30 seconds.
Now set aside the smartphone and
return to the console. Below the
QR Code in Figure 1, you will find
a number of emergency scratch
codes. If you lose your smart-
phone, you can still log in with
these codes to generate a new QR
code and start over. Each of the
emergency scratch codes can only
be used once. Keep these codes in
a safe place. Figure 3: Yes (y) is the right response to all of Google Authenticator’s questions.
Google Authenticator will now
ask you a series of security ques-
tions, all of which you can safely
answer with y (Figure 3). The
idea is to limit the number of log-
ins per time interval, but at the
same time ensure a certain toler-
ance for time differences between Figure 4: In addition to the user password (Password:), the login dialog now also prompts you for
client and server. the one-time password (Verification Code:).

WWW.ADMIN-MAGAZINE.COM 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE 19
10 TERRIFIC TOOLS – 2021 2FA

Listing 4: Modifying /etc/​p am.d/​l ogin Passwordless Login reads @include common‑auth by
adding a hashtag (#) at the start of
[...]
@include common‑auth Going back to logging in via SSH, the line:
session optional pam_motd.so noupdate many users prefer passwordless
# insert this line: access via public key authentica- #@include common‑auth
auth required pam_google_authenticator.so tion. To do this, the user bob en-
[...]
ters the command Then run the systemctl restart
ssh command to restart the SSH
Listing 5: Modifying /etc/​p am.d/​g dm-password ssh‑keygen ‑t rsa ‑b 4096 service. When Bob now logs on to
[...] the server, he does not have to en-
@include common‑auth on their client to generate a key ter a password, but he does have
# insert this line: pair (Figure 5). to enter the one-time password
auth required pam_google_authenticator.so
After that, the command from the smartphone app.
[...]

ssh‑copy‑id bob@influx
Conclusions
prompts for the user password
(Password: in Figure 4), but also is sufficient, followed by the input Security is not witchcraft. As shown
the one-time password (Verifica‑ of the current password. Bob can here, even simple mechanisms such
tion Code:), which you generate now log on to the influx server as 2FA can make logging on to a
with Google Authenticator. without entering a password. system far more secure. 2FA gives
Passwordless login can also be you additional protection against
Console Login combined with 2FA. To do this, unwanted visitors, even if users
change the two configuration files choose weak passwords. n
My changes so far only apply to on the server that I discussed
access via SSH. If you want to en- previously. First open /etc/ssh/ Info
able 2FA for the local login (the sshd_config and enter the follow- [1] UTC: [https://​­www.​­timeanddate.​­com/​
console) in addition to the remote ing line at the end of the file: ­time/​­aboututc.​­html]
login (the smartphone), you need [2] Apple iOS: [https://​­apps.​­apple.​
to change the /etc/pam.d/login file AuthenticationMethods U ­com/​­us/​­app/​­freeotp‑authenticator/​
(Listing 4). publickey,keyboard‑interactive ­id872559395]
To do this, insert the following line [3] Android: [https://​­play.​­google.​
Second, edit /etc/pam.d/sshd. Here ­com/​­store/​­apps/​­details?​­id=org.​
auth required pam_google_authenticator.so you need to disable the line that ­fedorahosted.​­freeotp]

after the @include common‑auth line.


The session optional pam_motd.so
noupdate line is used to display no-
tifications (Message of the Day); it
is not available on all systems.

Gnome Display Manager


If your console system uses a
Gnome graphical user interface,
you can also enable 2FA authen-
tication at login time. To do this,
you make the same changes previ-
ously discussed, but in a differ-
ent file: /etc/pam.d/gdm‑password
(Listing 5). After a restart, Gnome
will now prompt you for the sec-
ond factor at login time. Figure 5: For a passwordless login, Bob generates a key pair on the client.

20 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
ugrep 10 TERRIFIC TOOLS – 2021

Search more efficiently with ugrep

Tracked Down
Searching for text in files or data streams is a common and important function. Ugrep
tackles this task quickly, efficiently, and even interactively if needed. By Karsten Günther

Grep is one of the oldest Unix are relatively slow, since they can span consecutive lines, a
commands. The abbreviation first need to unpack the archive. thing that many other grep vari-
“grep” stands for Global/​Regular However, all grep variants used ants cannot do. By default, ugrep
Expression/​Print or Global search on Linux can also read data from assumes Unicode as the encoding
for a Regular Expression and Print pipes via the standard input for the search data.
out matched lines. It picks up on channel and write the results to Ugrep supports archive types in-
the syntax of the original Unix the standard output channel for cluding CPIO, JAR, PAX, TAR, and
editor, QED, which used g/re/p to searching in archives (Listing 1). ZIP, compressed with all common
search for patterns in text files. In methods (BZIP, GZ, LZ, and XZ).
addition to fixed search terms, it ugrep In addition, you can use filters to
can also search for patterns with prepare data in special formats
wildcard characters. The GNU vari- Ugrep can do all of this and more in advance. For example, PDF
ant of grep is normally installed on without explicitly unpacking the documents can be converted to
Linux. It extends the features of data streams. In addition, the text with a filter, before ugrep per-
the original grep in some places, program is known for its excep- forms the search.
for example, allowing recursive tionally fast processing speed. To Like all grep variants, the program
searching in directories. speed up the search, it uses mul- is largely controlled by options.
Another variant of grep, agrep tiple threads if necessary. For most options, as usual, there
(approximate grep) [1], extends On Debian and Arch Linux, setting is a short form (‑<O>) and a long
text searching to include fuzzy up ugrep is easy. Debian has the form (‑‑<Option>). Table 1 summa-
searches. It also finds near misses tool in its repositories; with Arch rizes the most important options.
as long as the differences are be- Linux, you can use the AUR. For all Besides all of this, the developer
low a specified threshold, known other distributions, you will have suggests a number of alias con-
as the word distance. This is cal- to install ugrep from the source
culated from the necessary permu- code [2]. The commands required Listing 1: Archive Search
tations, deletions, and additions for this are shown in Listing 2. $ zcat archive.gz | grep <pattern>
of letters that convert the search Ugrep is programmed in C++,
pattern into the actual data. has been around for several
In addition, there are some vari- years, and is available not only Listing 2: Installing ugrep
© Kurhan, 123RF.com

ants of grep that also find search on Linux, but also on other op- $ git clone https://github.com/Genivia/ugrep
patterns in certain archive types, erating systems. Search patterns $ cd ugrep && ./build.sh
$ sudo make install
such as ZIP files. These programs specified as regular expressions

WWW.ADMIN-MAGAZINE.COM 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE 21
10 TERRIFIC TOOLS – 2021 ugrep

structs for the .bashrc to ensure ugrep reads in a configuration file ing to specify them at the com-
compatibility with GNU grep, for (by default $HOME/.ugrep) which mand line every time.
example (see Table 2). Some of can contain special settings. This Ugrep supports several search pat-
these short forms rely on the ug means that important presets can tern variants, which you enable
command variant. In this form, be applied implicitly without hav- through appropriate options (see
the “Patterns” box). Besides simple
Table 1: Important Options and extended regular expressions
‑a Interpret data as text like GNU grep, ugrep also supports
‑c Match count Perl regexes and word patterns. In
‑e <pattern> Search for specified pattern (can specify multiple patterns) addition to these default patterns,
‑E Interpret search patterns as extended regular expressions which always define positive pat-
(default) terns, ugrep can also use negative
‑‑encoding=<encoding> Set encoding for data patterns (exclusion patterns).
‑f <file> Load search pattern from specified file They let you, for example, ignore
‑F Interpret search pattern as string (special characters are matches if they occur in com-
considered as text) ments. Files whose names match
‑‑filter=<filter> Pre-filter based on specified filter criteria a certain pattern can also be ex-
‑G Interpret search patterns as simple regular expressions cluded from the search. The ‑‑not
‑i Ignore case in pattern option has a special effect: All pat-
‑N <pattern> Define negative search pattern
terns to the right of it are used by
ugrep as exclusion patterns.
‑‑not Interpret all of the following search patterns as exclusion
patterns
‑O <extension> Edit only files with the specified extension Extensions
‑P Interpret search patterns as Perl expressions
‑‑pager=<pager>
In many places ugrep extends the
Set pager for terminal output
other, classic program versions.
‑Q[<delay>] Incremental search with optional delay
The new features for patterns in
‑R Recursive search
file names (“globbing”) are par-
‑w Word search ticularly interesting. For example,
‑X Output in hexadecimal form **/ stands for any number – even
‑z Unpack compressed data streams in advance zero – directories. At the end of
‑Z<Criteria> Fuzzy search with set criteria for allowed deletions, inser- a path definition, /** stands for
tions, or substitutions
any number of files. The special
case \\? addresses zero characters
Table 2: Suggested Alias Constructs or one. In the man page, the glob-
Alias Function bing section summarizes these
alias uq = 'ug ‑Q' Interactive, incremental search features and also gives numerous
alias ux = 'ug ‑UX' Binary search examples.
alias uz = 'ug ‑z' Search in (compressed) archives Special environment variables
alias ugit = 'ug ‑R Grep for Git let you additionally control the
‑‑ignore‑files' behavior of ugrep. $GREP_PATH sim-
Compatibility with classic variants plifies access to so-called pattern
alias grep = 'ugrep ‑G' Search with simple regular expressions files (i.e., files that define search
alias egrep = 'ugrep ‑E' Search with extended regular expressions patterns); the ‑f option enables
alias fgrep = 'ugrep ‑F' Search without regular expressions this feature. Patterns in external
alias pgrep = 'ugrep ‑P' Search with Perl regular expressions files are a good way to keep com-
Search in compressed data
plex search patterns permanently.
alias zgrep = 'ugrep ‑zG'
Some options, including ‑Q, can
Archive search with simple regular expressions
use an external editor that the key
alias zegrep = 'ugrep ‑zE' Archive search with extended regular expressions
combination Ctrl+Y starts. If the
alias zfgrep = 'ugrep ‑zF' Archive search for strings
$GREP_EDIT environment variable is
alias zpgrep = 'ugrep ‑zP' Archive search with Perl regular expressions set, ugrep uses the editor defined

22 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
ugrep 10 TERRIFIC TOOLS – 2021

Patterns With this type of search, each addi- the actual contents, you have to
tional letter specified further refines unpack these archives, which is
The term “pattern” usually appears in
the search and reduces the number done either by a filter (more on
multiple contexts with different mean-
of matches. All lines that match the that later) or the ‑z option, often
ings in search programs like ugrep.
previous entries are then displayed. combined with ‑r for recursive.
Patterns in file names determine which
For this form of search, ugrep pro- Ugrep supports fuzzy searching
files the program processes. The file
vides a special interface that you with the ‑Z option, which may be
content patterns are the actual search
enable using the ‑Q option. As an followed by a number appended
patterns for which it searches the pro-
argument of ‑Q, you can specify a directly without spaces. The latter
cessed files. With ugrep, these may also
small delay that ugrep waits for be- determines the degree of fuzziness,
be across lines. Ugrep and some other
fore evaluating the input. that is, the permissible number of
search programs also support nega-
tive patterns. They are used to exclude
The Q> prompt now appears in the errors (omitted, added, swapped
files or not to display corresponding upper left corner of the terminal. characters). The default is 1. Larger
matches. In fact, ugrep takes this pro- Everything you type is interpreted values quickly lead to many ad-
cedure quite far: In the program’s docu- by ugrep as a search pattern; each ditional hits, but this sometimes
mentation, there is a separate section, additional keystroke refines the makes the results unusable.
Search this but not that with ‑v, ‑e, ‑N, search. Typos can be corrected However, the type of allowable er-
--not, ‑f, ‑L, ‑w, ‑x, that deals with the with the backspace key. In the rors can be specified: With a prefix
finer points of this subject. example from Figure 1, we called of + or ‑, the specification refers
ugrep with the ‑ZQ (fuzzy, inter- only to additions or omissions,
active) options and searched for respectively. The tilde (~) groups
there; otherwise the one defined “alles” (“everything” in German). several errors. ‑Z~‑2 means that
in $EDITOR is used. Due to the fuzzy search, ugrep up to two omissions or swaps are
The $GREP_COLOR and $GREP_COLORS also finds “alpes”, “alls”, “ales,” allowed. The ‑‑sort=best option
environment variables let you and so on. sorts the output so that the files
specify when and how ugrep color This feature is so powerful that with the best matches appear first.
highlights matches when using ugrep in this mode can sometimes Ugrep uses some function keys for
the ‑‑color option. The GREP_COL‑ even replace a pager for display- special tasks in interactive mode.
ORS section in the man page de- ing output. For example, man ugrep
scribes this in more detail. | ugrep ‑Q displays the man page
But the really outstanding exten- of ugrep and lets you define ex-
sions in ugrep are the incremen- actly which search term it should
tal search feature and the user display. The output can also be
interface. shifted vertically with the arrow
keys; Esc ends the mode again.
User Interface On top of that, this option can be
combined with others. In case you
Grep programs are usually used need more than the ability to see
interactively in command lines, just the line with the match, you
scripts, or pipes; in many cases can add two context lines before
the results then act as input for and after the match to the output
further commands. This also works using ‑C2. In this form, ugrep is
without any restrictions in ugrep. extremely useful as an alias (alias
In addition, the developer has also q2='ug ‑C2 ‑G '), shell function,
paid great attention to extended in- or script.
teractive usability. For example, in- The ability to search archives is a
cremental searching is currently an similar case. Many modern docu-
absolutely unique selling point of ments are in complex formats like
ugrep. The user interface used for EPUB, ODF, etc. There, the op-
this was modeled on editors such tions usually only act on metadata
as Emacs and is normally reserved in the document containers – Figure 1: Ugrep enables interactive, fuzzy, and
for GUI programs. often ZIP archives. To search in incremental searches.

WWW.ADMIN-MAGAZINE.COM 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE 23
10 TERRIFIC TOOLS – 2021 ugrep

For example, F1 activates the on- or ‑‑filter‑​magic‑​


line help (Figure 2) where ugrep label=​<Label>:​
displays the current keyboard short- <MagicByte> option.
cuts. You can enable additional op- In the form ‑‑fil‑
tions by calling them in this mode. ter=​<filter>, the
For example, after pressing F1, the <filter> consists
key combination Alt-Left+Shift+Z of an expres-
activates fuzzy searching. sion of the form
Invoked with the ‑‑save‑config <Ext>:<command
option, the program creates line>. <Ext> is a
the $HOME/.ugrep configura- comma-separated
tion file. If necessary, you can list of file name ex-
create another file using tensions for which
‑‑save‑config=/<path>/<file>). you want the filter
Similarly, ‑‑config reads configura- to apply, such as
tion files. Calling ugrep as ug auto- .doc,.docx,.xls.
matically parses the configuration. The * character is
Since configuration files are a a special case that
powerful means of controlling acts on all files,
ugrep, there is also the shorthand especially those for
‑‑‑<file> for loading. You can cre- which there are no
ate configuration files with certain other filters.
preset options with the following The <command> line
command: must be constructed
to read input via the
$ ugrep ‑<option> [...] ‑‑save‑config standard input chan-
nel and write the re- Figure 2: The ugrep help function conveniently comes with a built-in
The configuration files are well sults to the standard configuration mode.
commented and can be easily output channel. Typ-
customized with a text editor if ical commands include cat (pass Multiple filters can be specified
needed. everything) and head (pass the first as comma-separated lists. A com-
lines of text), but tools like exiftool bined definition for PDF and Of-
Filters (extract and pass metadata) or fice documents might look like the
pdftotext (extract text from PDFs) one shown in Listing 3.
Ugrep tries to determine the type can also be included this way. Some
of an examined file based on the commands, like pdftotext, require Conclusions
data it contains, the file name options to work correctly – in this
extension, and the signature (the case pdftotext % ‑. You then need Ugrep belongs on every computer.
“magic byte”). In this way, the to quote spaces in the command It replaces and complements the
search can be specially prepared lines to protect them: standard commands quite excel-
for certain file types (i.e., filtered). lently, and anyone who has to
Here the filter extracts the text ‑‑filter='pdf:pdftotext % ‑' deal with text searches should
components from the data familiarize themselves with it.
streams. These filters execute a The ‑‑filter‑magic‑label=​<Label>:​ The incremental search alone is so
command, a script, or a specific <Magic> option lets you extend useful that it more than justifies
function, with pipes if necessary. the filtering mechanism to data the minimal training time. n
They are prepended to the search streams that ugrep then classifies
process via the ‑‑filter=<Filter> by reference to the magic byte. Info
Details can [1] agrep:
Listing 3: Combined Filter Definition be found [https://​­linux.​­die.​­net/​­man/​­1/​­agrep]
‑‑filter="pdf:pdftotext % ‑,odt,doc,docx,rtf,xls,xlsx,ppt,pptx:soffice ‑‑headless ‑‑cat %" in the man [2] ugrep:
page. [https://​­github.​­com/​­Genivia/​­ugrep]

24 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
GET TO KNOW ADMIN
ADMIN Network & Security magazine
is your source for technical solutions
to real-world problems.
ADMIN is packed with detailed
discussions aimed at the professional
reader on contemporary topics including
security, cloud computing, DevOps, HPC,
containers, networking, and more.

Subscribe to ADMIN
magazine and get 6 issues
delivered every year

Want to get ADMIN in your inbox?


Subscribe free to
ADMIN Update
and get news and technical articles
you won’t see in the magazine.

You might also like