Professional Documents
Culture Documents
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!
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
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
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/]
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
6 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
Tuptime 10 TERRIFIC TOOLS – 2021
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
8 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
dstask 10 TERRIFIC TOOLS – 2021
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
WWW.ADMIN-MAGAZINE.COM 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE 17
10 TERRIFIC TOOLS – 2021 2FA
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
18 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
2FA 10 TERRIFIC TOOLS – 2021
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]
20 10 TERRIFIC TOOLS FOR THE BUSY ADMIN: 2021 EDITION – THANKS TO OUR PARTNER TUXCARE WWW.ADMIN-MAGAZINE.COM
ugrep 10 TERRIFIC TOOLS – 2021
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
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