101 Cool Linux Hacks

Download as pdf or txt
Download as pdf or txt
You are on page 1of 100

2021 EDITION

ELI Ls E

cf CU uh \ Discover the
ana ae TO secrets of
SAO SOUS — the experts
A Linux Distribution
For Professionals

openSUSE Leap 15.3


Leap is a desirable distribution for IT
WELCOME ae

i COOL
IAN ats
This Linux Magazine special edition promises you “101 Linux hacks,” and we'll
certainly deliver — check the table of contents on the following page for a list
of all the gems we present inside. But what exactly is a “hack”?
In today’s world where Windows is the dominant desktop operating system,
the decision to use Linux is the first and most important hack. In addition
to that:
ulflcan use it to solve a problem or get some work
done faster than before, then it’s a hack.
u lf the way it works is unexpected, it’s very certainly a
hack.
ulf it teaches me a new and interesting way to use my
Linux machine, it’s a hack.
= When it makes me grin, because it’s so obvious that
only a geeky Unix person would ever think of doing
things this way, | add it to my list of anecdotes (and yes, it's a hack).
The definition of a hack is a matter of taste, and so is our choice of hacks
for this collection: Many authors have contributed, and together we have
assembled a mix of new tools, new configuration options for old tools, and
new ways to use familiar software. We've organized our hacks
into 10 categories so that you'll find them quickly when
you go back to search for them.
We call the final category “Having Fun,” because we
hope that, in addition to profiting from these clever
new hacks, you'll also enjoy yourself while you
browse this issue.

Hans-Georg EBer
Editor-in-Chief

101 LINUX HACKS - 2021 EDITION 3


NY GCC Te CU
Cure the Caps Lock Disease HACK 10 Find Your Files with DocFetcher 7
HACK2 Latte Dock: The Best Dock for KDE HACK 11 Organize Your Ideas with Zim, the Desktop Wiki 18
HACK3 KDE Window Hacking HACK 12 Track Time with Chrono 20
HACK4 — Global Menu for KDE Programs HACK 13 Launch Programs Inside a VirtualBox VM. 20
HACKS — Zoom Everything on Your Screen HACK 14 Bring Order to Your Photo Collection with digikam 21
HACK6 —Zoominto the Gnome Desktop HACK15 Create a Cheap Timer with sleep 2
HACK7 Use Virtual Desktops, Memorize the Hotkeys HACK 16 Find and Install Online Fonts 2
HACK8 — Caffeine Helps Your Linux PC Stay Awake HACK 17 Barrier: One Keyboard/Mouse Combo Is Enough 23
HACK9 — What Would That Resolution Look Like? HACK 18 Self-Organization with GTG 4

£433 0a UU oo
HACK 19 Clone Itwith Clonezilla 21 HACK25 Repair the Debian Package Database 34
HACK 20 Write ISOs to USB Sticks 28 HACK26 Learn the vi Editor Basics 36
HACK 21 Get a Quick Machine Configuration Overview 29 HACK27 Follow File Updates 37
with inxi HACK28 Monitor Your System in a Terminal 37
HACK 22 Repair Your Bootloader HACK29 Visualize ddrescue’s Progress 38
HACK 23 Clean House with Stacer HACK30 Run dmesg with the Right Options 38
HACK 24 Search and Find with the fd/find Tools HACK31_ Where Did You Mount That Disk? 39

SECURITY & PRIVACY = 40


HACK 32 _ Install and Run Tor Browser HACK 42 Monitor Your Network with Nutty 49
HACK 33 Permanently Wipe Files from Your Hard Disk cu HACK 43 DIY Network Configuration 49
HACK 34 Disable Webcam and Microphone 42 HACK 44 Advanced Tracing with traceroute and LFT 50
HACK 35 Disable Password-Based SSH Logins 43 HACK 45 Dig a Tunnel with sshuttle 51
HACK 36 Encrypt Your Emails with GPG 43. HACK46 Send Files Without Knowing the Target's IP 51
HACK 37 Enhance Security with sudo Options 44 HACK 47 Check Your DNS Serverwith DNSDiag 52
HACK 38 Use Two-Factor Authentication 46 HACK 48 Runa Simple HTTP Server: weborf 53
with Authenticator HACK 49 Use screen in SSH Sessions 53
HACK 39. Start Your Training with Web Security Dojo HACK50 Access a Remote PC's Shell Session 54
HACK 40. Lock Your Screen, Always HACK51 Slow sudo? Check Your Hostname 56
HACK 41 Use ccrypt for Quick Configuration
Encryption HACK52 Use Network Manager's CLI

101 LINUX HACKS


- 2021 EDITION
HACK'53 ConfigureYour Shell History 59 HACK 60 Command References at cheatsh 64
HACKS4 ProgressBars for Standard Tools 60 HACK 61 Highlighting Instead of Grepping 65
HACK55 Replacetop with htop 60 HACK 62 Add File Type Icons to Your File Listing 66
HACK'56 Super-Fast Terminal Emulator 61 HACK 63 Coo! Retro Term Brings 67
HACK 57 Universal Unpacker 61 Back the 80s
HACK 58 _ List Files
with Style 62 HACK 64 The fish Shell 87
HACK59 ASCII Browsing
with Browsh 63 HACK 65 Use a Sub-Shell 68
HACK 66 Start
the Right App 68

PUBLISH OR PERISH = 70
HACK 67 Install the draw.io Diagram Editor Locally n
HACK68 Record Screencasts with Peek 7
HACK 69 Edit Your Videos with VidCutter 3
HACK 70 Create Long Documents with Styles 2B Ht eS
HACK71_— Edit HTML with Live Preview in Brackets 74
HACK 72 Create E-Books with Sigil 5 HACK 75 Safely Power Off Your Machine 78
HACK 73 Test Alternative CMSs with Docker 16 HACK 76 Make Files Immutable or Append-Only 79
HACK74 How Fast
Is Your Server? 76 HACK 77 Mounttar.gz
and zip Archives 79
HACK 78 Recover Deleted Files with PhotoRec 80
and TestDisk
HACK79 Change Root into Second Distro 81
HACK 80 Bind Mounta Directory with New Permissions 81
HACK 81 Run Binaries from a Different Linux Installation 82
HACK 82 Don't Be So Case-Sensitive 83

qn WITH CODE = 84 HACK 93. Interesting Terminal Output


for Your Visitors 91
HACK94 Scan the Network Like @ Script Kiddie 92
HACK 83 Run C Code from the Command Line 85 HACK 95 Drive
eens
Your M Lander
eee—in ASCII! 92

HACK 84 Edit BinaryBinary Files


Files with hx 85 eee
HACKS7 Explore, Expand, Exterminate: Play Star Ruler2 =93
HACK 85 _ Edit Your Text Files with Textosaurus
HACK86 Manage Your git Repository
with GRV
86
86
HACK98. Edit Files Like : It’s the 90s Again i
4
HACK87 Make git: interactive 87 ee99 Read
HACK eeeOld Unix Books 4cs
HACK 88 Replace hexdump with a Colorful Tool 87 ick a Reto Screensaver
HACK 101 The Good Old Days: Linux From the 1990s 96
HACK 89 Textadept Works in Graphics and 88
Text Mode
HACK 90 Perform Dynamic Code Analysis with 88 WELCOME 3
SystemTap
HACK 91 Count Lines of Code in Your Project 89 MASTHEAD / AUTHORS 98
HACK 92 Fix Disturbing Indentation and More 89

101 LINUX HACKS - 2021 EDITION


4 2 DESO is
Your desktop environment
La rNe) Gal
is more than a window (on RUe Nee ere a Sr
manager: When you pick the nner
right tools and know how to Latte Dock: The Best Dock for KDE
personalize and use them, Pye
you'll be more productive and Cova Wr romas eve ar
do things with your computer Nee
that others deem impossible. Te LOL ae
IC uy
For starters, get rid of Caps Ae a)
rock Paras uu aC
Xena
PREC)
HACK 7
Use Virtual Desktops, Memorize the Hotkeys
Ney
Pei mO Maange EWE
HACK 9
What Would That Resolution Look Like?

101 LINUX HACKS


- 2021 EDITION
DESKTOP MODDING ~—~—

Curing the Figure 2


Caps Lock Disease
Are you old enough to say “the problems
with keyboards started when IBM moved the func-
tion keys from the left (Figure 1) to the top”? That
happened in 1986 when the IBM PC AT replaced the
PC XT and the then-leading personal computer man-
ufacturer introduced the new keyboard layout, which
has remained the standard ever since. New functions
in Microsoft Windows 95 made keyboard producers
add three new keys, and some modern keyboards
have a Fnkey inspired by such keys on restricted
notebook keyboards. Figure1
But what's the worst
problem with key-
boards both old and
new? In my view, itis The conservative treatment of the.
certainly the Caps Lock “Caps Lock disease” is to transform
key. Its purpose is to the key into a second Left Shift key.
mess up text you enter That way, if you press Caps Lock in-
in an Office document stead of Shift, you will still geta capi-
or on the command talized letter. You can use the xmodmap
line when you type without looking at the screen. Once command to change the key’s table entry:
activated, it will transform every lowercase letter into an xmodnap ~e “keycode 66 = Shift_L NoSynbol Shift_L”
uppercase one and vice versa. When you detect the mis-
take, you need to get rid of all the entered text and type it Ifinstead you want to completely disable the key, use
again (with Caps Lock off). Only network trolls who fee! the following shorter command:
like typing whole paragraphs in all caps can appreciate setxkbmap -option caps:none
that key. (If you rely on accessibility tools to help you type,
Caps Lock is not helpful either, since it does not grant ac- After that change, pressing Caps Lock will have no ef-
cess to the secondary bindings of non-letter keys. Instead, fect whatsoever. Notice however that the change only
sticky Shift, Ctrl, and Alt keys do the job.) affects the current X session. In order to make it perma-
The xmodmap tool can inform you about the Caps Lock nent, you need to use your desktop environment's au-
key’s current behavior: tostart mechanism. Adding the line to ~/.bashre will not
$ xmodnap -pke | grep -u 66 work (properly): It will generate a lot of error messages,
Keycode 66 = Caps_Lock NoSymbol Caps_Lock because both commands expect a working X server
and a properly set DISPLAY variable; they fail when run
The culprit is Caps_Lock. There are several ways that you in text mode (see the “Killing Caps Lock in Text Mode”
can get rid of it: Some of the desktop environment con- box). Here's how to make it permanent:
figuration tools let you configure Caps Lock behavior + Under KDE, create a file kil Icapslock.sh in your »/bin/
(Figure 2 shows how to do it with Ubuntu’s “Gnome folder and write the command into that file. Then,
Tweaks” tool after installing the gnome-tweaks pack- from the Start menu, search for “startup,” pick Auto-
age with apt), but | will focus on two quick solutions start, then click Add Script, and enter the full path to
that require single shell commands. killcapslock.
sh.
+ Gnome users run the gnome-sessi on-properties com-
eect mand. Click on Add, then provide an informative title
in the Name field, and enter the command in the
If you happen to work in a text mode session (without X), the Command field.
xmodnap and setxkbmap commands will be useless - they cannot + Under Cinnamon, search for “startup,” pick Startup Ap-
influence the keyboard settings in console mode. Instead, what plications, then click the + button, and choose Custom
you need is loadkeys. Normally, this program is used to switch Command. Provide an informative title in the Name
between alternative local keyboard layouts, such as: field, and enter the command in the Commandfield.
sudo loadkeys us # US layout Now the future looks bright: Caps Lock won't trouble
sudo loadkeys uk # UK layout you again.
sudo loadkeys de # German layout
By Hans-Georg EGer
However, you can also use it to change a single key setting. Use
the following command to make Caps Lock behave like Shift:
echo -e “keynaps 8-127\nkeycode 58 = Shift" | sudo loadkeys -
101 LINUX HACKS - 2021 EDITION
Latte Dock: The Best Dock for KDE
One of the best things about KDE ~ and there are Figure3
many ~is the functionality contained within the panel.
It works well horizontally stretched across the entire
display or as a small panel across half. It works well
vertically, as well as floating in the middle. You can
have more than one, and each one can be configured
to do as much or as little as you want. But the default
KDE panel can still feel a little utilitarian, partly be-
cause it's nothing like the panel in macOS. This is why
there are perhaps so many panel replacements that Neos
look more like Apple's similar dock.
Latte Dock is the best alternative I've seen for KDE
(Figure 3). Unlike most panel replacements, it has got a
comprehensive set of configuration options that mimic
much of what KDE's regular panel does. By default, it
will appear in the middle of your screen’s bottom bor-
der when your pointer gets close. The icons for running OE
applications appear and enlarge as you roll over these
in beautifully animated transitions. The same happens
when you open the configuration panel, which allows
you to change the location of the panel and its align-
ment. You can place it anywhere and get the icons to.
center exactly as you wish. You can also control the
transitions and zoom levels, as well as enable or dis-
able the panel background and running application To try it, install the package via sudo zypper in latte-dock
highlight modes. On a high DPI desktop, it looks abso- (openSUSE) or sudo apt install 1atte-dock (Ubuntu, Mint,
lutely fantastic. The SVG icons scale perfectly, and re- and Debian). Then run the latte-dock command.
placing the old KDE panel with this is a serious tempta-
tion, despite it not fully supporting functional applets By Graham Morrison
like monitoring tools or desktop pagers. https://store.kde.org/p/1169519/

KDE Window Hacking


KDE's window manager lets you do lots of crazy Alt+F3 again to open the win-
things to windows. Some of them are pretty useful. dow’s configuration menu.
Right-click on any window's titlebar, and a menu will Within Window Specific Settings (or Special
pop up. Apart from the options to minimize, maxi- Window Settings) and Application Specific Settings
mize, and close the windows, you'll notice the More (also called Special Application Settings), you have all
Actions option. The Keep Above Others and Keep manner of options to fix the application window's po-
Below Others options are self-explanatory, but you sition and size. You can make a window stick to a cer-
can also make a window Fullscreen, and it will be tain area of your screen and become unmovable. At
maximized; the application's titlebar and any other the same time, you can adjust its size to the pixel. You
desktop elements (like panels) will disappear, giving can configure things so that, when you launch a cer-
you maximum workspace. If the application doesn’t tain application, it always opens in a certain place,
offer you a way to exit full screen mode, press Alt+F3 maximized, or shaded. You can make the application
and use the menu to deactivate it. so it won't close, or you can choose actions from
You can also “shade” the window, which means it dozens of other options.
will roll up like a blind, leaving only the titlebar visible.
Another alternative is to remove the border and titlebar, By Paul Brown
leaving a bare window with no decorations. To recover
borders and the titlebar, select the window and press

101 LINUX HACKS


- 2021 EDITION
Global Menu for KDE Programs
A default KDE Plasma desktop has a panel at the bot- will show up on the screen’s left. You can narrow
tom of the screen, a start button holding menus at the your search by typing “global” into the search box.
bottom left, and a tray on the right - all quite conven- When you see the Global Menu widget, double-click
tional, boring, and even Windows-y (see Figure 4). But on it, and it will be added to the panel. (You may
Plasma can be configured to look like anything, even think that the action was not successful — at least
like Ubuntu’s defunct Unity, Gnome, macOS, or what- that’s what happened to me. If a small circled “1” ap-
ever else rocks your boat. pears in a corner of the widget’s icon, you were suc-
cessful even though the panel
Figure 4 still looks empty.)
Running applications con-
tinue to have their own me-
nubars. Close and reopen
them, and you'll see how now
their menus have moved from
the application window to the
upper panel you just made.
With KDE Plasma versions be-
fore 5.13, this only works with
native KDE apps, but newer
releases support the feature
for other programs, too. This
is especially relevant for GTK-
based applications.
To make the effect even
more striking, click the Start
menu on the bottom panel
and pick System Settings or
Settings | Appearance. Under
Both Unity and macOS use a global menu: It is the Global Theme, choose Breeze Dark and click Apply.
menu that appears in a bar at the top of the screen and You will end up with something like Figure 5.
shows a selected application’s options, instead of hav-
ing them in a bar along the top of the application.
To create global menus in
Plasma, first right-click in any
free space on the Plasma
desktop and select + Add
Panel| Empty Panel from the
pop-up menu. Usually, the
panel will appear at the top
of the screen, because the
bottom is already filled with
the default Plasma panel. If it
has popped up anywhere
else, right-click on the panel,
choose Edit Panel, and then
click and hold the Screen
Edge button and drag the
panel to the top.
Once you have placed the
panel, right-click on it again and
click on + Add Widgets. A bar
with all the available widgets

101 LINUX HACKS - 2021 EDITION


DESKTOP MODDING

Zoom Everything on Your Screen Fix KDE


Many applications let you zoom the content they dis- KDE, like Gnome, needs some
play; for example, in Firefox and LibreOffice, you can extra work so you can zoom smoothly. You will need
press the Ctrl key and move the mouse wheel to in- the xbindkeys tool and also dbus-send or qdbus (which
crease or decrease the zoom level. should be preinstalled with KDE).
But sometimes you may need a different kind of Try the following commands:
zooming. Imagine for example that you show a Libre- qdbus org.kde. kglobalaccel /conponent/kuin 2
Office Impress presentation to your audience, and invokeShortcut vieu_zoom_in
there's a detail you want to draw attention to on your
dbus-send --type=method_call --dest=2
slide. You'll have to leave presentation mode and org.kde.kglobalaccel /component/kuin 2
zoom into the slide in Impress’ editing mode, which is org. kde. kglobalaccel
. Component. invokeShortcut 2
not really professional. Luckily, it is possible to zoom string: view_zoom_in
the whole desktop. Depending on your desktop envi-
ronment, you may have to activate the feature. If one of them zooms a tiny bit into the desktop,
you're ready for the next step - on my openSUSE test
Cinnamon Can Do It, Gnome Almost machine only the second command worked. If none
If you use Cinnamon, open Preferences| Accessibility of them works, try to enable the zoom effect as ex-
and click on Enable zoom. Then change the Mouse plained in the “KDE: Enable the Zoom” box.
tracking mode to Cursor pushes contents around: First of all, zoom out again: Just repeat the command
That way mouse movements will not change what that worked, but replace view_zoon_in with view zoom_out.
you see on the screen - until you reach the borders. Then create (or open) the file .xbindkeysre in your home
The default key, called Super, is the Win key next to directory and add the following four lines:
Left Alt. So keep Win pressed and use the scroll wheel
to zoom into your desktop and out again. "cHORKING COMMAND ENDING IN Vieu_zoom_in>”
Gnome has a preconfigured zoom feature; it is alt + b:4
one of the accessibility functions. Press Win+Alt+8 "<HORKING COMMAND ENDING IN view zoom out>"
to enable zooming, then Win+Alt+= to zoom in, alt + b:5
and Win+Alt+- to zoom out. However, you cannot
configure it to change the zoom in small steps, and The first line contains the command for zooming in,
you cannot use the mouse. If you want that to hap- placed between double quotation marks; the third line
pen, check the hack on the next page — it is more is the same but ends in vieu_zoon_out. Lines 2 and 4
advanced. hold the mouse/key combinations: ait is the Alt key (it
will work with both the left and
KDE: Enable the Zoom right Alt keys); b:4 and b:5 are
Scroll Up and Scroll Down on
If zooming does not work at all or if you the zoom is active and you try to move the mouse wheel. (If you want a
want to fine-tune how much KDE the mouse out of the visible area, KDE more complicated combination,
zooms in/out with one wheel move, scrolls so that the mouse pointer stays try control + alt + b:4, for exam-
open KDE's System Settings and go to visible. But try the other options, too: ple; the xbindkeysrc man page ex-
Workspace| Workspace Behavior. Then It's a matter of taste, plains how to use the
click on Desktop Effects. Figure 6 other modifier keys.)
Make sure that Zoom Now start xbindkeys (if
(Magnify the entire desk- you already use it, kill it
top)is activated and click first) and check whether
on the settings icon.
In the new dialog win- zooming with Alt and
dow (Figure 6), change the mouse wheel works.
the Zoom Factor value If so, make things per-
to something between manent by adding
1.01 and 1.20, My sug- xbindkeys to your auto-
gestion for the Mouse start programs.
Tracking option is to set
it to Push: Then, when By Hans-Georg EGer

10 101 LINUX HACKS - 2021 EDITION


DESKTOP MODDING ~~~

Zoom into the Z00M_MIN=1.00


200M_MAX=2. 08
HACK 6 Gnome Desktop Z00M_ADJUST=0.. 05
Gnome’s built-in zoom function, which you enable via
Win+Alt+8, lets you zoom in very large steps: from a 1.0 into a new file ~/. local /zoon-conf ig. This is where you'll
zoom factor to 2.0, then 3.0 and so on (Figure 7). While be able to change the behavior of your new super
you can make things large quickly, it lacks the smooth zoom: The Z00H_ADJUST value will be added or subtracted
transition helpful in a presentation. until you hit the maximum or minimum value.
Luckily, Gnome’s control tool for the command line,
gsettings, lets you query and set the zoom factor with Bring in the Mouse
fine precision. For example, You can already test the new feature by calling ~/bin/
zoom-in and ~/bin/zoom-out from the shell. If ~/bin is in
gsettings set org. gnone. desktop. ally. magnifier 2 your PATH, the shell should find the scripts when you
mag-factor 1.15 call them as zoom-in and zoon-out.
But we want mouse support. If you've read in the pre-
will set the zoom to 115 percent. (Note: that is "a-one- vious hack how to react to mouse wheel movement,
one-y”, not "a-el-el-y” in the command.) If you want to you already know what's coming: You need the xbind~
query the current value, replace set with get, and drop keys tool that you have to install with your package
the number. Now, adjusting the current value (say, in manager (apt install xbindkeys on Ubuntu). Then cre-
order to add or subtract 0.01) is not so simple. I've cre- ate an »/.xbindkeysre file with those four lines:
ated two simple Bash scripts that do the job; they use
the terminal calculator bc to perform the floating-point “«/bin/zoom-in"
additions, subtractions, and comparisons — the shell alt + bid
can only work with integers. “~/bin/zoon-out"
Put the code from Listings 1 and 2 into files ~/bin/ alt + b:5
Zoon-in and ~/bin/zoon-out, respectively, and make
them executable (chnod atx ~/bin/zoon-*). (Depending Like in the KDE zooming hack, this assigns the zooming
on your Linux distribution, you may have to create the commands to the mouse/key combinations, where b:4
»/bin folder.) Then put the three configuration lines and b:5 are Scroll Up and Scroll Down on the mouse
wheel. Check the xbindkeysre man page for more com-
plex key combinations.
Sry mere ey Now start or restart xbindkeys and check whether
zooming with Alt and the mouse wheel works. If so,
!/bin/bash make things permanent by adding xbindkeys to your
[-r ~/.1ocal/zoon-config ] && source ~/.1ocal/zoon-contig
Z0OM_HAX=${200H_HAX:-1. 10} autostart programs.
ZoOH_ADJUST=${Z00H_ADJUST
SCHEHA-org. gnome. desktop. ally Negative Zoom
Zoon=S(qsett ings get $SCHEMA mag-factor) By the way, it’s also possible to use zoom factors below
check=S(echo "zoom < $Z00H_MAX" | be -1) 1.00 (change Z00H_HAX to 0.5 to try this out), but it
if [[ $check -eq 1 ]]; then
Zoom=$(echo "'scale=2; $zoom * $Z00HADJUST” | be -1) doesn’t make much sense - the desktop will shrink and
gsettings set SSCHENA nag-factor $zoon fill the upper left corner of the screen, and the rest of
fi the monitor displays gets filled with gray.

ee
By Hans-Georg EGer
Figure 7
#1/bin/bash
[--r ~/. local /zoom-config ] && source ~/.1ocal /zoon-config
Z0OH_HIN-S{Z0OH_MIN: 1.00}
Zo0H_AOJUST=${Z00M_AOJUST
SCHEMA-org. gnome. desktop. ally
Zoons(gsett ings get SSCHENA nag-factor)
check=$(echo "$zoom > $ZOOH_MIN" | be -1)
if [f Scheck -eq 1 1; then
zoon=$ (echo "sca zoom ~ $200 ADJUST” | be -1)
gsettings set SSCHENA nag-factor $zoon
ft

101 LINUX HACKS - 2021 EDITION 11


DESKTOP MODDING

Use Virtual Desktops, Memorize the Hotkeys


Do you work with virtual desktops? If not, try them. As- Add the Workspace Switcher
suming that you do more with your Linux machine than applet to your panel so that you
run a browser, a mail client, and LibreOffice, it is likely can switch the desktop with a single click.
that your desktop becomes cluttered with windows. If you would prefer to use Ctrl+F1, Ctrl+F2, ete. on
Maybe you minimize some of them to get the chaos Cinnamon, open Preferences| Keyboard from the menu,
under control. Connecting one or two extra monitors switch to the Shortcuts tab, and pick the Workspaces |
would improve the situation, but that requires free Direct Navigation category: You can now define your
space on your desk (and money). own hotkeys that will let you switch to a desktop directly.
Instead of physical, go for virtual. Linux desktop envi-
ronments like KDE, Gnome, and most others have a Gnome
feature called virtual desktop. You can have two or With a Gnome installation, Ctrl+AlttDown (or
more independent areas where you can place your win- Win+PageDown) will bring you to a fresh, new desktop —
dows. There's no need to minimize them; just spread but only after you've opened at least one window on the
them out on as many desktops as you need. current desktop. With Ctrl+Alt+Up (or Win+PageUp), you
can go back to the previous desktop.
KDE By default, Gnome only has a hotkey for switching to
On KDE, press Ctrl+F2 to reach a second (empty) desk- the first desktop (Win+Home), but when you open the
top; Ctrl+F1 brings you back to the original one. If that settings and go to Devices| Keyboard, you can add hot-
doesn’t work, virtual desktops are disabled. Open the keys for further desktops. Ctrl+F1 is not available be-
start menu, type virtual, and select the Virtual Desktop cause some Gnome applications use it to show the
configuration entry. Then click on + Add several times shortcuts available in that program.
until you reach a number of desktops that makes sense: In all desktop environments, each window's menu
Ilike to have at least four of them (Figure 8). KDE auto- will let you move a window to a different workspace,
matically creates more hotkeys (Ctrl+F3, Ctrl+F4, etc.). and there may even be hotkeys for doing that with-
out the mouse. The developers have come up with
multiple ways to configure your desktop’s behavior
(e.g., some program may always open on the second
desktop).
It takes some time to get used to multiple desktops,
but once you know the most important hotkeys by
heart, you'll do many things faster than before.
If you tend to switch between KDE, Gnome, and other
environments or window managers often, it might
make sense to change the settings so that working with
virtual desktops feels the same in every environment -
but if you've already chosen your favorite desktop, sim-
ply get to know its default hotkeys: They are likely to
stay the same for future releases.
By Hans-Georg EGer

Rename the new desktops (for example: Desktop 2, Figure 9


Desktop 3, etc. - or something that reminds you of spe-
cific activities you want to perform on a desktop) and
arrange them in rows. (By default, KDE puts them all in
a single row, which will waste too much space in the
taskbar.)

Cinnamon
If you run Cinnamon, press Ctrl+Alt+Right to move to
the next desktop. Cinnamon calls them “workspaces,”
but the concept is the same. Press Ctrl+Alt+Up to view
a summary of all desktop contents (Figure 9). This is.
also the right place if you want to add more desktops.

12 101 LINUX HACKS


- 2021 EDITION
Caffeine HACK 8
Helps Your
What Would That
Linux PC Stay
Resolution Look Like?
Awake
There's a command-line tool called
Sometimes you don’t want your computer
to start xrandr that can work magic in configuring your desk-
the screensaver (and possibly lock you out) or acti- top. You may already be aware of its capability of
vate some energy-saving mode and suspend. For changing the resolution via a command similar to
example, | used to get very annoyed when |
brought my notebook to a classroom and stepped xrandr --output OP-1 --mode 2566x1448
away to explain something on the blackboard -
only to find a few minutes later that the beamer no and even defining completely new resolutions using
longer showed my presentation slides. For me, a modeline (which you'll have to create with a tool
that’s a problem of the past, because | use Caffeine. like cvt or an online modeline generator).
There are several tools with that name (including But xrandr can do more ~ if you run classic X11; it
‘ones for macOS and Windows); pick the right one does not work on Wayland. A not so well-known trick
for your desktop! is using a scaling factor to make the desktop bigger
If you work with KDE or Cinnamon, you can install (in pixels) than the maximum resolution offered by
the caffeine package (do not confuse this with Kaf- your monitor. Try the following command:
feine, a KDE media player). Then run caffeine-indica~
tor (if you like it, add it to your auto-start applica- xrandr --output DP-1 --scale 1.5x1.5
tions). This will add a new coffee cup icon to your
panel. Clicking it opens a context menu from which (replace DP-1 with your monitor's ID). If you see no ef-
you can select Activate (or Deactivate). When Caf- fect, use a number closer to 1.0. On my test machine, |
feine is active, you can see steam rising from the cup could not move beyond 1.7x1.7, but even with that
(Figure 10). scaling factor, | saw an incredible 4352x2448 resolu-
Asa Gnome user, visit the Gnome Shell Extensions tion. Of course, the monitor could not display so many
website, search for Caffeine, and enable the exten- pixels, but internally the X server did render an image
sion — this will work best if you have installed the of that size and then created a smaller version for the
chrome-gnome-shell package and the Gnome Shell monitor. I made a screenshot (Figure 11) to check:
integration plugin for Firefox. Using this is even sim-
pler: Just click it to toggle on/off. $ file megares. png
megares.png: PNG image data, 4352 x 2448 [...]
Figure 10
Ifyou enable zooming, you can even work with the high
resolution and still make the window contents visible.

By Hans-Georg EGer
https:/wiki.archlinux.org/index.php/Xrandr
https:/arachnoid.com/modelines/
One last hint: Don’t try an online search for
“Cinnamon+Caffeine” —| did that, and it was com- Figure 11
pletely useless: Google gave me coffee recipes and
health-related articles.

By Hans-Georg EGer
https:/launchpad.net/caffeine
https:/extensions.gnome.org/
https:/www.zhornsoftware.co.uk/caffeine/

101 LINUX HACKS - 2021 EDITION 13


wydf

Get to know Shell, LibreOffice, Linux, and


more from our Special Edition library.

The Linux Magazine team has created a


series of single volumes that give you a
deep-dive into the topics you want.
Available in print or digital format

Check out the full library!


shop.linuxnewmedia.com
RL Beagle
Petar)

E) 3011 BEST BA

E oe
Sein ho wen and och Nore! SUPERCHARGE be
~~ oe eT TT eT Tn aa foe «ee
ets } ‘xpert

ACN ne Aa
COOL

fACKS
Ut Seu nes
Cm ea cg

ee ceotesd
erent
rae
Dis
ula

Discover the
secrets of
the experts
Find a document on your computer, search for a good font
online, organize your project, and track the time you spend
on individual tasks: Nothing in this list is spectacular, but if
it must be done, do it well. We suggest how.

HACK 10
Find Your Files with DocFetcher

Xe Gil
Organize Your Ideas with Zim, the Desktop Wiki
LNG ard
BeToa UROL

PN Gi ky
Tl SS eet a Lp
Le Gre
CC RCh Matec ocean Ty
HACK 15
Cerca MuCa TSC)
HACK 16
Finding and Installing Online Fonts
Ne Gd
1ST Le Oe CeA ela ete) Se rele
rN Git]
Surman CHG

16 101 LINUX HACKS


- 2021 EDITION
GETTING STUFF DONE ~~

Find Your Files with DocFetcher


| like empty partitions: When | install a new Linux distri- just launch the Figure 1
bution on a test machine and log in for the first time, | DocFetcher-GTk3.sh script Document Types
sometimes take a look at the empty Documents folder to start the program. (Ey AbiWord (abe, abe, 2abw)
and think: How beautiful! Let's put two or three files in (On Ubuntu, install the 2 erus cent)
that folder and enjoy the clarity. On my real computers, default-jre package with rac (fae)
things are different. The following code was run on a the apt install command.) ED He tem bem,
notebook that holds only some of my files: DocFetcher can index [2 sPEs tna pea)
MP3 (rnp)
all sorts of files (Figure 1), [2 MS Complies HTMLHelp (chm)
[esser@n2:~]$ for dir in Data Documents; do printf \ including PDF, LibreOf- Ms Excel xs)
"x-95: xSd files in x5d folders," “$dir” \ fice, and Microsoft Office 2 Ms Excel 2007 (nsx, sm)
$(find $dir -type f | wo -1) \ files (both classic and [2 Ms Powerpoint p50)
$(Find $dir -type d | we -1); \ XML-based). It will also Eas Powe 2007 (pe, pen)
(2M Visiowvse)
du -sh $dir | cut -f1; done look at ID3 tags embed- 2 Ms Word (doe)
Data: (96477 files in 18818 folders, 586 ded in MP3 files, so you 2 ms Word 2007 (docx, doc)
Documents: 1499 files in 335 folders, 146 can later search for MP3 COpenofceorg Cal (ods, ot)
songs by title or album 2 openorfice org Draw (oda. 19)
© openfice-org impcess (dp, of)
(If you like what this command does, put it in a shell name even if this meta- pence org writer (dk, ot)
script.) Creating or collecting thousands of files means data does not appear in POF Dacumert (pd
trouble when you need to find one of them. Linux gives the filenames. Normally, Painter
you a few built-in options for searching, so you might DoeFetcher uses the file Ach TextFermat irs)
want to start with them. extensions (like .odt, Scalable Vector Graphics (50)
By cleverly combining shell commands such as .docx, etc.) to decide what
Is -1R (recursive listing) kind of file format it is looking at, but you can enable a
grep (filter search terms) Detect mime type option if you tend to store files with
find (search for files with specific properties) non-standard or without file extensions.
» locate (use a pre-built database to search) Once you've built the index, you can start your
you can already do a lot. locate is especially helpful, be- searches. Results will show up ina table, and when you
cause it gives you instant replies, whereas running find select a particular result, DocFetcher gives you a preview
can take many minutes if you throw it at a large folder (Figure 2). Depending on the file type, itis possible to
hierarchy. It’s likely that you have to install locate first, take a look at all search hits in a document: Imagine a
typically from the mlocate package, and you need to big PDF file that frequently contains your keyword.
regularly run file database updater called updated.
By Hans-Georg EBer
More Comfort, More Features httpi/docfetcher.sourceforge.net/
All the helpers mentioned so far search
for patterns in the filenames - they com- Figure 2
pletely ignore the contents. But in order
to be truly helpful, a tool has to find files
that contain some of the searched key-
words. To do this live would mean ana-
lyzing the whole disk for every search,
and that would take much too long. The
solution is obvious: Build an index, like a
search engine does for web pages.
That's precisely what you get with
DocFetcher. The Java program runs on
all operating systems and needs no clas-
sical installation; you can even put it on
a DVD together with an index that leads
to other files on the DVD. For running
the program, you need not care about
complex java command-line options,

101 LINUX HACKS - 2021 EDITION 17


~ GETTING STUFF DONE

Organize Your Ideas with Zim, the Desktop Wiki


Install and use Zim, a handy tool that enshrines the using File| Save version.
principle of the wiki on your Linux, macOS, or Windows Although Zim is intended for local use and focused on
desktop. The word “wiki” comes from Hawaiian and the single user, the versioning feature does provide an
means “fast.” The term refers to a system in which option for collaboration.
HTML documents on the Internet are both read and ed-
ited using a web browser. The most prominent exam- Use Plugins to Extend Zim
ple of a wiki is the Wikipedia online encyclopedia. You can extend the Zim desktop wiki using around 30
Other wikis inhabit both large and small projects preinstalled plugins. In addition, you will find numer-
within the open source universe. Many wikis are used ous plugins by external developers on GitHub. They in-
for documentation purposes. Debian, Ubuntu, and Arch clude support for formulas, charts, and music notation,
Linux are known for their comprehensive wikis. A wiki’s plus a source code view and a spell checker. Zim can
main task is to organize content in a structured way. “print” to an HTML file and has a table editor, keyword
Many of the popular wiki tools are designed for collabo- management tool, and calculator (Figure 4).
ration over the network, but the wiki concept also pro- You can format text in various ways and supplement
vides benefits for a single user working at a single desk- it with pictures, lists, enumerations, and annexes. In the
top. Zim is a handy desktop wiki that is useful for brain- Tools| Custom tools menu, Zim gives users the oppor-
storming and knowledge gathering, as well as building tunity to create their own extensions. In addition, you
task lists and organizing documents and books. can launch your own web server in the Tools menu and
To operate Zim, you do not need a web server or a thus view your Zim wiki in the browser.
database. The Zim desktop wiki is available for Linux,
macOS, and Windows; it uses the same data format First Launch
across all platforms. As a comparison, WikidPad, a tool When you launch Zim, it asks you where to store the
from the Windows world that also runs on Linux, is data. Zim then creates a first notebook at the defined lo-
conceptually similar, but Zim goes well beyond Wikid- cation, names it Home, and adds the . txt suffix. Home is
Pad's capabilities. You can find Zim packages in most then opened as a notebook whenever you launch Zim.
Linux distributions’ repositories. In theory, you could now just start typing in Zim’s
WYSIWYG editor; however, it makes sense to define
Markup and Versioning
Every page created in Zim is stored on disk as a text file Figure 4
with a wiki markup (Figure 3). The program organizes
these files into notebooks, which can best be compared Inerface | Edtng Plugs Applicavons
with a traditional wiki's database. To create a new page,
first create a link to the initially nonexistent page. You
aaa i
can then add references to other sites to the page’s text. eens ssasties
Zim also supports plugins, including one for version-
ing that stores the editing history for a document in the
ee Toes
form of the Git, Bazaar, or Mercurial version control saatee 5,
Domacien This is a core plugn shipping wah zim
systems (VCSs). You need to install the VCS locally on
the computer. As soon as you enable the plugin via the
settings, you can store a document's current version
Figure 3

Jesserguburi0g:~/Notebooks/Notess. Us =
Lesser ester 155 Jun 3 22:18 Eatt-101
Lesser ester 124 Jun 3 22216 notebook:24h
s0t:~/Notebooks/Notess
Notes edited Edt 101. Hacks/
Jesserqubu2i0d:~/Notebooks 101 -Mackss Us -1
leotat
hcfwer- 1 esser esser 231 Jun 2 22:18 To_do.tKt BH Princto Browser
J-sserdubu2s04:~/Notebooks/Notes/edtt_ 10% NacksS cat To_do.txt
ontent- Type: vext/x-zin-wtkt pale
aoe ees
| check that sturt (Open plugins folder | Getmore plugins enine
JJr+ and
stxttnakeworksnew asscreen
beforeshots
Qcancet | YOK

101 LINUX HACKS


- 2021 EDITION
GETTING STUFF DONE ~~

your wiki's structure first. For each project (say, a book lines using the Tab key. Zim continues these lists until
project, a collection of links, or a to-do list), you will first you insert a blank line.
want to create a separate notebook to provide an easy Ifyou enable the tasklist plugin, you can expand on
means for distinguishing the content. this function. Supplement the bullet by typing, say
A look at the Format menu clarifies the formatting [] Task 1 12-23-2619 |
that you can apply to the currently selected text via the
toolbar or the usual keyboard shortcuts. If you do not to include a due date and a priority (each additional ex-
select a text passage explicitly, Zim formats the word clamation mark decreases the priority), and then di
under the cursor. In addition to the usual markup fea- play all of the project's tasks by pressing the Task List
tures (such as bold, italics, underline, and striketh- button in the toolbar.
rough), you will find five levels of headings. You can Internal links to other pages of the notebook you are
also highlight words or text passages in yellow. currently editing, or to another notebook, mean that Zim
Highlight source code by means of a fixed-width font also has a powerful organizational function. You can ei-
to set it apart from the remaining text. Charts, lists, and ther press Ctrl+L to create a reference to a nonexistent
enumerations complete the picture. If you use the right page (Zim then creates the page automatically) or link to
plugin, you can also embed calculations in Zim and an existing page. The link appears in blue in the text. Al-
represent formulas. The same applies to Gnuplot ternatively, you can create links without dialogs or short-
graphics and images. You can also use an arbitrary cuts using CamelCase or WikiWord notation. For exam-
image editor while working within Zim; launch the ple, entering LinuxMagazine automatically generates a
image editor via an image's context menu and save the link of the same name and the appropriate page due to
results in Zim. The original image is not changed. the uppercase M. Since this feature can lead to un-
The Toggle notebook editable pen icon in the toolbar wanted links, you have the option of switching off Cam-
lets you enable write protection for the entire notebook. elCase linking through the configuration settings.
In the calendar, clicking on the icon labeled Today in the Zim automatically converts paths such as /etc/de-
active notebook generates the structure of a journal faut into links; clicking on one of these links takes you
with sub-items for the year, month, and day that you to the appropriate directory or opens the associated
can use asa diary. file. Local files can be saved as file attachments using
While you are working, Zim continuously stores the Tools | Attach. Zim assigns the attachments to the arti-
current state. Finished documents can then be exported cle and moves them to the new instance if you copy or
as HTML, LaTeX, or Markdown. The tab bar below the move the original. If you copy the wiki to a second com-
toolbar, which grows to accommodate the increasing puter, the attachments remain in place.
numberof projects, shows the state of editing and can- The data is stored in text format with wiki markup,
not be deleted during the session. thus opening up numerous possibilities. For example,
you can use a makefile to generate a website from the
Lists, Links, and Annexes wiki entries. Thanks to the text format with wiki
If you start a line with an asterisk (*) or square brack- markup, you can use the stored information on all three
ets ([]), Zim automatically switches to a mode in ‘supported operating system platforms. The flexible
which it is very easy to create bullet lists or checklists methods for linking let you build rich documents that
(Figure 5). To add a little more structure, indent the you either use as a preliminary stage for processing in
other applications or finalize in Zim.
Figure 5 Zim is easily accessible, revealing the power of its op-
tions only when needed. Once you have discovered the
ey
File Edit View Insert Format Search Tools Go Help
versatility of Zim, you will not want to be without this
desktop wiki, which has been in development since
@<¢ < aaa ao@g 2005. Even Linux beginners who are familiar with Mi-
index « © Lee..e8 Operating Systems | Algorithms [Fede crosoft OneNote are likely to quickly find their way
~ edit 101 Hacks: Todo around Zim.
‘Created Thursday June 03,2021, Zim impresses as a complete package, and if you like
© Lectures
‘Algorithms What to do? the organizational structure of wikis, you are bound to
‘Operating Systems feel right at home.
+ checkthatsturt
+l works as before
+ and make newscreen shots By Ferdinand Thommes
Briest task: dond http:/w.zim-wiki.org
i second task: stil working ont. httpsi/en.wikipedia.org/wikiWikidPad
{Third task: make up a third task
https:/github.com/jaap-karssenberg/zim-wiki/wiki/Plugins
Edit 101 HacksTo do None https:/en.wikipedia.org/wiki/Camel_case

101 LINUX HACKS - 2021 EDITION 19


~ GETTING STUFF DONE

Track Time with Chrono


If you work from home, or work for yourself, a time Chrono is a command-line time tracker that offers a
tracker is an essential tool that can not only help with comprehensive set of features while remaining simple
productivity, but help when it comes to invoicing cli- and quick enough to slot into even the busiest sched-
ents, estimating the timing and velocity of a project, ules. With the tool installed, you start a project by typ-
and tracking your own efficiency. But to be effective, a ing chrono start <project name> followed by a + tag (Fig-
time tracker has to be as efficient and as transparent ure 6). You can now add comments just as you might
as possible. In particular, it needs to be as simple as with a git commit while programming. You can then
possible. Too complicated, and the effort required to review your comments, and when you're ready to.
maintain a log, or context switch between your work move on to something else, simply type chrono stop.
and your time tracker, makes the tracking process it- After this, start working on a new project with the start
self inefficient. This is especially true if you're working command. You can also add to a previously created
on the command line and need to switch to a GUI. project by reusing its project name (typing chrono proj-
This makes Chrono ideal. ects lists all the projects about which Chrono knows).
Figure6 Each new chunk of work is called a
frame, and each has its own unique
Seer identifier, regardless of the project to
fessergubu2i04:~s chrono start Editing +LAI101Ttpps, which it belongs. This is great for in-
starting project Editing [Unii01tipps) at 22:37 voicing, and you can always go back
§ chrono notes add "checked out Chrono fron the github repo”
§ chrono notes add "Added screenshots for chrono’ and add or edit a specific frame if you
Checked out chrono fron the github repo need to add your own notes. The entire
Added screenshots for chrono work output can then be displayed by
‘gubu2104:~$ chrono stop
stopping project Editing [Untioxtipps], started 1 pinute ago (td: seeb7eb) typing chrono 10g.
'sserqubuzi04:~§ chrono log
sday 3 June 2021
(1D: sceb78b) 22:37 to 22:38 0h o1n 285 Editing [Intaextipps] By 3raham Morrison
= checked out chrono fron the github repo
Added screenshots for chrono https:/github.com/gochrono/chrono
(10: attieee) 22:39 to 22:40 0h Oin 20s Lectures [operatingsystens]
Created Final exan POF

Launch Programs In le a VirtualBox VM


If the Guest Additions are installed in a VirtualBox The parameters are always at
guest, you can start programs directly on the guest the end following the two minus signs. In the example,
with VBoxManage. The following command logs into gedit/arg@ indicates that the parameters for the gedit
the virtual machine (VM) named “Fedora 29” as the program follow next. Here, this is just the complete
user tim and a password of 123456: path to the text file that you want gedit to open.
VBoxtlanage guestcontrol “Fedora 29" start --exe 2 The guestcontrol command gives an insight into the
“yusr/bin/gedit" --usernane tim --passuord 123456 2
state of the guest system if required:
uteny "DISPLAY=:6"
VBoxHanage guestcontrol "Windows 18" list all
When it gets there, it launches the gedit text editor. The
--exe option is followed by the full path to the program Among other things, guestcontro! also lists the current
you wish to execute. In the case of a Windows VM, you processes. If a process is hanging, you can kill it with
need to enter the backslashes in the path twice, such as closeprocess:
--exe "C:\\ Windows\\System32\\calc.
exe". Fora graphical
X11 application to launch on a Linux guest, you need to VBoxManage guestcontrol “Fedora 29" closeprocess 2
set the DISPLAY environment variable using the --putenv --session-id 4 2022
parameter. You can also add further parameters to the
program: Via --session-id, you provide the ID of the session in
which the process is running. The number at the end
VBoxManage guestcontro! “Fedora 29" start --exe > represents the troublemaker's process ID.
“/usr/bin/gedit" --username tim --passuord 123456 2
--puteny "DISPLAY=:6" -- gedit/arg@ /hone/tin/brief.txt By Tim Schiirmann

20 101 LINUX HACKS


- 2021 EDITION
One of the biggest compromises you make when you This is an important addition when you
forgo the privacy infringement of online photo stor- consider how prevalent Canon cameras are in
age is convenience. Not only is online storage usu- the open source community, thanks to the fabulous
ally limitless and cheap, it’s typically combined with Magic Lantern firmware. One of the best things about
the same clever Al-generated search metadata that digiKam is that despite the huge size of many RAW files
drives whatever online platform you choose. Google, the import, navigation, and loading of photos is typi-
Apple, and Amazon, for example, all silently trawl cally very fast. Facial recognition can slow this down,
through your uploaded photos to recognize common but fortunately you can turn on an option to scan new
items, colors, locations, situations, and of course, images automatically.
faces. This can really help you find a single image in The application itself is still a powerful tool that’s
a collection that might have started over a decade better suited to organization than editing. It does have
ago, and it's a process that can’t be easily replicated an editor and some excellent color analysis and filters,
ona local machine with local storage and no access but it excels at rating, geolocation, tags, notes, album
to the cloud. Until now. generation, and export. The last of these supports
DigiKam 7 is the latest release of KDE Plasma’s many of the aforementioned online hosting services,
flagship photo manager, a photo manager that also as well as some excellent HTML rendering options for
happens to work brilliantly on other desktops and hosting your own photo collection. This release adds
(keep it quiet!) Windows and macOS. Its best new a beautiful HTMLS Responsive theme to the latter, for
feature is one that finally delivers on a function the ‘stance, which is perfect for dropping onto a server
app has long been experimenting with: deep-learn- and browsing from a smartphone. For editing, you're
ing-powered face recognition. This is thanks to con- still better off using darktable or RawTherapee, but
tributions from Google Summer of Code developers, digikam now seems to concede this point with good
who first demonstrated that neural networks could grace, accepting its place as a brilliant catalog and li-
improve recognition, before integrating the new brary tool and happy to help its users access external
deep neural network features now found in the won- applications and services when needed. Thankfully,
derful OpenCV library. It uses a previously trained facial recognition is no longer one of those external
dataset to discover faces in your photos from just a services you need to use.
single example, without any online communication.
Faces can then be tagged with whatever name you
assign to them. Just like any cloud service, the tags https://www.digikam.org
will even show the
face as a thumbnail,
making it trivially
easy to find photos
with the same person.
If you've not in-
stalled digiKam for a
while, a first-run wiz-
ard steps you through
the database back end
(SQLite) before asking
where your photos are
located and whether
you want metadata in
the database or photos
themselves. Although
digiKam has always
supported a huge
number of image for-
mats, this release adds
support for Canon's
new CR3 RAW files.

101 LINUX HACKS - 2021 EDITION 21


Create a Cheap Timer with sleep Finding and
You call someone on the phone, but they are
Installing
busy, so the two of you agree to call again in 10 Online Fonts
minutes. But then you forget to call, because ee umeur uum err utente
you've been too involved with some other task. Mire Crs ene Arse een Mrmr)
Does that sound familiar? Peco Cunt ere ne
Solve such simple problems with an equally bundling their own fonts designed specifically for
simple solution: Set a timer. Now, you'll certainly CEINEnC Cou CourtmM ala it en iaeg
find sophisticated timer apps for your desktop time with code or words, you'll know that the right
(or smartphone), but how about simply using font doesn’t simply look good; it also helps ease eye
tools that are already installed? Just use the fol- strain and ai saaelm ales Mee selone seule arc)
lowing command to get the pop-up window in Techie hen Rech uml steer Rte
Figure 8 after two minutes: Pou en a eta tml corcunes
KDE has a great font-browsing tool that will let you
sleep 2m; gdialog --nsgbox "$(date +*H:xM) - 2 preview fonts, as well as install them either locally or
it is late - stop work!" PO eNANersit ects mea urs sake WEN Se)
The two minutes are the waiting time that you EVAN AOd Cu hcn eva Tcuiel AUcue
asked sleep to wait. Replace the 2m parameter PORT el Memon) amici mellem) ecole(eM oR aE Te] UL ULol gp
with something else - for example, 3h for three it acts as a kind of application store for the free fonts
hours. Without any suffix, sleep assumes you hosted on Google's font archive. It's also a lovely
mean seconds. GTK3 application, with a sleek minimal interface.
Putting the time in the message window with Ubuntu users can install a Flatpak package:
$(date ...) has a simple purpose: You might not CO ee cae
be in front of your computer when the message SrA Scar ee eam ae
pops up. With this extra information, you'll know ie Ean ee as aE aa}
how much time has elapsed. Gee museca RC ae oat aan cy
On KDE, try kdialog instead of gdialog. If you flatpak run io.github. mmstick.FontFinder
have neither *dialog program on your machine,
there’s always a cheap replacement: Open an Ree Nae a te
xterm window and launch a shell that displays eee te CeCe a Reece R as
your message via PeeM eMC more hn reed Cue
sleep 2m; konsole -e bash -c “echo 2
Pieter Canam tee
$(date *xH:xH) - it is late, stop work ; read"
Pe eM eR ates OUR eOm MT cc
Ea CMa eM eae aaa irom Uncle
The read command at the end waits for you to (One Cen onnecAVacun Ck crore
press Return; the terminal window will then close. Renmei Nxt
By Hans-Georg EBer CMe an eer
Figure 8 tick/fontfinder

eeu iar Ngee tr st ame osc edicig i sel


isn terran bret dk ogee
00
te ts late, stop work! Loremisun nx Mapai ot stonetconsecrtureipicinet,
sed eusmod emporio uboreet oe magn che

{Lorem ipsum Uns Moptin olor it ome, consectetur asing

22 101 LINUX HACKS


- 2021 EDITION
GETTING STUFF DONE ~~

Barrier: One Keyboard/Mouse Combo Is Enough


Many years ago, when computers were big and supported versions with the same functionality. But
heavy and their screens were bigger and heavier, open source packages of the older version are still
you might have had more than one machine. If you available, and Synergy 1.x has been forked into a
did, you really wanted to avoid having more than project called Barrier that continues to be developed
one screen. The best solution for this was a KVM and aims to solve many of the issues that were still af-
switch - not to be confused with the now more fecting the older project. While Barrier does break
commonly used acronym for kernel virtual ma- compatibility with the older version, it does exactly
chines. A KVM switch connected a single keyboard, what the old Synergy did, letting clients be controlled
a single video device, and a single mouse to one or by the keyboard and mouse on a server, and it works
more machines, with a physical or software-con- across operating systems. Other operating systems
trolled switch that was used to flip between control- include Windows and macOS and even unofficially
ling any of the connected machines. It saved space the ancient Amiga, so it's ideal for controlling other
and time. But there was another clever solution that machines from your Linux or OpenBSD box, or even
needed no clunky hardware, and that was a piece of vice versa, and it works perfectly.
software called Synergy. With Synergy, one ma- By Graham Morrison
chine would act as a server, and other machines
would act as its clients. The server was physically https:/github.com/debauchee/barrier
connected to the
keyboard and Figure 10
mouse, and
Synergy would
handle the pro-
tocol that would
send keyboard
and mouse
a # Server Configuration
input to numer-
ous connected Sereersandinks | Wotheye Advanced server stings
clients. The cli- =- Configure the layout
of your bari server configuration.
ent software aL
would reinter-
pret these con-
trols on the local
machine, with
video handled
with something bp tnt box
like VNC or a
separate moni-
tor input.
The Synergy ‘rag new screens othe gid x move existing ones sound
‘raga cick
sreento the trashcan
project became Double on screen to ect itto delete
etn.
Symless, which is
nowa proprietary © cancel
product offering

101 LINUX HACKS - 2021 EDITION 23


~ GETTING STUFF DONE

Self-Organization with GTG


Getting Things Gnome implements the Getting Things intermittent or ongoing attention. GTG is a conve-
Done (GTD) approach, which is so close to this catego- nient, simple tool for tracking tasks and maintaining
y's name that we have to discuss it. GTD is a self-orga- that to-do list. You can quickly record the task, the
nization method developed by David Allen. It is based start date, the desired completion date, and any sub-
on the theory that trying to maintain a complex task list tasks that might be required as part of the process.
in your head takes a toll on concentration. The idea is to GTG also lets you tag tasks for easy searching by cate-
move task tracking out of the mind and put it in the gory and record notes describing the state of the task.
hands of a trusted external system. The system tracks
the tasks, so the user can focus on solving and com- Creating Tasks
pleting the problems. GTG focuses on the tasks, which the program displays
GTD works both with physical objects (such as pen in the main window. You can create a new task by click-
and paper, an inbox that is a real box, and a physical fil- ing on the + button or using the keyboard shortcut
ing system) and with digital objects. Various applica~ Ctrl+N. A new dialog appears. In this example, | want to
tions let you implement the GTD system. One handy save a yoga class offer for a later date. In the first line of
and free program that helps with GTD is Getting Things the new dialog, the title of the task, Yoga Class, appears
Gnome (GTG). While the former website (gtgnome.net) ina larger, underlined font followed by a task descrip-
no longer works, a new team has continued the devel- tion, Penguin Yoga, [email protected].
opment, and they provide a Flatpak archive that you To make it easier to find tasks, you can assign tags,
can install with which consist of an @ sign, followed by the keyword.
flatpak install flathub org. gnome. G76 In our example, you could assign the following tags:
@maybesometime @leisure @yoga. The tags are high-
and then run with Figure 11 lighted with a yellow back-
ground making them immedi-
flatpak run org. gnome. GTS ately stand out in the text (Fig-
Add Parent
if you've setup the Flatpak sys- ure 11).
tem (see Hack #16). Yoga class Finally, you will need to de-
The first step is to collect all Penguin Yoo, pengunyogu@examplecom fine a start and a due date.
the documents that represent emaybesaretime @postoxon elesure iH For the yoga course, you
your various responsibilities: might not have time until Au-
letters, newspaper clippings, ar- gust, and the offer is only
ticles, photographs, and hand- good until October 31. There
written notes, as well as digital are two fields available at the
items such as email messages bottom of the dialog: You can
or notes in a digital notebook. enter the data or select from
You work through the items that require action and com- a calendar. If there is no specific due date, just
plete them according to predefined criteria. The basic choose sometime. When you close the dialog, the
rule is: Anything that you have taken from the inbox new task will appear in the main window.
must not be put back, but must be assigned to a suitable Using Show sidebar from the hamburger menu or
place in the system. the F9 key, you can now open a sidebar in which all the
Select items one by one. The first question for each tags you have assigned are displayed. Right-clicking on
item is: Throw it away, archive it, save it for later, or a keyword opens a dialog, in which you can change the
complete it? You can archive a newspaper article that color the program uses to highlight a keyword for a
you have read but want to keep. The archive can also task. Additionally, you can assign an icon to the key-
include things you might want to do later but don’t word; this icon then appears in the main window next
have time for now. Some of the tasks that you won't ar- to the task title. A search function is available via the
chive or throw away are easier to do immediately, with- magnifying glass button.
out cluttering up the system. As a rule of thumb: Do
things that take less than two minutes immediately; re- Wait
serve the rest for later completion. You can also enter tasks delegated to others in GTG.
After separating out the things you will throw away, Tracking delegation helps you keep an overview of
archive, or do immediately, you get down to some- what you assigned, for when, and to whom, and it
thing resembling a to-do list with items that require can also remind you that completion is overdue.

24 101 LINUX HACKS - 2021 EDITION


GETTING STUFF DONE ~~

Figure 12 merate the tasks in the order in which you


want to complete them.
In the sub-tasks, you can save notes for
BD Yogectas each step, for example, a list of the litera-
teamabout Pins ture you want to read. As usual, you also
Giese have the option of entering tags. After
Feiss LeamnHow to Usethe Quick Ad ty
Reporting Bugs sending a draft of your article to the editor,
you can to add the @wait tag to the corre-
sponding sub-item.
watingtor You need to assign start dates and due
Ey dates for sub-tasks. In this way, you can
keep track of which sub-task is pending; of
course, the due date for a sub-task must be
no later than the due date for the project.
For instance, you could forward a letter from the After you complete a sub-task, right click on it and se-
IRS, reminding you that you need to complete your in- lect Mark as Done from the menu.
come tax return, to your tax consultant. At the same
time, you would use Ctrl+N to create a new task. Give Regular Processing
the task a new title, such as Income Tax Return: Re- To see which tasks are currently pending, you need to
minder from Internal Revenue Service forwarded to work through GTG regularly as part of your daily rou-
tax consultant February 1, 2021. Meaningful tags tine. In the main window, click the Actionable button.
would be: @wait @income tax. Pressing the button changes the view of the main win-
Your tax consultant promised to have your income dow (Figure 12). GTG only displays those tasks that you
tax return ready by April 1, so that sufficient time re- need to complete. They include tasks that either have
mains for you to check the results from the consultant, no start date or whose start date has already been
sign the forms, and file your return with the IRS by reached. If required, you can filter this list for keywords.
April 15. You enter this data as the start date and com- For example, if you are heading into town for shopping,
pletion date of the new task. you can display all items with the keyword @shopping,
so that you are sure to complete all your pending pur-
Projects chases in a single visit. You can then highlight any com-
Tasks that you want to complete yourself, and that take pleted tasks, and they will disappear from the list.
more than two minutes, are referred to as projects in Various plugins add functionality to GTG. To view
GTD. Such projects are typically broken down into indi- and enable them, select Plugins from the hamburger
vidual tasks. menu. A remarkable entry is the Developer Console,
First, create a new task for the overall project in the which lets you call methods in the code while the pro-
usual way by pressing Ctrl+N. If you want to write an gram runs (Figure 13).
article for a professional journal, the title could be By Daniel Tibi
Write article. The following tags seem appropriate: http:/gettingthingsdone.com
@projects @article. The completion date is the edito- https://wiki.gnome.org/Apps/GTG
rial deadline. Enter the individual sub-tasks Figure 13
line by line with a leading dash and blank; for
example:
- 1. Literature research,
- 2. Get literature,
- 3. Read literature,
- 4. Write draft,
- 5. Send draft to editor,
- 6. Incorporate editorial changes, and
- 7. Send finished article to editor.
GTG creates its own sub-entry for each part
of the task and also creates a corresponding
link in the main entry’s window. In the main
window, the entries are shown indented under
the main entry. To keep track, it is useful to enu-

101 LINUX HACKS - 2021 EDITION 25


Linux admins no longer say “Never change a running
system,” but they do say definitely keep it running!
We'll show you hacks that help with everyday system
administration. Repair stuff that’s broken, keep an eye
On it so you notice when it breaks, and be prepared.

*- "7
ey ©) Cm© 2

WwW, “a.
HACK 19
PoC eaten eral)
HACK 20
Write ISOs to USB Sticks
HACK 21
Get a Quick Machine Configuration
eae MANN
HACK 22
Lit Tm Um =e
HACK 23
Cement mas
HACK 24
Se MRR Lele
HACK 25
eR a eae Ne eee
HACK 26
TOR UCR BS lest Ne)
HACK 27
alae trcs
HACK 28
Nomca cts cum cuie
HACK 29
Visualize ddrescue's Progress
HACK 30
Cues MUU IIa tes
LNG ei)
SWRPA CLOT
aU ae ee

26 101 LINUX HACKS


- 2021 EDITION
KEEP ITRUNNING ~~~

Clone It with Clonezilla


Experts agree that you should keep a copy After booting and selecting the
of your data, but restoring from incremental language, Clonezilla prompts you
backups takes time and sometimes doesn’t work as for the operating mode. This is
expected. Alternatively, you can clone the partition. where you say whether you want to
Several tools help with that job; we suggest you use clone a single partition or a complete
Clonezilla even though its text-mode interface looks disk. The software either copies the source to an identi-
outdated. cal target or creates an image of the source disk or par-
Cloning software differs greatly from backup soft- tition. As a further alternative, there are also possibili-
ware. Partition copies cannot be supplemented and ties for cloning on the network. The network option is
accelerated by differential or incremental partial back- intended for large-scale software deployment, while
ups. Admins can thus reconstruct the complete sys- the local option is more suitable for individual cloning
tem in a single pass in case of a crash. Unlike a backup operations or for creating snapshots for data backup.
solution, a clone does not require importing several In just a few steps, Clonezilla guides you to the fin-
backup layers. ished image. It first queries the target for saving. You
The best known example of cloning software is the can choose from a list, whether this is a local medium;
free live system Clonezilla. Developed in Taiwan, it is an SSH, Samba, or NFS server; or whether Clonezilla
based on Debian Sid or alternatively on Ubuntu 21.04 should park the image in the Amazon cloud.
and has no graphical user interface (GUI). You control If you go for the local option, you can specify the tar-
the complete system via ncurses menus. get disk in the next step. For external options, you can
Clonezilla is available in several variants. While the then connect to the source computer. The system auto-
alternative Ubuntu version exclusively serves 64-bit matically detects a plugged-in USB data carrier. Next,
systems, the Debian-based version also offers two choose the source; Clonezilla lists the different parti-
32-bit versions, one of which supports processors tions on the local disk.
with the Physical Address Extension (PAE). The ISO The following ncurses screen allows a filesystem
images each are less than 300MB and fit easily on check to ensure the filesystem’s integrity. Clonezilla
CD-ROMs, allowing the tool to run on very old com- also offers to check an image's recoverability after it
puter systems. The software is available as a hybrid has been created. In the last dialog, the user can also
image, which can therefore be launched from a USB- select encryption according to the AES-256 standard.
based storage medium. The developers stipulate a After a final confirmation prompt, Clonezilla creates
minimum of 196MB RAM for operation. the image. When the software is finished, you can shut
Clonezilla is also suitable for heterogeneous infra- down the system, restart it, or create another image
structures: In addition to the filesystems commonly used (Figure 1).
under Linux, it also supports Windows, Apple's HFS+, Ifyou use Clonezilla, you must make sure that the tar-
and several BSD-derivative filesystems. Also, Clonezilla get partition is at least as big as the source partition
can reinstall the current 2.x ver-
sion of the GRUB bootloader (or Figure 1
the legacy version if required)
and can cope with common
older and newer BIOS versions.
On booting the Clonezilla wClonezitla is free (GPL)
Clonezilia ‘Opensource Clone System (00S)
softuere, and cones with ABSOLUTELY NO HARRANTY«
disc, several startup options 7//int\ From now on, if multiple choices are available, you have to press space key to mark
await the user in the GRUB Your selection. fn asterisk (+) will be shoun uhen the Selection is done///
Two modes are available, you can
boot manager. If there are (1) clone/restore a disk on partition using an image
(2) disk to disk or partition to partition clone/restore.
problems with the screen reso- Besides, Clonezilla lite server and client modes are also available. You can use them for
fassive deploynent
lution, Clonezilla also offers a
generic VGA driver along with
legacy SVGA and XGA resolu- Gevice-device
Penote-source
work directly from a disk or partition to a disk or partition
Enter source mode of remote device cloning
tions. It is also possible to load Penote-dest Enter destination mode of renote device cloning
lite-senver Enter_Clonezilla_live lite server
the entire system into the com- lite-client ite-client
puter’s RAM, which noticeably
accelerates work on older sys- «ok <Cancel>
tems in particular.

101 LINUX HACKS - 2021 EDITION 27


KEEP IT RUNNING

when functions and the corresponding dialogs are included


cloninga in the previous routine’s ncurses menus, so you don’t
disk. In addi- need any additional training.
tion, the source If you want to restore an image, just reverse the
drive must be un- steps. After starting the live system, again set the lo-
mounted while the cale. In Clonezilla, define the source medium where the
cloning process is run- images you want to transfer are located. In the next
ning or creating an image. step, select the image repository in which the desired
Cloning does not work with the image is stored. In the last dialog, Clonezilla uses the
drive mounted. restoredisk option to transfer the clone or image to the
Since version 2.5.2-31, the devel- target disk.
opers have also integrated a Clonezilla
Lite server into the live system. The server By Erik Barwaldt
is used to enable the rapid deployment of op- http://w.clonezilla.org/downloads.php
erating systems in a network environment; it can
clone 40 plus computers simultaneously. The server

Write ISOs to USB Sticks HACK 20


Many of us still resort to the humble dd command when you whether your ISO is hybrid and capable of being
writing a distro image to USB storage, because it's sim- written to USB storage and whether enough USB stor-
ple and untainted by options or system interaction. But it age has been found. On Ubuntu, first run
does have some profound problems. Worst of all is that if apt install curl jq syslinux wimtools
you geta single character wrong when declaring the de-
vice node, such as /dev/sda, dé will start overwriting your and then download the source archive and run sudo
internal storage without even asking politely whether ake instal] in the extracted folder.
you're certain, and you'll soon be diving for Ctrl+C. In the background, boot iso is also running lots of integ-
A great alternative is bootiso, which doesn’t present rity checks on the ISO, making sure it will boot and has
the same risk, adds loads of new features, and still runs the correct MIME type, as well as that the potential desti-
from the command line. At its simplest, you can run it nation is correct and not a single partition. This is useful
against an ISO file with the -p argument, and it will tell in itself, and it will even let you know which device node
Figure 2 your storage is hanging off in case
you still want to risk dd. But bootiso is
even better when you want to write
the image, and that's because it still
[esserexpsi3:Downloads]$ boottso ubuntu-21.04-desktop-amd64.(so
lbootiso: Found hybrid image; choosing Image-Copy mode uses dd. Give it your ISO as the single
lbootiso: Partttton label automatically set to ‘UBUNTU 21.0 = You can argument, for example, and it will join
explicitly set the label with -L, --Label. up its detection routine with its encap-
lbootiso: Listing USB devices avatlable tn your system:
NAME MODEL VENDOR SIZE TRAN HOTPLUG sulation of dd to write the image auto-
sdc Cruzer Blade SanDisk 28,76 usb 1 matically, carefully asking whether
sdd Ultra Fit SanDisk 14,36 usb 1
Select the device corresponding to the USB device you want to you're certain, after presenting the de-
make bootable: sdc,sdd tails on what's going to happen (Fig-
Type CTRL+D to quit.
Select device td> sdd ure 2). While there's no progress indi-
lbootiso: The selected device '/dev/sdd is connected through USB. cator — just like dd— by choosing the
lboot iso: About to wipe the content of device '/dev/sdd’ optimal block size in the background,
‘Are you sure you want to proceed? (y/n)> y the transfer is often quicker than try-
lbootiso: Erasing contents of '/dev/sdd’...
lboot iso: Copying files from image to USB device with ‘dd’ ing your luck with dd.
lboot iso: Synchronizing writes on device '/dev/sdd"
lboottso: Took 248 seconds to perform tnstalt-auto act ton By Graham Morrison
lbootiso: USB device succesfully ejected. You can safely remove it!
[esser@xps13:Downloads]$ I https:/github.com/jsamr/bootiso

28 101 LINUX HACKS


- 2021 EDITION
KEEP IT RUNNING ~~~

Get a Quick Machine Configuration Overview with in:


Every admin knows how to retrieve information aboutthe default value) processes are
system on which they are working. How many cores does _currently hogging the most
the CPU have? cat /proc/cpuinfo! Is eth3 a gigabit inter- RAM, inxi -t m will help me
face? ip | sh! Butinstead of many tools, you can just use _find out. If | want to see the top 10
one: inti. Itis available via many package repositories processes, | enter -t mi@. If | hear the CPU fan hum-
(e.g., openSUSE, Debian, Ubuntu, and Linux Mint). ming, on the other hand, | just need to replace the m
Suppose I need an overview of a machine with which _with a to view the processor load. You can also com-
Idon’t normally work. Then, Icall inxi without any pa-__ bine the two: inxi -t cml@ returns the top 10 RAM and
rameters and get some basic information about the CPU hogs.
hardware (CPU, clock speed, RAM, and disk size) and At the end of this informative newscast on the com-
the system (kernel and shell processes). If wantto see —_ puter, I'll take a quick look at the weather:
a few details, the -F parameter provides information on inxi -w -H "Berlin, Germany”
the video and audio hardware, partitioning, Swap, tem-
peratures, and fan speeds (Figure 3). tells me what the situation looks like outside the server
If 'm only interested in a particular component, |can room.
target this with specific parameters, such as -C, -A, and
-G, which stand for information on the CPU, audio, and By Charly Kiihnast
graphics, respectively. Information on the RAM is re- https://github.com/smxi/inxi
turned after a (lower-
case!) -m, which takes Figure 3
some getting used to. [m* ro va]
fie an_ on tenets
op Hy
Memory Details esserenpsi2:
systen:
Running with root
2F

Inachine: Type: Loptop Syst OFSPSY vE ADO sertel: «superuser requlred> UEFI" Dell v! 1
privileges, inxi tells leattery:TD-1: 8470 charge: 43.5 wh condition: 43.5/32.0 Wh (87s) model: SH DELL caVC 2 oyar/20an
Fall
me more about the ru: 5500 bhts: 68 type: MT ‘heck Fev: A
loge: avx avx2 win/eax:
ln nx pao400/4000
sse ss02Wz stedCoresio4_1
RAM: Apparently Speed: 800 fiz speedsssot_2 (Wiz): sss031: 800vex 2:bogomtps:
800 3: 80031999
4: 600 $: 800 6: 900 7: 800 8: 800
four 2GB DDR mod- leraphtes: 'ernet bus 1D:_00:0210
Realtek Tntegrated.webcas
org 1.20.4 NO ‘loaded: type: USB driver: wvevideounloaded:
bys TD: fbdev,vesa
1-5:3 resolution: 2360x1490~soKe
ules are plugged into ocesetting
eso Tate UMD NO Grapher 620 (ROLDeltC'2) driver:v: 4.6 Nosssnd-hda_tntel
21-0.1 dtroct render: Yes
my test machine and pwd: Tntet Sunrise Potnt-LP Auto vendor:
edie Audto Adapter (UaCtek Y-247A) type: USB driver! Nidagenere
clocked at 1600MHz — 11.3350
Sound Server! ALSA v:_K3.11.0-17-generic
yes, this is a fairly Inetwork: Device-i:
vendor’ Rivet Qualcona
NetworksAtherosKULLerQCAGL74 B02.11ac wireless
1435 Wirelass-AC driver? Network
athiOk Adapter
pet v: kernel port: £040 bus 1D: 02:00.0
ancient beast (see
Realtek RTLSIS3 Glgab(t Ethernet Adapter type: USO drtver: 8152 bus 1D:
Figure 4). The -c4 0ec2de80 state: up speed: 1000 Mops duplen: full mac: 00:e0:4e:c2:de:50
parameter shown in Bluetooth: Repor 8 bus 10:9¢"06:00:00:80:06
1-7:4
Figures 3 and 4is ‘apev! 42 address!
Drives: LocalDek: Storage:
/dev/eveednhtotal:vendor?
476-94SK C18Hyeused: 265 GLB (55.64)
responsible for the sodel: PCIOL Nite S126D stze: 476.94 GIS teap: 39.9
Partitton: boot eft size: 748 MIB used: Cte
stze: 221.5 GU8 used: 53. 77.3 Cis.) fs:
color scheme. The MiB (10.4%)
swap:
Sensors: Alert:
Systen No.Teaperatures:
Swap data wascpu! found
default color scheme 12.0 C mobo: W/A
Fan Speeds (RH): W/A
is not easily legible ant Processes: 317 Uptlne: 224 15h 09 Memory: 15.33 GIB used: 9.57 GLB (62.4%) Intt: systend runlevel: 5 Compilers:
‘gee: 10.3.0 Packages: 3364 Shell; Gash vi 5.1.4 txt: 3.3.01,
on terminals with a st
light background, but
thanks to the pleth-
ora of options from Figure 4
~cl to -c32, selectable
sets are available to
suit your taste. me.
Ican even talk inxi Sood 800 2 ‘800'3. 800 5: 800 5: 800 6: 800 7: 800 8: 800
Kess erex
lfenory psi3R:n}s sudo tnxt
ls total 15.39 61B sed: 9.6 GUD (62.64)
into a spot of simple ty: 18 6B 0 2 ec
process monitoring. ed 2233 Ws
Devies.2: 9 23 mI
If want to know Kessereapsi3:~18 1
which five (this is the

101 LINUX HACKS


- 2021 EDITION 29
KEEP IT RUNNING

Repair Your Bootloader various options in tab groups and grays any
inaccessible tabs. In the first tab Main options, you can
Sometimes things go wrong when you are installing an op- only configure a few basic settings for GRUB 2; you will
erating system on a hard disk drive or SSD. A boot repair see that the tool has already activated the option for rein-
disk gets your boot configuration back on its feet, quickly. stalling the bootloader. In addition, you can trigger an au-
The boot process for computers has become massively tomated filesystem repair; Boot Repair gives you the op-
more complicated in recent years. Unified Extensible tion of reanimating a damaged MBR if necessary.
Firmware Interface (UEF!) has largely replaced the tradi- As an important additional option, the dialog offers the
tional BIOS, while increasingly large storage devices re- possibility to make a backup of the partition table, boot sector,
quire new types of partitioning. Figure 5 and all logfiles so that you can re-
The configuration options of construct the old data later in case of
bootloaders such as GRUB 2 have problems, If you enable the Restore
thus been massively extended; MBR option, Boot Repair grays the
even minor changes to the system following tabs GRUB location and
can cause startup problems. In the GRUB options and instead enables
worst case, you will be left sitting the MBR options tab. In the second
in front of a black screen with a tab from the left, labeled GRUB loca-
flashing cursor without the operat- tion, you can define where GRUB 2
ing system having booted. is installed. You can either select all
In this situation, Boot Repair Disk mass storage media or a specific
provides invaluable assistance: disk, which you choose in a selec-
The operating system, based on tion box. You can also specify
the lean Lubuntu 18.04 with the eo} which operating system the boot-
LXDE desktop, takes care of dam- loader should load as the default.
aged boot configurations even in heterogeneous environ- In the following tab, GRUB options, you can choose to
ments, repairing them automatically at the push of a button. completely delete an existing GRUB 2 installation before set-
ting up GRUB again, or enable GRUB Legacy as the default
Ready, Steady, Boot boot manager. You can also configure various parameters
Boot Repair Disk is available as an ISO image of approxi- that GRUB 2 needs to correctly start specific operating sys-
mately 922MB for 64-bit architectures, or as 756MB for the tems. If the configurations offered here do not meet your
32-bit variant. Thus, both versions of the operating sys- needs, you can press Edit GRUB configuration file to tune
tem require a DVD when you want to burn them to optical the configuration file manually to your liking.
media. Grab an older release with less than 650MB, if you In the Other options tab, you can define various options
have legacy hardware without a DVD drive. Alternatively, for logging the individual tasks. If you also have a Win-
you can use UNetbootin to transfer the image to a USB dows version on your computer, you can enable the Re-
stick for use on computers without an optical drive. In our pair Windows boot files option to repair a Microsoft sys-
lab, we were unable to write a bootable image to a stick tem that fails to launch. Then enable the respective op-
with the on-board tools. tions by clicking on the Apply button. If you want to repair
After setting up the image, boot the computer from the amass storage device's MBR, enable the Restore MBR op-
corresponding media, and choose the bottom entry in the tion in the Main options tab. Boot Repair then grays the
boot manager Boot Repair Disk session. Within a short settings dialogs for GRUB and instead enables the MBR
time, the system starts and immediately launches the options tab. You can then select which tool to use to re-
Boot Repair software on a very plain LXDE desktop before construct the MBR. If there are multiple partitions on the
proceeding with a system scan. Then the program's con- mass storage device, you can also define here which of
trol dialog appears. them to boot by default.
Under normal circumstances, you will just want to press
the large button labeled Recommended repairto initiate an Bootinfo
automatic reconstruction of damaged system components The Boot Repair Disk also comes with another program
such as the Master Boot Record (MBR) and boot manager. If dubbed Bootinfo, which helps you with problems at system
you first need accurate data on the mass storage media, but startup time. It can be found in the System Tools menu of
do not want to make any modifications for the time being, the operating system and provides a clear-cut window
then click instead on Create a Bootinfo summary. In addi- where you can define with a single mouse click whether the
tion, the window also offers advanced configuration options, tool should store the boot log online or locally.
which you can access by clicking on Advanced options. After another click on Local report (text file), the tool
The window then expands to include a configuration scans the computer and then opens the Leafpad text edi-
dialog for the GRUB bootloader (Figure 5), which groups tor, which opens up with the scan log. You will not only

30 101 LINUX HACKS


- 2021 EDITION
KEEP IT RUNNING ~~~

find detailed information on the Figure 6 Desktop


system configuration here, but Pic tet teach Optom We Besides the tools for repairing the sys-
~at the end of the log ~ also tem, you will only find a few prein-
some hints on how the repair stalled applications. Office applica-
tool will approach the task. You Buot 60585262 30273600 eis rar cna) tions, games, multimedia, and educa-
can thus determine what modi- tional applications are missing com-
fications the tool will make on pletely. The Accessories menu con-
the computer (Figure 6). tains entries for the LX terminal, the
The tool lists all the partition nz fod
wetean Blocks
"Spokane" 14. 63SystonUlnun Leafpad text editor, and the PCManFM.
data of all mass media (includ- file manager.
ing USB flash drives) connected ty would relnstatt the geek You can launch Firefox from the In-
to the computer system, as well ‘ternet menu, and the usual LXDE
as the GRUB configuration files. configuration dialogs are found
In addition to the repair pro- below the Preferences menu. As a
gram’s log, you will also find the special feature, the System Tools
complete output from the parted menu offers the Synaptic package
~1,parted -1m, mount, df -Th, and manager, which provides access to
fdisk -] commands in the text file. You are thus given a the Lubuntu repositories, if you need additional software.
good overview of the mass storage device configuration.
Hands-On
OS Uninstaller In our practical tests, the system was totally convincing. It
The third in-house developed tool included with Boot Re- not only successfully restored damaged boot sectors in
pair Disk is found in the System Tools menu: OS Unin- Linux-only installations, but also repaired a mixed system
staller. This helps you delete an operating system without with one Windows and two Linux partitions.
leaving any remains on your mass storage device and Also the OS Uninstaller enormously simplifies adminis-
without painstaking manual work. trative tasks: In our lab, it always reliably completed the
After launching, the desired tasks on multiple machines with a variety of
Figure 7 application first lists all shared storage devices, thus removing the need for time-
€ O5-Uninstaller +x the existing operating consuming manual deletion and modification of the parti-
Which operating system do youwant to uninstall? systems after a brief tion table, as well as the GRUB configuration files.
Linux mint 18 a¢ah (sd31) scan of the system (Fig- Boot Repair Disk is a very useful tool that every admin-
Ubuntu 16.045 (sda6)
ure 7). Select the operat- istrator in a heterogeneous environment should include in
ing system that you want their toolbox. Even less experienced users will be able to
to delete from this list quickly control the intuitive tools without any problems.
Xcaneel | [YOK and press OK. Aftera The system itself is extremely stable, and the special tools
safety prompt, the unin- for revitalizing the MBR and the GRUB 2 boot manager
staller first deletes the operating system, then reconfig- were impressive. Also the deletion tool for unneeded op-
ures the boot manager, and finally displays the results. erating system installations saves a huge amount of man-
After a reboot, you will find the remaining operating sys- ual configuration work.
tems in the GRUB startup menu, where the OS Uninstaller By Erik Barwaldt
adds entries for the Plop Boot Manager and Smart Boot https:/sourceforge.net/projects/boot-repair-cd/files/
Manager. They do not have a function without additional https:/unetbootin.github.io/
configuration, so you can safely remove them from the
Start menu. Figure 8
i
More Tools Cm Ocoee erm
In the event that hardware problems cause difficulties
when booting a computer, Boot Repair Disk comes with
two graphical diagnostic tools in the form of Hardinfo and
GParted. Hardinfo, which you will find under the System
Tools menu labeled System Profiler and Benchmark,
clearly visualizes the hardware in a two-pane window and
also performs benchmarks. GParted, on the other hand,
helps to manage the storage devices. This is where you
can, for example, identify problems arising from incorrect
formatting or damaged filesystems (Figure 8).

101 LINUX HACKS - 2021 EDITION


Caution is advisable before HACK 23
Cleaning House with Stacer deleting Application Caches: This could slow down appli-
Classic command-line utilities are considered the go-to cation launch, and you should proceed with caution when
tools for system administration, Figure 9 it comes to the logs and keep at
but some powerful graphical least the current X.Org log and
tools also are available for mon- the apt and dpkg logfiles. Num-
itoring and optimizing a Linux bered logs are always older and
system. One of those tools is can typically be disposed of
Stacer, which lives on GitHub. without any worries.
SourceForge also offers sources
for compiling, as well as deb Apps and Services
packages for 32- and 64-bit After clicking on Startup Apps,
systems and an Applmage for you can view the applications
64-bit machines. In this hack, I'll the system launches when you
discuss the Ubuntu package login and set up new startup
and the Appimage version. apps. This is especially handy
Stacer was designed for if you work with different dis-
Ubuntu (it's in the default repos; tributions: You do not always
simply run apt install stacer) but works with any distribu- need to think about where you need to set up applica-
tion. Before the first start, you need to make the Applmage. tions that start automatically on the respective systems,
executable, which you can do as a user working in the direc- and you can also tell Stacer to lock an application for
tory where the package is located; then, run Stacer from the the next login session as a test, without having to
same directory: plumb the depths of the Control Panel.
$ chmod a+x Stacer-x8¢_64. AppImage
Starting and stopping system services is intended to be
$ . /Stacer-x86_64. AppInage just as easy via Services. A filter function facilitates find-
ing a particular service. This feature did not work on
(Depending on what download link you follow the file Ubuntu 21.04, while it was just fine on openSUSE 15.3.
could be named Stacer-x64. AppInage.) A message tells you The Uninstaller function was broken on Ubuntu 21.04
that the setup routine is adding the application to the (where at least a list of installed packages was shown, but
menu and putting an icon on the desktop, which is the removing them did not work) and openSUSE 15.3 (where
only way in which the application changes your computer. no packages were found)
Alternatively, you can launch Stacer, like all Appimage ap-
plications, by double-clicking on the executable file. Colorful Plots
Stacer welcomes you with a modern window that lets The Resources dialog displays the last 30 seconds of CPU,
you access various features via icons on the left side. RAM, and network activity (Figure 10). If you have four,
From top to bottom, these are Dashboard, Startup Apps, eight, or more cores, Stacer shows them individually in con-
System Cleaner, Search, Services, Processes, Uninstaller, trasting colors. To view each plot separately, press the His-
Resources, Helpers (an editorfor /etc/hosts entries), APT tory of CPU button, for example.
Repository Manager (on Debian-based machines), Gnome All tasks handled by Stacer can be run at the command
Settings, and Settings (see Figure 9) line, with standard graphical tools, or even with the use of
The program starts with the Dashboard (you can change competitor products such as BleachBit, but not with the
that in the Settings), which only provides information and same graphical appeal. Delivery as an Appimage lets you
does not allow any interaction. It gives you an animated distribute Stacer to multiple distributions in a single pack-
view of CPU, memory, disk space, and network interface age; additionally, you save yourself the installation over-
utilization, as well as information about the installed pro- head. However, the AppImage weighs in at more than
cessor and operating system. 30MB, and the executable file is around 75MB after un-
Figure 10 packing. Keep in mind when
System Cleaner using Stacer that you could shoot
The System Cleaner helps you yourself in the foot with poorly
ditch the ballast: This is where considered actions. Also, the
you can remove unnecessary overall usefulness varies with the
log or cache files and empty ey Linux distribution you use.
the trash can on your system. o
In the initial state, Stacer does By Ferdinand Thommes
Cc
not provide any data for trash F] https:/github.com/oguzhaninan
disposal; you first need to en- Fa Stacer
able the desired categories and e
then launch a system scan. G https://appimage.github.io/Stacer/
a
32 101 LINUX HACKS
- 2021 EDITION
KEEP IT RUNNING ~~~

2
SS
Search and Find with the fd/find Tools
I'm not very good at sorting things sensibly and then This is because fd is not case-sensitive by default. How-
finding them again — both in my office and on my ever, if an uppercase letter is stipulated as the search
computers’ filesystems. For the latter, at least | have term, it switches its behavior and only returns case-
electronic help in the form of tools like find and, more specific results.
recently, fd. You can search for file extensions with the -e param-
The find command existed on Unix systems long eter. For example, to find all PNG images in and below
before Linux was invented — in fact, it's older than the current directory, just type:
most of the people who use it. On many of my sys-
tems, there is a directory named /test where | try fd -e png
things out. Anything that proves useful is sent to Git;
the rest just hangs around gathering dust until the luse regular expressions for fine tuning. By way of an
cron job in Listing 1 sweeps it away without write ac- example, the command
cess after 365 days.
fd ‘*a.*pngs*
finds file names that start with a and end with png. The
Find /test/* -mtine +365 -exec rm {} \; GitHub page for the tool explains many more applica-
tions and parameters.
Now all | really need is a physical fd counterpart to
While doffing a hat to the now impressive power of tidy up my office ...
the GNU implementation of find, you still sometimes
find yourself wishing for a tool that can perhaps do a By Charly Kihnast
little less, but one that is more intuitive to use. This is https:/www.gnu.org/software/findutils/manual/htm|_mono/
where fd jumps into the breach. The compact younger find.htmnl
sibling of find, fd has already made its way into many https:/github.com/sharkdp/fd
distributions, but often only recently. In Ubuntu, itis
available starting with version 19.04, for example.
After installing fd on my test Ubuntu, | now have an Figure 11
fdfind command. But the developers make it quite
clear that their tool is named fd and use this name in
all the examples. In order to permanently teach my
system the short form, | just added an alias fd=find
entry to my .bashre.
Quickly perusing the man page reveals that fd can
definitely do less than find, but it does what it does
well, intuitively, and quickly. Typing fd without any
further parameters returns the current directory’s
contents including all its subfolders, but without the
hidden files and directories — like Is, but recursively.
If the environment variable LS_COLOR is set (which is
the default on most systems), the output will be in
color.
Things become more interesting if you are searching
for a file name or name component. In Figure 11, | told
fd to search the root directory \ for rng. As you can see,
it also found PatternGranmar. txt (at the very bottom).

101 LINUX HACKS - 2021 EDITION 33


KEEP IT RUNNING

Repair the Debian Package Database


Sometimes the package database on a Debian-based which builds packages that contain only dependency
Linux installation becomes inconsistent, and you can information.
no longer install or remove packages. There are ways In all these tools, you should gather whatever infor-
to fix the situation with apt, aptitude, and dpkg. mation you can about the state of the packages in-
Maybe you installed the wrong package from the volved. However, actually fixing the problem is likely to
Testing or Unstable repositories or gambled on Ex- take you far beyond the usual internal commands like
perimental. Maybe you installed a flawed third-party instal! and renove.
package or mixed packages from different Debian de-
rivatives. Or maybe the maintainer made a mistake, Making Repairs with apt
or a major technology change has happened, and When apt announces that you have broken dependen-
you are not to blame at all. But in all of these cases, cies and suggests solutions, very occasionally, remov-
you either receive an error message (Figure 12) or a ing problem packages with
ranked list of possible solutions, and suddenly you
are unable to install, remove, or update anything apt remove PACKAGES
until the problem completes its efforts and returns
you to a waiting command prompt. can solve the problem. On the principle of starting with
If you are patient, a new version of the problem pack- the simplest solution, try this command, but don’t be
age will be released that fixes the problem. The only surprised if it does not succeed.
trouble is, the new version might not be released for Another relative long shot is editing package sources
weeks, depending on where Debian, or your Debian de- to get newer versions of the problem package(s), using
rivative (like Linux Mint or Ubuntu), happens to be in its apt update to make them available. In particular, search
development cycle. Even after filing a bug, it can some- fora mirror site with more recent packages than your
times take time to resolve the problem. Probably, then, usual ones to add to the file /etc/apt/sources. list.
you want to take more active steps. Amore promising approach is running
Fortunately, the tools you need are ones with which
you are likely already familiar: apt, the package manag- apt dist-upgrade --no-upgrade
er’s front end; aptitude, the popular command-line in-
terface; and dpkg, the basic package tool. Alll three have to upgrade all the packages installed on the system. Do
the structure not use apt upgrade, since the last thing you want to do
is complicate the problem by adding more packages to.
COMMAND SUBCOMMAND PACKAGES the mix.
Another possibility is to force completion of an install
as well as many of the same features for installing and with:
removing packages.
apt and dpkg are installed by default on any Debian or apt dist-upgrade -f
Debian derivative system. However, if you have risky
habits, like constantly taking the latest package ver- Sometimes, specifying some or all of the packages
sions from Unstable, you should make sure that apti- mentioned in apt messages will work instead:
tude is installed, as well as other useful tools such as
script, which can log your recovery efforts, or equivs, apt install -f PACKAGES

Figure 12 Alternatively, try


apt remove -f PACKAGES

but read the summary of


what will happen carefully
before continuing the com-
mand. For some obscure
reason, all these commands
may work the second, third,
or even the fourth time you

101 LINUX HACKS


- 2021 EDITION
KEEP IT RUNNING ~~~

runthem, sorunthem Figure 13


several times before giv- aptitude — Konsole
ing up on them. You can Bookmarks settings Help
also try specifying the re- Poca) oon Resolver aera
pository and full package c-T: Menu 7: Help q: Quit Pet cma C ae eGo wi Ce
name by adding the -t eee eMC) eae
Upgradable Packages (91
option to any of these
commands.
However, if you try all
these solutions and have wr
no luck, you have ex- ores
hausted the capabilities
of apt and need to try an-
other command. bash @ | -: aptitude @
Aptitude Dancing
When run without options, aptitude opens an ncurses in- background information that can help you develop a so-
terface to the Debian package manager (Figure 13). How- lution. The --yet-to-unpack option can be especially use-
ever, what many users do not know is that aptitude con- ful when you have been looking for solutions for some
tains many of the same tools as apt, apt-get, and dpkg for time and don’t care to scroll back in your history for the
fixing broken packages, as well as several extra of its own. names of the problem packages.
For example, you may be able to resolve problems by An especially powerful dpkg option is --purge (-P).
using the markauto command to mark packages as being --purge is a more powerful version of renove, deleting
automatically installed, or unnarkauto to mark them as not only the package, but all records of it, including the
manual installations. Another useful command is ~t RE- configuration files. In addition to removing the pack-
LEASE, which specifies which release version to use, or its age, ~-purge also runs its postr (post-removal script).
counterpart forbid-version to specify a version not to use. While you are troubleshooting, this thorough deletion
Another useful pair of tools is uhy and uhy-not. Both are can simplify the problem's background and sometimes
followed by a dependency. The why command shows why even solve the problem itself. The dpkg man page will
a dependency would be required, whereas uhy-not shows give you more information.
why a dependency produces a conflict. The results of Another important option is:
both can indicate how a subset of broken packages in-
volving conflicts with another package can be resolved. dpkg install -~ignore-depends=PACKAGE
However, the most popular feature of aptitude is the
Resolver menu. The menu lists the package manager's Pees accuse
suggested solutions to dependency problems (see the
“Descent into Dependency Hell” box) and allows you Manually finding a solution when the package system no
to approve and reject them. Often, this menu alone longer works can be hard. Resolving broken dependen-
solves problems that apt-get, dpkg, or other features of cies can take hours, and the complications are so numer-
aptitude cannot, although at the cost of hiding exactly ‘ous that, when you do find a solution, it can feel like luck.
what it is doing. The real solution, though, is to work systematically
through the possibilities.

Escalating to dpkg Ifyou regularly find yourself in dependency hell - as bro-


Because dpkg is a lower-level package than apt, it in-
ken dependencies were once called -then maybe you
should consider your computing habits. While everyone
cludes many features that apt and aptitude do not. As its is tempted by the latest possible release and can make
man page shows, dpkg is especially useful for reading de- mistakes out of enthusiasm, by stepping outside the
tailed information about packages, including the state it safety of the package management system, you are strik-
is in, and for filtering
the information displayed. You ing out on your own.
might be able to run dpkg with the option --forget- An expert can do that, but to do so requires caution
o1d-unavai lable, ~~clear-selections to remove problems, every step of the way. Otherwise, you may be reduced to
or --audit (-C) to receive advice on what actions to try.
desperate efforts such as editing a package's scripts or
fiddling with /etc/apt /preferences in the faint hope of
However, more often, dpkg options or commands, such changing results that have already failed.
as dpkg-query, will be most useful in filtering or gathering

101 LINUX HACKS - 2021 EDITION 35


— KEEP IT RUNNING

This option is misnamed, since it does check for depen- well as the man pages, before using it.
dencies but only reports conflicts between packages. In fact, dpkg as a whole can be so deadly that you
Often, it can be the solution for which you are looking. should use
An equally powerful solution i
=-no-act [--dry-run, --simulate]
dpkg --configure -a
to do a dry run of any action, simply on the off-
which configures all partially installed packages. In my chance of unexpected effects. The simulation will not
experience, this command fixes more broken depen- tell you in so many words that your system or desk-
dencies than any other option mentioned in this article, top environment will crash, but studying the list of
although itis not infallible. affected files should warn you that you risk making
If not, then take a detailed look at --force-things your situation worse.
THING, as well as --no-force-things and --refuse-things. The Debian package manager has other front ends,
Just as --purge is an enhanced version of renove, so notably Synaptic, a desktop interface. However, if apt,
--force-things is a fine-tuned version of the apt-get dpkg, or aptitude cannot restore full functionality, then
--force option. You probably want to avoid completions the chances are high that neither Synaptic nor anything
of these commands such as bad-version, renove, or over else can do so.
urite unless you are absolutely confident of what you By Bruce Byfield
are doing. However other completions, such as doun- https:/wiki.debian.org/Synaptic
grade, conf igure-any, and remove-reinstreq may provide https:/en.wikipedia.org/wik/Dependency_hell
solutions. But --force-things can bring your system
down when used carelessly, so consult --force-help, as.

Learn the vi Editor Basics


Half of the Linux administrator's life is entering com- that it teaches you something
mands in the shell. The other half is editing files in the conceptually new.
vi editor (or its improved version, Vim - which stands So have a look at vi if you've never done so
for vi improved). Rumor has it that there are alterna- before. Search the web for “learning” and “vi,” and
tives to vi, names like Emacs, MCEdit, Gedit, Kate, and you'll find lots of introductory texts and videos. Or run
nano come to mind. the vintutor command. Start with the GUI version gVim
Don't worry, this hack won't take part in the famous (Figure 14) if you prefer to see a menubar.
“Editor War.” If your preferred editor is not vi, then let By Hans-Georg EBer
me only suggest that you learn the basics of this an- https://www.vim.org/
cient tool that - according to its Wikipedia page - has https://en.wikipedia.org/wiki/Editor_war
been around since 1976. Why should you do that? Here https:/en.wikipedia.orghviki/Vi
are my favorite reasons.
* viis not only available for every operating system, it
is also preinstalled on every Unix-like system. So if Figure 14
‘ai raevevala)- vie
you happen to find an ancient Unix workstation run- Fe ae Tash Spee ters Wed Hep
ning SunOS, HP-UX, or AIX, you'll be able to edit its eae oe po *>¢ @@r ona
configuration files. te (mutex tey Lock (paging Loch): _ / active waiting for Tock
Hor (ane as = 17spacs{as]
as. WiR status
ADDR SPACES:
* vis a text-mode program, so it doesn’t require an X ‘ie (asdess = AS USED)ste){
session. It also does not require a mouse or a full key- eige ectory vrs aes esis: onlyentrywerk inon vseprocess nnary
board with cursor keys. So even in the unlikely event ‘f (pd->ptdsii} present) { iy darectory
(page tables) (mi SteAL ((pdmptasIt) fran adr) << 229);
that you're remotely logged in to a strange Unix ma- 11 abe entry in ose
chine and the keyboard settings are broken, you can Sh (ascounter
220)tablelinged)
| pageno, Posea)MAX COMTERS):
{
still use vi.
* viuses two modes, one for text input (the Insert
Mode) and one for executing commands (called 11 RPO eI COE
Normal Mode). It starts in Normal Mode, so you can-
not enter text when you've just launched the editor.
That is so different from almost every other editor lek pageno = tor pages
Wr pet + 85, panene): — / RENO emuccING, Cone

36 101 LINUX HACKS


- 2021 EDITION
FEP IT RUNNING

HACK 2 7 Figure 15

Follow File Updates


Some Linux admins think that the magic of
27-inch display is that you can open 25
xterm windows and use them for various

qT
monitoring activities (Figure 15). If you
need to keep an eye on some critical infra-
structure, it might make sense to log in to

Fr TTT
those machines via SSH and watch activi-
ties in logfiles with the standard command:
bg
tail -f <logfiter
In the case of one daemon process that handles logging of some ser-
But there is a tiny problem: Every now and Vice, telling it to switch to a new version of the logfile is easy. But there's
then a server will rotate some or all of its no way to keep track of various other processes that read the logfile and
logfiles. Rotating such a file means renam- contact the processes in a meaningful way. Using a tool like 1sof will
ing it, possibly compressing it, and creating show all processes that have opened a specific file:
anew logfile with the old name. When a
helper program like logrotate has finished esser@xpsi3:°$ Isof /var/log/syslog
rotating some daemon's logfile, it will then COMMAND =PID USER FO TYPE DEVICE SIZE/OFF NODE NAME
inform the daemon by sending it a hang-up tail 16841 esser 3r-REG 259,3 612458 12058755 /var/log/syslog
(HUP) signal (kil1al1 -HUP daemon); the dae-
mon in turn will close the (old) logfile and But how would you try to inform those processes of a change? The solu-
reopen it. If that last step doesn't happen, tion must lie on the clients's side. For tail, itis simple: Use the -F option
the daemon will continue to write to the old instead of -f, and you're set. It will also make tai! wait indefinitely for the
logfile (even when that file completely dis- watched file to reappear.
appears after a compression step). By Hans: org EBer

Monitor Your System in a Terminal


ary eC ee CMT Cmte SERUM rk ur un esate koe
Da eMC cet run lg Ure nm co Tee Rec Meee ener aera e
Fee eu icra alate ete cule elu on ke eee Anata
Eire ea Wesson NaNO ou Col cs ee ee ae ued ti une eh mn ae
Ele ee Rar et CO 9 up your system. The fan speed will typically ramp up
ora TU a Oke cee item ten tom Poh eu Mra Karicem elas SCH)
Pee OR Reo CMC Pigs ages Zoli load and ongoing performance.
Uta Re AY Mar etia unas ence The folding and unfolding of each element is a quick
Gren eN eters ec TT ae Ce ace) Eu eCOMr AOnmMuek Cen a Pcecee tree
(ate ca) Pan CME UN ean Tuc Sang ue
Ce ekuee ie Secrets unui aurlS
GRU aie eoanarr mea haute ec
Cocina et ink Meee uu
Beene ertuc tierce cleans
Puede ae ae kegOkt
Re ROE nae oe g tome ea
Wate iste unwanted
and libsensor4-dev packages, cloning the Git repository
EI ea Un ee ketal an
en lea
Pie oe

101 LINUX HACKS - 2021 EDITION 37


KEEP IT RUNNING

AN 4 HACK 30
Visualize ddrescue’s Progress Run dmesg with the Right Options
Many users use GNU ddrescue to save data from The dnesg tool shows messages that appear in the “kernel
a faulty disk. However, the resulting logs are dif- ring buffer,” and it can do so in many ways as the im-
ficult to read. ddrescueview graphically processes pressive list of options in its man page shows. But most
logfiles. In order to use it, run ddrescue with a of those options aren’t interesting; you just need a few.
third file name argument so that it creates a Run diesg -HTux to see both user-level and kernel-level
“map file.” Then open that file in the viewer pro- messages with a human-readable, absolute time format
gram (File | Open mapfile). (-H1), as well as priority prefixes (-x) in continuous/follow
First, the tool determines the disk size and dis- mode (-u). That leads to the situation shown in Figure 18.
plays an overview of all sectors in the main win- The color highlighting appears automatically unless
dow (Figure 17). The different colors represent you're remotely logged in from a terminal with strange
how a section is doing and whether the tool was settings; in that case, you can try to force colored output
able to save it (green), it is defective (red), not with --color=aluays.
trimmed (yellow), or not yet recognized (gray). While this lets you look at the screen and wait for fu-
You can receive detailed information about a ture messages, you cannot scroll back. If you want to see
sector via a mouse click: This will open the Block the past, lose the -u option: You will then see the ring buf-
inspector dialog, which reveals where the faulty fer's entire contents (starting with the first lines), and you
section starts, how big it is, and how much data can scroll down to later entries. Note that the ring buffer
ddrescue could ultimately reconstruct. is in fact a ring: Its size is finite, and it will lose the boot
The tool assumes a block size of 512 bytes by messages after the machine has been up for a while. If
default. You can define other dimensions in the you want to restrict dnesg output to user-mode or kernel-
program settings, as well as set up a refresh in- mode messages, add a -u or -k option.
terval that keeps the display up to date while Note also that some pieces of information never make
ddrescue is running. it into this message buffer: Check files in /var/1og as
On Ubuntu and Linux Mint, you can simply apt well; your syslog service might log some information
install the gddrescue (GNU ddrescue) and to messages, syslog, or other files in that folder.
ddrescueview packages.
By Hans-Georg EBer
By Uwe Vollbracht Figure 18
httpsi/www.gnu.org/software/ddrescue/
https:/sourceforge.net/projects/ddrescueview
Figure 17
bcs apt, Fae contrat

Image Copyright Martin Bittermann

101 LINUX HACKS


- 2021 EDITION
KEEP IT RUNNING ~~~

Where Did You Mount That Disk?


If you like to extend your computer's life by adding hard So far, however, you do not know
disks (instead of replacing the old ones), you can which options were set when mounting the
quickly lose track of what partition holds what kind of partition. The mount command shows these kinds of
data. Some elementary tools help you get an overview. details. Its output is quite extensive and often includes nu-
The Isbik (“list block devices”) tool shows all block merous virtual devices managed by the kernel and sys-
devices. The default view in Isblk tem programs. In many cases,
includes only the devices or parti- Figure 19 however, only the physical mass
tions currently in use (Figure 19). oot@hp7420: shomeresser ° storage devices and their
In the right-hand column, you will Fle Edt Wew Seach Terminal Tabs Help mounted partitions are of interest.
find the mount point (i.e., the po- rootehp stan homelesee xm Since Linux partitions mostly
sition at which the device is |rootehp-2420: /hone/esser# Usbik use one of the “extended” file-
mounted in the directory tree). MAJ:MIN RM. SIZE RO TYPE MOUNTPOINT systems (today, typically ext4) or
© 894,36 © disk
The output of Isblk has six col- 1K © part Btrfs, you could filter the output
umns. Table 1 gives an overview 37,36 8 part of mount with grep accordingly.
39,16 ° part
of the information you get from 931,56 ® disk However, this detour is not actu-
600,56 ° part
this list. 1k ° part ally necessary. nount offers a -t
Using the -a switch helps 366 ° part [SWAP] (short for --type) switch that out-
506 ° part Znnt/suse
Isblk reveal more devices by in- 2456 8 part Zant/home puts filesystems of a certain type
931,56 ° disk
cluding devices that are not cur- 833,96 8 part dant/wins or several types only. So, type
rently in use. For example, it will 97,76 ° part mount -t ext4,btrfs to restrict the
232,96 ° disk
show a series of loop devices 00H ° part list to ext4 and Btrfs filesystems.
232,36 8 part
part /nt/win2
(virtual block devices that do not ‘478M ° part If you search for NTFS filesys-
map to a physical device, but use 1024 ° tems, remember that those are
o
a file for underlying storage) from typically mounted via FUSE and
/dev/100p8 to /dev/1oop7. show up as fuseblk, not ntfs. If
you have installed a commercial NTFS driver, the file-
Filesystems system type will be ufsd (universal file system driver).
The -a switch tells you which partitions exist and under Because mount provides so much information, clarity
which mount points they are mounted in the filesystem. can suffer. The output of Findant from the same software
package offers a better structure. When called without
Table 1: Isblk further options, f indant shows a tree view from which you
NAME Device name can see how the individual filesystems are mounted. The
MAJ:MIN Main and extension numbers of the device findant command also identifies the origin and type of
RM Ofor fixed and 1 for removable devices the filesystem and the options with which it was
(like CD/DVD drives) mounted. findant also supports the ~t option, with which
SIZE Storage capacity of the device in human- you can filter for ext4 filesystems, for example (Figure
readable form 20). Unlike mount, findant isn’t limited to a single filesys-
TYPE ‘Type of device (see Table 2)
tem parameter but lets you enter several if required.
MOUNTPOINT Directory in which the device is mounted By Frank Hofmann

Table 2: Isblk Device Types Figure 20


disk Hard disk
loop Loop device
+ ext3,extd, tuseblk
Ivm Logic Volume Manager (LVM) FSTYPE” OPTIONS
extl
partition oxte ru relate,
part Partition on a storage medium ext
rom CD/DVD drive Irsotehp-2420: /hone/esser® [}

101 LINUX HACKS - 2021 EDITION 39


When you expose your machines to the Internet, a
little paranoia makes sense. Hide your tracks on the
WWW, encrypt your files and mails, disable your
webcam and mic, and make sudo secure. And if you
sell your disk on eBay, wipe it — wipe it for real.

Install and Run Tor Browser Enhancing Security with sudo Options

Gea CeCe Use Two-Factor Authentication with Authenticator

TR TU Uece
ae Start Your Training with Web Security Dojo

DTD UKst RSS Reel Lock Your Screen, Always

rena Teun Wetec eca tesa

40 101 LINUX HACKS


- 2021 EDITION
SECURITY & PRIVACY

HACK 3
Permanently Wipe
Files from Your Hard Disk
When you delete a file in the file manager, it
does not exactly disappear. In most cases, it
falls into the recycle bin, from which it can be
quickly restored. But even if you empty the
Install and Run Tor trash, the supposedly deleted data can still be
Browser reconstructed.
Linux supports two console tools, shred and
Do you like how searching for a new TV online will fill web uipe, both of which securely delete files, direc-
pages with ads for just that product over the next few tories, or entire partitions. In practice, how-
months? If not, you may want to stop Google and other ad ever, you will rarely want to launch a terminal
sellers from tracking you. That's not so simple: You need to to wipe a file off your hard disk. File managers
switch to a fresh IP address for every new website you visit, can be equipped with similar functions. For
block cookies, and more. Tor and Tor Browser combine all the example, Gnome Files (formerly Nautilus) has
tricks currently available for secure and private web brows- Nautilus Wipe, an extension that lets you se-
ing. The actual browser is a Firefox version that’s been pre- curely delete files with a single mouse click.
configured to use the Tor network. (For KDE, the Secure delete service menu
Install the torbrowser-launcher package (via apt install on adds the same functionality to Dolphin.) After
Debian/Ubuntu/Mint, dnf install on Fedora, and zypper in on installing the package (nautilus-wipe on
openSUSE) and then run the torbrouser-launcher command Ubuntu), restart the file manager by running
from inside a terminal. If used for the first time, the tool will the nautilus -q command. Two new options.
download the latest version of the Tor-enabled Firefox for are then available in the context menus of
your platform and language, check its signature, and then files and folders. The first one (Wipe) over-
launch it. If you already have a current version, it'll just start writes the objects selected in the file manager
immediately. with random data. The application lets you
In the window that appears after a few seconds, click on choose the number of deletion passes (Figure
Connect; then Firefox — branded as Tor Browser (Figure 1) ~ 2). Two passes are typically sufficient.
will launch, Use the browser as usual and select New Tor After that you should also use the second
circuit for this site from the hamburger menu to reload the option, Wipe available disk space, which over-
current page with a fresh IP address. Figure 1 also shows writes the space marked as free on the parti-
proof in the server logs of a visited site: three accesses to a tion and ensures that backup copies and
non-existent page registered with three IP addresses. shadow files of the previously edited docu-
ments are securely overwritten and thus per-
By Hans-Georg EBer manently deleted.
https:/www.torproject.org/ If you use an SSD instead of a classical hard
disk, things are more complicated, and wiping
Figure 1 will not protect you against an attack by a pro-
w fessional forensic expert.
By Christoph Langner
http://wipetools.tuxfamily.org/
CN, Figure 2
‘Are you sure you want to wipe “testfile.txt"?
if yeuwipeanitem, it wll not be recoverable

fuumber of passes: 2 (advised for modem hard disks)


Fast and insecure mode (po /dev/erandom, no synchronize mode)
Last pass with zerosinstead of random data
Help cancel

101 LINUX HACKS - 2021 EDITION 41


~ SECURITY & PRIVACY

Disable Webcam and Microphone


A computer's webcam and microphone are often Applications such as
abused for attacks and privacy violations. Thanks to Cheese will then no longer find a
modern web technology, such as HTML5 with WebRTC, webcam on the system. If necessary,
a browser is all it takes to transfer the image and sound you can reload the module later (with sudo mod-
from your living room to the web. For example, video probe uvevideo). You will need administrative privileges
chats with AppRTC can be handled directly in the on the system for all of these commands.
browser (Figure 3); a web page could also tap the web- To prevent the Linux system from loading the kernel
cam for other purposes. module responsible for the webcam, add a black] ist
Figure 3 entry to a configuration file in the /etc/modprobe.d/ di-
rectory. On some distributions, you will find a file called
blacklist. conf in that folder; others may prefix the
name with a number (for example, 58-blacklist.conf on
openSUSE). Ifno such file exists, simply create it. The-
oretically, you are free to choose any name, such as
disable-webcan. conf, as long as it ends with . conf. Add
the following lines to that file:
# Hebcam Disabled
blacklist uvevideo

After a restart, the webcam should not work, which


you can test with Cheese or Skype. If you do want to
use the cam, load the kernel module manually (sudo
modprobe).

Although a browser requires the user to confirm that Cams with Microphone
the website is allowed to enable the webcam and micro- Things are a little different with a microphone built into the
phone, errors (on the part of developers, as well as device. Theoretically, as with a webcam, you need to dis-
users) occur time and time again. And with a locally in- able the necessary kernel module, which you can deter-
stalled application — installed voluntarily or by a trojan — mine quite easily by looking at a file in the /proc hierarchy:
you might not even be prompted to confirm. Apart
from a small light in the bezel, there is usually nothing $ cat /proc/asound/modules
to indicate that the device is recording. With some de- @ snd_hda_intel
vices, the program can even turn off the webcam LED. 1 snd_usb_audio
With a classic desktop PC, you can usually simply un- 2 snd_usb_audio
plug the camera and microphone tostop the possibility 3 snd_usb_audio
of video spying. This solution is not available for porta-
ble systems with integrated input devices. Users with However, switching off snd_hda_intel not only takes
laptops and smartphones therefore often apply stickers down the microphone, but also the entire internal
to the webcam and the internal microphones. sound card. In this case, therefore, you need to com-
Alternatively, you can disable the webcam in the sys- promise between sound and perfect privacy. If neces-
tem settings so that programs can no longer call it. On sary, you could still connect a USB headset (even with
Linux, you have to disable the uvcvideo kernel module, an integrated microphone) those devices use the snd_
which is normally loaded automatically at boot time. In usb_audio kernel module.
principle, you can do this manually via You can also scan the BIOS or UEFI settings for an
option to disable the integrated devices. Working at the
sudo modprobe -r uvcvideo BIOS or UEFI level gives you even more security: Theo-
retically, a blacklist created through the operating sys-
but very often, some program will have claimed the tem can be reversed by software running with adminis-
module so that modprobe fails with a “module in use” trative privileges.
error message that forces you to go for the heavy artil- By Christoph Langner
lery and try:
httpsi/webrte.org
sudo rumod -f uvcvideo https:/github.com/webrte/apprte

42 101 LINUX HACKS


- 2021 EDITION
SECURITY & PRIVACY

Disable Password-Based SSH Logins HACK aD


Do you run an SSH server that is accessible from the In- Pubkeyfuthent ication yes must be enabled. Don’t con-
ternet? That is extremely likely if you rent a root or vir- fuse this config file with ssh_config, which is for cli-
tual server from some hosting company or if you have ents. Restart the SSH server (for example, with service
configured your home Internet router to forward some ssh restart).
port to a local machine's SSH port. In order to be safe Copy the public key into the server user's .ssh/au-
from dictionary-based brute-force attacks against your thor ized_keys file by running the ssh-copy-id TARGET
SSH server, you should enable public-key-based access command. This will ask for your password one last
and then disable logins that are based on username time. Check that you can then log into the server
and password entry. without being asked for your password. Repeat this
Before you start, note that if you do this and then step on all client computers from which you want to
later lose the key required for login, you will not be able log into the server.
to login at all. So you need some way to reset the prop- Finally disable password-based login: Back in the
erties, for example via a management console that sshd_config file, search for the line Passuordfuthent
ica
your web hoster provides. (With your personal home tion yes and change the “yes” to “no.” If the whole line
server, there's no problem, because you can log in lo- is disabled via a "#” symbol, remove that symbol. Then
cally to fix things.) restart the SSH server again.
On a client computer, create an SSH key pair with Now logging in should only be possible from the
ssh-keygen -t rsa and protect it with a passphrase. (You computers whose keys you copied to the server; on
can work without a passphrase but should only do that every other machine a login attempt should be de-
when the client computer cannot be lost or stolen.) This nied with the error message “Permission denied
will generate a public key (id_rsa.pub) and a private key (publickey).”
(id_rsa) in your «/.ssh directory.
Log into the server and make sure that key-based By Hans-Georg EBer
logins are allowed: In /etc/ssh/sshd_config, the line

Encrypt Your Emails with GPG


GNU PrivacyGuard (GPG or GnuPG) is a cryptography Asa starting point, read an older GPG article in Linux
tool that lets you send and receive encrypted mail. It Magazine (issue 90, May 2008) that describes how to
also comes preinstalled with every Linux system - but configure Enigmail, the GPG add-on for Thunderbird.
not preconfigured for email. Other mail clients can work with GPG, too: KDE’s KMail
Sadly, there is no out-of-the-box tool that you can in- has built-in GPG support.
stall and automatically have all your communication
secured. Sender and receiver have to use the same en- By Hans-Georg EGer
cryption protocol, and in the case of GPG, some further https:/mw.gnupg.org/
preparation (key exchange) is needed before they can http://www linux-magazine.com/Issues/2008/90/Enigmail
open an encrypted mail channel be-
tween the two. Figure 4
Using a keyserver (such as key-
server.ubuntu.com or pgp.mit.edu),
‘ oe
you can search for public keys (Figure
4) and import them into your GPG cli- Search results for ‘esser.hans-georg’
ent. GPG users often put a fingerprint
in their mail signature so that it’s eas-
ier to find their key. Once you've im-
ported a person’s public key, you can
use it to encrypt a message and send
it. Only that person can then decrypt is
the message, because it requires pos- | “”
session of the private key.

101 LINUX HACKS - 2021 EDITION 43


~ SECURITY & PRIVACY

Enhancing Security with sudo Options


The sudo command has been around since the 1980s, but Starting visudo opens a com-
it has gained popularityin recent years as the default tool mand-line text editor. Usually, this edi-
for running commands as root in Ubuntu. However, tor is Nano or Vim, but you can also set an-
there’s far more to sudo than Ubuntu's policy. In fact, sudo’s other editor. For instance, if you want visudo to run vim
man page is over 700 lines long, covering a staggering instead of nano, you can change the environmental vari-
number of situations — some of which, like many powerful able with the command:
Linux commands, can get you in a lot of trouble if you are
careless. sudo also offers options that can greatly enhance export VISUAL=via; visudo
security, especially if you take the time to be creative.
Why would you want to enhance your security? The The sudeers file itself is divided into three sections. The
answer is that, from a security standpoint, Ubuntu’s use first section is for the default behavior. It lists one op-
of sudo can be viewed as a problem (although opinions tion per line. For example, if you want to use the insults
do differ). As you may know, when sudo is configured option —a genuine option, which insults users who
the way it is in Ubuntu, you can use the password for make mistakes trying to log in to sudo - the entry is:
your everyday account to log in to sudo and run root
commands. The trouble is that any password for an ev- Defaults insult
eryday account is exposed in a way that the root ac-
count is not, especially on the Internet. That means that Default settings can be overridden by specific users’ or
if the everyday account is compromised, the intruder groups’ settings. However, above the specific settings
gains root access, too, if sudo is set up on the system. is a section that defines aliases for hosts (hostnames, IP
The traditional separate root password is more secure, addresses, network numbers, or netgroups), for users
although less convenient. Fortunately, though, you can (account names, UIDs, groups, or netgroups), for users
manage both convenience and security by taking the to run as (account names, UIDs, groups, or netgroups),
time to learn the details of sudo. and for commands (usually with full path names). All
aliases consist of uppercase characters or underscores.
Editing sudoers These aliases exist to make defining specific settings
sudo has a unique configuration system. You can con- less cumbersome. For example, if you want user ac-
figure the behavior of the sudo command using the su- counts bab, plu, and vaf to all have the same privileges,
doers file in the /etc directory (Figure 5). sudoers lists you could create the alias
default behaviors and the privileges granted to individ-
ual users. As the top of the sudoers file warns, it should User_Alias ADHIN = bab, plu, vat
only be edited using the visudo command. visudo is de-
signed to prevent you from editing sudoers in a way With this user alias defined, you can simply define privi-
that would cripple or disable sudo by doing all editing leges for ADNIN, instead of for bab, plu, and vaf separately.
in a temporary file and replacing the original file only In the same way, you create an alias for a list of network
when all editing is done.
Should you make an Figure5
error while editing sudo- a
ers, as you try to save, i yeas tan eee ces
iC
visudo will give you the A e BCs) oeae OMe Cee ae Cre
di rims caeeal
option to reopen its tem-
porary copy of sudoersto if Cea era
correct the errors (e) or — Sc rn constr
discard your edits (x) - ett rie) aaa yy
choices that you obvi- i
ously should not ignore.
Depending on the distri-
bution, visudo may or 4 "C ification
may not display these Ee aeeT prstetats
choices, but they will be Metter ain
available whether dis- Perey at erty
played or not.

44 101 LINUX HACKS - 2021 EDITION


SECURITY & PRIVACY

terminals from which a sudo user can log in ora set of password,
‘commands that a group can or cannot use. Although just as in
aliases can take time to set up, they make creating anew Ubuntu. How-
set of privileges or editing an old set much easier. ever, you can do
In the third section, individual privileges are defined better than that simply by specifying
one per line, using this structure: rootpu, which requires the root password.
Subtler still, targetpu USER can require another account's
[USER or ALIAS] [TERMINALS]=[USER RUN AS] 2 password, so that you set up a user with root privileges
(OPTIONS: ] [PERMISSIONS] that is used only with sudo. With targetpu, an intruder
will need to be able to read the list of users in order to.
Permissions are generally those thata user or alias can find the password for sudo.
use, but adding an exclamation mark (1) in front of Still another basic piece of security is noexec. noexec is
them turns the list into those that cannot be used. designed to limit the running of applications from
For instance, the basic entry for the root user with all which other commands can be run. Without noexec, the
privileges is: running of one application could easily give intruders
access to other applications in the system.
root ALL=(ALL) ALL However, individual privileges are where ingenuity
reigns. With a little planning, you could set up separate
Individual terminals or commands can be entered in- accounts with limited root privileges. For example, one
stead of ALL. USER RUN AS and OPTIONS are optional, so that account could only be permitted to run tools for install-
the line ing package managers, such as Debian’s apt-get, apt,
and dpkg, while another would be limited to running
bab ALL= (ROOT) passud, chown, chgrp, chaod commands for changing file attributes. With such an
arrangement, Linux can be made to mimic other so-
is enough to give user bab the ability to change pass- phisticated Unix descendants. While each limited ac-
words and permissions from all terminals on the sys- count can do specific functions, an intruder who gains
tem, while running as root. More simply still, defining access to one account via sudo would not have com-
an alias called ATTRIBUTES that included all four com- plete control over the system.
mands would reduce the line to:
Getting More from sudo
bab ALL=(ROOT) PERMISSIONS sudo is a sophisticated command. However, as you can
see, it is also a seriously underused one. Even if you
Remember, though, that specific permissions override have no interest in such options as setting the com-
those set as defaults. mand prompt, there are still a number of options that
can make switching into sudo to temporarily gain root
Defaults, Privileges, and Options privileges safer — and all without sacrificing any conve-
Defaults and privileges are defined using the options nience once everything is configured.
listed in the sudoers man page. The available options It is easy to think of sudo as a magical word that some
range from requiring no login whatsoeverto specific distributions require at the front of administrative com-
settings for greater security. mands. And for many people, that may be enough. But
Many security options affect how to log in to sudo. sudo can also be much more. You might even investi-
For example, passuord_tries=NUMBER sets how many gate sudo plugins like Privilege Manager for Sudo,
times a user can try to log in before being denied. It is which allows you to set policies for sudo graphically, or
accompanied by passud_timeout= MINUTES, which sets sudo_pair, which requires an admin to approve any use
how long sudo runs before logging out a user- an es- of sudo. But, one way or the other, if you are concerned
pecially useful feature when using root privileges, about security, you owe yourself the time to learn what
since basic security decrees that the root account else sudo can do.
should be used for as short a time as possible. With
passud_tineout, you no longer have to rely on your own. By Bruce Byfield
memory to close root as soon as possible. Less drasti-
https:/ww.sudo.ws/
cally, timestamp_timeout=HINUTES sets the time before
sudo prompts for another login. https:/ww.oneidentity.com/products/privilege-manager-
for-sudo/
Other options set which password sudo requires from
you. The option runaspu requires the current account's https:/github.com/square/sudo_pair/tree/master/sudo_pair

101 LINUX HACKS - 2021 EDITION 45


Y & PRIVACY

Use Two-Factor HACK


Authentication
with Authenticator
Many of us now use two-factor authentication
(2FA) when connecting to vital online services
such as Google Mail and GitHub. 2FA adds a Start Your Training
second factor alongside your password, with
the most common second factor being a time-
with Web Security Dojo
limited, one-time pin generated by an app on Protecting your own websites from attack either costs
your smartphone. a lot of money or requires a lot of expertise. A special-
But using a smartphone appisn’t always ized Linux environment called Web Security Dojo offers
ideal. This is where Authenticator helps. It is a an easy way for everyday users and beginning profes-
GTK3+ application that fits perfectly into a sionals to learn about web security. Dojo is designed to
Gnome or Cinnamon desktop (Figure 6). It has provide practical, hands-on exercises on web security
both a light and a dark theme and looks lovely, and intrusion techniques. On SourceForge, you can find
oriented in a portrait style much like the app. Its a virtual machine (VM) image of around 3.9GB in OVA
best feature is that when you click the + button format that works with both VirtualBox and VMware; it
to add a credential, almost every service you is based on Xubuntu 18.04.4 LTS with an Xfce desktop.
can imagine that supports 2FA is listed, rather When you launch a browser in the VM, you learn about
than leaving you randomly entering encryption the software you're going to attack: Damn Vulnerable Web
keys in the hope it works. With that done and Application (DVWA). From a menu, you can pick various at-
with the necessary keys exchanged with the on- tack technique options, such as Cross Site Scripting (XSS),
line service, you can then use Authenticator just SQL Injection, CSRF, or Brute Force (Figure 7). For the vari-
like the app — selecting the preconfigured ser- ous scenarios, you will receive background information in
vice to get a time-limited code and entering this the form of links to related websites and wikis.
into your login prompt. Web Security Dojo provides an excellent training oppor-
Having this facility on the machine where tunity for budding security professionals who want to be-
you're likely to use the codes is very convenient. come familiar with the basic mechanisms for protecting
However, it does add a security risk, as anyone web applications. The OVA image is easy to install, and
with access to your machine will be able to con- the Xfce desktop is easy to configure. The developers
nect to your services (if they know the other fac- have carefully adapted the tools and test environments for
tor - the password), so be careful! their intended use, so you can get started with the practi-
By Graham Morrison cal exercises right away.
https:/gitlab.gnome.org/World/Authenticator/ By Erik Barwaldt
Figure 6 https:/www.mavensecurity.com/resources/web-security-dojo
/sourceforge.net/projects/websecuritydojo/

Figure 7

There are no accounts yet...

46 101 LINUX HACKS


- 2021 EDITION
SECURITY & PRIVACY

Lock Your Screen, Always


There are obvious situations when you should lock search for unlocked computers, and open a website
your screen, like when you work in an open-plan office, like lockyourscreen.com (Figure 8). Of course, that's
you have opened four terminal windows with remote better than quickly installing a backdoor SSH server.
root shells on various machines, and you're just about But even in less dangerous situations, it makes sense
to leave for an extended lunch break - you don’t want to lock the machine; if you're at home and have a cat
the computer to stay accessible. who likes to walk across the keyboard, it may provide
During my time as a postgrad, it was a running joke just the right input for the vi editor to do bad things to
that co-workers would enter each other's offices, your configuration file. (However, it is unlikely that the
cat will enter :u and save her changes.)
Figure8 Every desktop has some menu entry for locking the
screen, but it's faster to just press some keys. In addi-
tion to Linux, I've also looked up the hotkeys for two
non-Linux operating systems, because this is important
on every computer:
* Gnome: Win+L
* KDE, Cinnamon, and Xfce: Ctrl+Alt+L
* macOS: Ctrl+Command+Q
* Windows: Win+L
Of course, the Linux desktops will let you change those
hotkeys to something else.
By Hans-Georg EGer
https:/lockyourscreen.com/

Use ccrypt for Quick Encryption


DM uy ACNen reo aay e ae tel BKC ue kc Rscat
Ren Re OMCs reine a) provides a quick solution. It is available
Sere ne aunt Grmeas [suite ence ae nace a
Reet ee recog ecei Tatet ery erage een Cel lon
Rezo CRU it Rene cea Clan eran tun Cs sclccmt aca ue
Se ecm ee eh ene eee ROTA ROME Seu uen ateul mck ct)
elven cn Remi tee Ruchu ha Rat does not echo the characters you type), and that's it.
Erne Te cae tt RC ECR Seanko een ence Cache ea nei
tected ZIP archive is an option, but why create an ar- Pena lat Wan Rane Ieee asec cuit ce
COM CUn COUN nt ort Ta et eric Eee ote eee aCuR ER CCl ro
of the original file.
Figure 9 Tan Ne Reo Conner
Rens eA RT OR een aero mm cet ey
now transfer the file over insecure channels. The re-
sist
rutin on scar at Regen ears
enters the password — after that the original file is re-
S thle test.txteepi Bae Mem eun tt ime ak Lcer S
Jesseronint hexdump -€ test.txt.cpt | head -3 Rese RS Me cit Tt Ruhi turd sirens
Heeoo0gce
(96000810 €7 7a {8 72 9a 39 78 80 beBe C62c ebGf Acsf a88a da4d 33 7
71 £4.24 b2 91 57 82 54. Tee ae CoM Te nC Renae ATE teCoun auaD
(90000026 $9 89in 17 9 8 80 db S 11.cedecrypt
al 18 Aftest.de txt-ept
68 o8 eens
wt
total ¢
Srver-se-- 1 esser esser 1327 May 16 23:15 test.txt ane
Jessergnintanscin Shead -2 test.txt Dit ecg eee gee ee ae
Gf:Desktop Modding
GF:Start theasseln
Right Ap=/D

101 LINUX HACKS - 2021 EDITION 47


Hopefully, your network is doing fine, both Ethernet and WLAN.
If not, look at our hacks that help with network configuration
and analysis. We also talk about clever tools like Magic
Wormhole and Weborf that let you do hassle-free file

PNG a 2 HACK 48
CLT Cle MM Aare WTLUMA Le TERS

HACK 43 ENGL at)


DIY Network Configuration Sa SS SSS)
HACK 44 HACK 50
ve MC RUC Ln Access a Remote PC's Shell Session

LPC) a) LNG oul


TMC AW TUES Ly Slow sudo? Check Your Hostname
eT Coy
HACK 46
Send Files Without Knowing the Target's IP HACK 52
PIN a) Un een Eee
Check Your DNS Server with DNSDiag

48 101 LINUX HACKS


- 2021 EDITION
NETWORKING

Monitor Your Network with Nutty


Network monitoring isn’t easy for everyday connection, and then perform a series of monitoring
users. If you've ever taken a look at the packets processes or tests. Ubuntu users will need to install
captured by Wireshark, they're incredibly complex and from source as described on the project page - there is
difficultto understand. And so too are the associated a Snap package for Ubuntu, but it is broken.
command-line tools. It’s easier for distros to keep users Nutty’s main view is a tabbed interface with the first
at arm’s length, letting them worry about wireless net- pane showing general details about your hardware,
work strength and streaming quality rather than present- such as your hostname, network driver, IP address, and
ing users with a stream of data that's difficult to inter- firmware. The second tab, Usage, attempts to detect
pret. But much like with a task manager or memory which processes are using your bandwidth. This can be
monitor, there are many good reasons for ordinary users. very revealing, especially if you've forgotten about that
to be better informed about their network consumption. Nextcloud daemon quietly syncing your files to the
Nutty is a network monitoring tool that will attach it- cloud in the background. The third tab uses speedtest-cli
self to one of your interfaces, such as your wireless to test the speed of your connection, while the fourth
Figure1 lists all your local ports being used on the network and
the processes attached to those ports (Figure 1). This is
likely the most useful if you want to see which processes
are accessing your network. The final tab will perform a
network scan, much like netstat -sP on the command
line. And that's really what this great little tool is all
about, encapsulating some of the most useful output
from disparate and sometimes difficult to use command-
coset pond line tools to help you monitor your network.
estat on)
By Graham Morrison
nme atten https:/github.com/babluboy/nutty

DIY Network # ip route add default via 192.168.1.1


Configuration You need to substitute 192. 168. 1.1 with your gateway ad-
Just because you can have your IP address assigned dress, which needs to be on the same subnet as you are.
automatically doesn’t mean it's required. Good old Your final step is to tell Linux the DNS server to use:
static network configuration still works in 2021. # echo ‘nameserver 8.8.8.8' > /etc/resolv.
conf
Linux provides several approaches to manual net-
work configuration. The traditional one is via ifconfig This will set up a Google DNS server. Replace that with
and route, but modern distributions don’t automatically your true local DNS server if you know its address.
install these tools anymore. Today's alternative is using Things are trickier if your system uses resol veonf or a
the single ip tool, which is more versatile. similar management framework. In that case, refer to
The roadmap is as follows. You bring the device on- the man pages.
line, assign it an IP address, then add some routes (at If you don’t want to configure the network card but
least, the default one), and configure DNS. Imagine you only look up the current settings, use the shou options
want to configure the network on the ethe device. Then to get the output in Figure 2.
start with the following (as root): By Valentine Sinitsyn
# ip link set up dev ethe https:/en.wikipedia.org/wiki/Resolvconf
This brings the device “up,” that is, to the active state. Figure 2
Now, assign it an IPv4 address with:
# ip addr add 192.168.1.5/24 dev ethe
Itis up to you to ensure that the IP address you've cho-
sen doesn't conflict with anything else on your net-
work. You may also notice that | used a CIDR notation,
addr/nask: It allows you to assign both the IP address
and the netmask in a single command. nask is the num-
ber of bits set in the network mask, so /24 is equivalent
to 255.255.255.8 in ifconfig’s parlance.
The next step is adding the default route:

101 LINUX HACKS - 2021 EDITION 49


NETWORKING

Advanced Tracing wi h traceroute and LFT


Practically every admin uses the classic traceroute tool (LFT). It can handle other transport methods and thus
at more or less regular intervals. This gets me all the makes it through most firewalls. In addition, it can out-
more irritated when | find myself in a hotel with a WiFi put whose network blocks the packet is passing
network where the admin has completely disabled through, including the number of the autonomous
ICMP. Apart from the fact that this causes more system responsible for it (Figure 4).
trouble than benefits in what is by definition a public It is therefore worthwhile to take a closer look at the
network, it can be easily circumvented. different traceroute variations - if only to keep your
The first version of traceroute was written in 1988 blood pressure down during your next hotel stay.
by a certain Van Jacobsen - Van is his first name, not
an honorific. To be able to trace the path of packets By Charly Kéhnast
through the web, Jacobsen came up with a clever http:/freshmeat.sourceforge.net/projects/LFT
method. He sent test packets
through the Internet to a defined Figure 3
destination and increased the frootéglas:-# traceroute bbc.co.uk
time to live (TTL) value for each ltraceroute to bbc.co.uk (151.101.0.81), 30 hops max, 60 byte packets
192.168.1.254 (192.168.1.254) 0.345 ms 0.379 ms 0.486 ms.
packet. 2100.72.0.1 (100.72.0.1) 2.457 ms 2.376 ms 2.401 ms
The first packet is assigned a 100.127.1.6 (100.127.1.6) 6.542 ms 6.216 ms 6.346 ms
2100.127.1.7 (100.127.1.7) 7.186 ms 8.163 ms 7.083 ms
TTL of one. Each router that 100.127.1.11 (100.127.1.11) 6.005 ms 6.374 ms 6.139 ms
transports the packet further re- 185.22.45.30 (185.22.45.30) 10.169 ms 6.764 ms 7.304 ms
duces the TTL by one. Once the * 62.140.26.189 (62.140.26.189) 7.180 ms 7.098 ms
ae-1-3107 .edge5 -Frankfurt1.Level3.net (4.69.163.18) 6.770 ms 7.547 ms
TTL reaches a value of zero, the 0: ms
router sends it back with an ICMP
TIL exceeded message. By succes- 10
aa
sively increasing the TTL, Jacob- ln
sen got the packets back from ha + *
ha #7
routers that were further and fur- lroot@glas:~# traceroute ~T bbc.co.uk
ther away and was able to follow ltraceroute to bbc.co.uk (151.101.64.81), 30 hops max, 60 byte packets
the path of the packet until it fi- 192,168.1.254 (192.168.1.254) 0.407 ms 0.584 ms 0.717 ms
100.72-0.1 (100.72.0.1) 3.442 ms 3.450 ms 3.426 ms
nally reached its destination. 100.127.1.6 (100.127.1.6) 7.772 ms 7.351 ms 7.736 ms
This does not work if the remote 100.127-1.7 (100.127.1.7) 8.035 ms 8.688 ms 9.156 ms
100-127.1.11 (100-127.1.11) 8.160 ms 7.825 ms 7.447 ms
peer suppresses ICMP messages. 185.22.45.30 (185-22.45.30) 11.193 ms 7.460 ms 7.222 ms
However, traceroute has evolved 62.140.26.189 (62.140.26.189) 7.380 ms * *
over the years. It has been able to 213.19.200.114 (213.19.200.114) 12.973 ms 13.240 ms 13.814 ms
use an alternative TCP-based lho 151-101.68.81 (151.101.64.81) 16.583 ms 16.396 ms 13.926 ms
method that relies on TCP SYN rootégias:~#
packets for quite some time. Fig-
ure 3 shows two traceroutes to the Figure 4
same destination, the BBC web
server (bbc.co.uk). The first call froot@gias:-# 1ft -A -N bbc.co.uk:443,
gets stuck at some point, probably racing
due to an ICMP filter. The second
one uses TCP SYN packets ~ it gets PTL LPT trace to 151-101.192.81:443/tcp
[AS198949] (PRIVATE-ADDRESS-CBLK-RFC1918-TANA-RESERVED] 192.168.1.254 24.5ms
to its destination unhindered. [ASN?] [SHARED-ADDRESS-SPACE-RFCTBD-IANA-RESERVED] 100.72.0.1 24.2ms
Alternative traceroute tools, [ASN?] [SHARED-ADDRESS-SPACE-RFCTBD-IANA-RESERVED] 100.127.1.6 24.2ms
[ASN?] [SHARED-ADDRESS-SPACE-RFCTBD-IANA-RESERVED] 100.127.1.7 24.2ms
such as MTR which continuously [ASN?] [SHARED-ADDRESS-SPACE-RFCTBD-IANA-RESERVED] 100.127.1.11 24.2ms
repeats the trace and thus helps. {AS60294} [RIPE~185/DE-DGNO-20130326] 185.22.45.30 24.2ms
[AS2356] [RIPE-C3/FRANKFURT-CUSTOMER-SERIAL-LINKSS] 62.140.26.189 600.0ms
to detect occasional packet {neglected} no reply packets received from TTL 8
losses, take things one step fur- [AS3356] [RIPE-213/AMSTERDAM--CUSTOMER-LINKS) 213.19.200.114 24.2ms
{AS54113} [SKYCA-3] [target] 151.101.192.81:443 24.3ns
ther. Another very interesting
tool is Layer Four Traceroute lroot@glas:~#

50 101 LINUX HACKS - 2021 EDITION


= > NETWORKING i‘

keep the local LAN still visible, | define it as an excep-


tion using the -x parameter:
In untrustworthy networks, | let OpenVPN tunnel my lap- sudo sshuttle -r --dns <User>@<Server> 8/8 -x 192.168.2.0/24
top. There are certainly alternatives, and | would like to
present a particularly simple one: sshuttle. As the name dns is included here. This means that DNS queries also
suggests, the tool relies on SSH. The tunnel’s endpoint is run through the tunnel, which does not happen auto-
a leased root server, just like with OpenVPN. Sshuttle is matically. This is sshuttle’s Achilles heel: It only trans-
very frugal. It only needs SSH access with user privileges ports TCP; ICMP and UDP do not pass through the tun-
on the server; root privileges are not necessary. Addition- nel, apart from DNS.
ally, Python must be installed on the server— that's it.
This is because sshuttle loads and executes the re-
quired Python code on the server after the SSH connec- Whereas other VPN technologies work at packet level
tion is established. It also avoids version conflicts be- and rely on TUN/TAP devices, sshuttle works at session
tween server and client software. The following com- level. It assembles the TCP stream locally, multiplexes
mand is all it takes to set up the tunnel: it over the SSH connection, while keeping the status,
sudo sshuttle -r <User>@<Server>:<Port> @/8 and splits it into packets again on the destination side.
This avoids the TCP-over-TCP problem that plagues
You can leave out the port number if it is the SSH stan- other tools such as OpenVPN: TCP has an overload
dard port 22. The 6/8 means that Linux should direct all control (congestion control). The protocol defines a
connections into the tunnel. However, this means that | performance limit on the basis of dropped packets. If
cannot reach other devices in the local network. To you tunnel TCP over TCP, you lose congestion control
for the inner connection, which can lead to bizarre error
Figure5
patterns. Sshuttle is immune to the problem.
Verbose parameters can help if you do need to trouble-
shoot. Figure 5 shows a connection setup with -v. With the
verbose option, sshuttle is very long-winded, so | recom-
csr mend redirecting the output to a file that can be evaluated
in peace. My conclusions: Sshuttle is an excellent and sim-
ple VPN for people who can do without UDP and ICMP.

https:/github.com/apenwarr/sshuttle

Magic Wormhole really is one of those tools that, once by the same phrase, and the transfer
you've used it, you'll wonder how on earth you managed will start immediately downloading the file
to get by without it. This is because Magic Wormhole from one machine to the other, no server required. It's
solves one of those ancient problems that have been perfect for transferring between virtual machines or
around on Linux since we first started to connect comput- people sitting next to each other.
ers together with null modem connectors and a couple of On Ubuntu, install the Snap package (snap install
lengths of wire. Back in those olden days, you might have wormhole); the package you can get via apt is broken.
used ZMODEM to transfer a file across the serial connec-
tion. If you then upgraded to a connection capable of TCP/ https:/github.com/warner/magic-wormhole
IP, you could use FTP to transfer files and then came HTTP.
In the modern age, scp is often the best choice if you're ac- Figure6
cessing an SSH server and want to securely transfer files,
or rsync if you want to copy folders or perform incremen-
tal backups. But all of these solutions suffered and suffer
from the same problem: The remote machine needs to be
running a server of some kind, and you need to know the
remote address of the machine you want to access.
This is why Magic Wormhole is so brilliant. If you want
to send a file, simply type wormhole send followed by the
file name (Figure 6). In the output, you'll see a secret
phrase that you'll need to share with whomever you want
to receive the file. The phrase is constructed from a few
words, so it’s easy to say or copy without mistakes. Your
recipient then simply types wormhole receive followed

101 LINUX HACKS - 2021 EDITION 51


NETWORKING

Check Your DNS Server with DNSDiag HACK 47


If some transactions take an inexplicably long time, you The result from running it shows a remarkable dis-
don’t have to blame yourself for the delayed transmis- crepancy between minimum and maximum response
sion of user data — name resolution issues might be to times (Figure 7).
blame. Three tools help in studying the DNS server:
dnsping, dnstraceroute, and dnseval. Highwayman?
The tool collection for name resolution is entitled dnstraceroute determines the path my DNS query takes
DNSDiag. If you run Ubuntu, simply apt install dnsdiag. to reach the target. By comparing this with a classic
On other distros, you'll need Python 3 and pip3 to install ICMP traceroute, | can identify an attacker trying to kid-
and run the trio. Use sudo to let it create ICMP sockets. nap my DNS queries. My test call is:
dnsping lives up to its name, repeatedly querying a
DNS server and displaying the response times. The host- sudo dnstraceroute --expert --asn -C ~s 8.8.4.4 2
name to be resolved is a mandatory parameter. dnsping Vinux-magazine.com
prompts you for the system's default name server, which
can be changed using -s <naneserver>. After typing The result is shown in Figure 8. The --expert parameter
provides tips if something seems to be suspicious in
sudo dnsping -v -s 8.8.8.8 linux-magazine.com the output — for example, if the target server is only a
hop away from a private IP address (RFC 1918). False
I queried a public DNS server from Google. Its re- alarms also occur if you are not working on a cloud
sponses took 20 milliseconds to reach me, four times server, but locally, and a DNS cache such as Dnsmasq
more than my provider's DNS. is running on the router.
dnseval queries several servers in parallel. As a compe- For each hop, the --asn parameter shows you the au-
tition judge, it presents the results so that you can imme- tonomous system providing the network for the ad-
diately see which server responds fastest or slowest. | dress. | can thus quickly see where the process crosses
redirected the list of servers to be checked into a text file, my provider's boundaries.
with one server in each line. Lists of public DNS servers By Charly Kiihnast
are easy to find; | took the first five servers from the list
in an article on lifewire.com. The call looks like this: https://dnsdiag.org/
https/wwuilifewire.com/free-and-public-dns-servers-2626062
sudo dnseval -f ./liste.txt -c 5 linux-magazine.com http:/wvwwthekelleys.org.uk/dnsmasq/doc. htm!
Figure 7
server min(ms) max(ms) stddev(ms) lost (*)
209.244.0.3 225.456 630.450 276.140
64.6.64.6 120.021 203.152 46.536
8.8.8.8 19.474 26.253 5.138
9.9.9.9 13,115 18.752 6.193
84.200.69.80 165.459 568.930 237.859
Figure 8
lesser@ubu2104:~/Documents$ sudo dnstraceroute --expert --asn -C -s 8.8.4.4 Linux-magazine.com
ldnstraceroute ONS: 8.8.4.4:53, hostname: linux-magazine.com, rdatatype: A
gateway (10.0.2.2) 1.121 ms
CSTOHE UNE

fritz.box (192.168.178.1) 3.456 ms


[email protected] (62.214.63.87) [AS8881 VERSATEL, DE] 17.633 ms
62.214.36.213 (62.214.36.213) [AS8881 VERSATEL, DE] 14.544 ms
62.214.32.35 (62.214.32.35) [AS8881 VERSATEL, DE] 22.813 ms
*
108.170.236.175 (108.170.236.175) [AS15169 GOOGLE, US] 23.104 ms
66.249.95.169 (66.249.95.169) [AS15169 GOOGLE, US] 26.901 ms
dns.google (8.8.4.4) [AS15169 GOOGLE, US] 27.418 ms
Expert Hints
[*] No expert hint available for this trace
lesser@ubu2104:~/Documents$ ff

52 101 LINUX HACKS


- 2021 EDITION
NETWORKING

Run a Simple HTTP Server: weborf


The wormhole tool mentioned in Hack 46 is perfect for to do NAT traversal to share files outside of the local net-
one-off transfers, but it's not all that great if you want to work and sending directories as . tar.qz files.
share more than a single file or leave the tunnel open
so that you don’t have to keep renegotiating keywords. By Graham Morrison
There are lots of ways this can be done, but ueborf re- https:/github.com/Itworffweborf
mains almost as simple to use as uorshole. Figure 9
ueborf (Figure 9) sets up a simple HTTP server, just like
running Apache in the olden days to share the contents of
/srv/uu. This makes it supremely flexible, not just from a
web browser, but from almost anything with access to the
network using WebDAY, with caching, even from virtual
hosts or running CGI scripts. You simply run the server
command with an argument for the port to use (-p port)
and a folder to share (-b dir), and all the client has to do is
access your IP address with the correct port. It can be run
in the background as a daemon, use certificates, handle
authentication with your own tools, and listen only for
connections from specific IP addresses. If the command
line offers too many options, queborf (available in a sepa-
rate package), a convenient Ot-based GUI can be run to
handle all this semiautonomously, even adding the ability

Use screen in SSH Sessions


Imagine that you work on a remote machine via Maybe you're not sure whether there is already a screen
SSH and launch a command that will take some session: The tool offers a -1s option for that situation:
time to complete (such as a build process). If he computer esser@hp-2428:$ screen -1s
you're working on goes to sleep or temporarily loses its There is a screen on:
network connection, the SSH connection will die. The re- 16712.pts~6.np~2428 (85/86/2019 11:2. 19 AM) (Detached)
mote machine will notice and terminate all processes 1 Socket in /run/screen/S-esser.
started in that login session, so your build process is gone.
There are several things you can do to avoid such a You can even automate the procedure of logging into
scenario. An old trick is to prepare for network outages the remote machine and checking for screen sessions.
and connection loss by explicitly running processes in Create a file ~/.bash_login (if you don’t have one al-
the background and using the nohup command so that ready), and add the following line to it:
they will ignore the hang-up signals that are sent after screen -Is > /dev/null & screen -1s
connection loss. For the build process, that might be
nohup make & That way, when you log in and there is a detached
screen session, you will be notified about it (Figure 10).
instead of a simple nake command. Aside effect is that (Bash only executes «/.bash_login in login shells.)
all output will be written to a nohup. out file in the current If you want to manually detach from a running ses-
directory. sion, press Ctrl+A, D. There are many more interesting
My preferred solution does not require nohup or simi- things you can do with screen — check the man page and
lar tricks. Instead, | use screen in remote sessions. (If try a few of them.
your machines don't have it installed, the package is By Hans-Georg EGer
typically called screen, too.)
When screen starts, it displays a longish message about Figure 10
copyrights and licenses; press Return to get rid of it. You
can then continue to use the shell as usual. If you lose the
connection, simply reconnect to the remote machine and
run screen -r to reattach to the existing session.

101 LINUX HACKS - 2021 EDITION


Access a Remote PC’s Shell Session
Your parents or friends have replaced an unmanage-
able Windows installation with an easy-to-use Linux Creating Keys
variant, and they have designated you as their remote After the installation, which occupies only a few kilo-
admin. To access the system from afar, you resort to a bytes on your disk, you need to create a key pair for SSH
GUl-based tool such as TeamViewer or AnyDesk. All is (if it does not already exist). As shown in Figure 11, this
well until the GUI for the computer you need to access is done by typing ssh-keygen -t rsa -b 4096; answer the
breaks. Suddenly, your GUI-based remote access tool individual prompts by pressing the Return key. You can
won't work anymore, because you don’t have access to assign a password for the key, but in our example this
an X server. is not necessary for home use.
Tmate, which stands for “team mate,” offers a con- ‘Tmate uses the RSA cryptographic procedure with a
venient solution for remote access in situations when secure key length of 4096 bits. By default, the keys are
you can’t depend on the graphical tools. This fork of located in the hidden .ssh/ directory in your home direc-
the populartmux terminal multiplexer has signifi- tory; tmate will find them automatically when you use
cantly more functions than the original. Tmux is func- the tool. You need to generate these keys on each com-
tionally similar to screen (see Hack 49) in some ways. puter involved if a key pair does not already exist there.
You can use tmate to create and manage remote vir- When you open a connection, the program creates a
tual sessions within a terminal. 150-bit session token. It then launches a tmux server in
a sandbox without a filesystem and user rights, but
Self Hosted with its own namespace to isolate the server from
Tmate is not only suitable for external help, but also other processes. To make this possible, the software
lets developers collaborate on software. Technically, opens all the files it needs for running the tmux server
the tool uses SSH to establish a secure connection to before they end up in the sandbox.
the tmate.io server, which is under the control of the
tmate developers. SSH ID or URL
Alternatively, you can run tmate on your own server. After starting tmate as a user for the first time, a bar at
The resource requirements are kept within such narrow the bottom of the terminal window shows a random
limits that a recent Raspberry Pi or a similarly equipped SSH ID for establishing an SSH session in read/write
single-board computer is sufficient. The machine only mode, and a total of four connection methods is shown
generates an SSH ID and some URLs for different types on the top of the window (Figure 12). Copy those lines,
of sessions— SSH or web sessions in read-only mode into a file - you will need one of them to connect. The
or with full access. bottom line will be replaced with a tmate status line
Installing tmate is easy, because the program is avail- after a few seconds, and the longer info text goes away
able from the package sources of all common distribu- when you press q or CTRL+C.
tions. For Arch Linux, use the AUR user archive; for If you lose the connection data, you can bring it back
Debian, Fedora, and their derivatives including Ubuntu, with the tmate shou-messages command. This command
just install the tmate package with Apt or DNF. is also used for logging during a session (Figure 13).
Figure 11 Figure 12
feort-WaaiW:-$ ssh-Keygen -t rsa -b 4096 ee
Generating public/private rsa key pair.
Enter file in which to save the key (/hone/ft/.ssh/id_rsa):
| Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /hone/ft/.ssh/id_rse.
Your public key has been saved in /hone/ft/.ssh/id_rsa.pub
The key fingerprint
'HA256:23 eirSgEaYvyqs9zF389B65SIYJ82Ik3pOPLHtzr8 ftett-Nl4xiM)
The Key's randonart image is: Jesh sesston read only: ssh ro-Nir2utbcstdshyhaUn2skhayxelont.tnate.t0
~-[RSA 4096]----+ b session: https: //tmate. Lo/t/thh}YSEBKagx44LbshSnLdsU
Te ssh sesston: ssh uthh}voeskagnsaibshsnLdsuelont.tnate.to
l+=@
[+08
I
I
1
1
Jo.
I+

54 101 LINUX HACKS


- 2021 EDITION
Figure 13
Ft@Ft-NL4xWU:-$ tmate show-messages
Thu Nov 22 8:49:06 2018 [tmate] Connecting to ssh.tmate.io...
Thu Nov 22 68:49:07 2018 [tmate] Note: clear your terminal before sharing readonly access
Thu Nov 22 68:49:07 2018 [tmate] web session read only: https://tmate.io/t/ro-VdXxGZbJ2iwxSyIYCCZG2CF76m
Thu Nov 22 68:49:07 2018 [tmate] ssh session read only: ssh ro-VdXGZbJ2iwxSyIYCCZG2CF76mGam2.tmate.io
Thu Nov 22 68:49:07 2018 [tmate] web session: https://tmate.io/t/mCiIE3rEXHPD8hcwCluC3t2miv
Thu Nov 22 08:49:07 2018 [tmate] ssh session: ssh [email protected]. io
Thu Nov 22 69:01:34 2018 [tmate] A mate has joined (89.249.64.155) -- 1 client currently connected
Thu Nov 22 09:06:16 2018 [tmate] A mate has joined (95.168.145.55) -- 2 clients currently connected

While the SSH ID displayed at the start of tmate cre- connections: Just create a URL https://tmate.io/t/SES-
ates a read-write session in a terminal, the longer SION where SESSION is replaced with the username
output (or tate shou-messages) also shows an ID for a part. The tmate software itself is only required on the
terminal session that supports read-only access. In machine where you want to start sharing a session—
addition, the program provides two URLs that sup- that can run Linux, macOS, or one of the BSDs.
port the same procedure in the browser. When the other party now enters the transmitted
You should hide the IDs by clearing the screen before SSH ID/URL, the terminal shows what the person seek-
you share the session in read-only mode so you do not ing help is seeing in the terminal themselves. Com-
publish the read/write session information. mands and their results run back and forth between the
computers in fractions of a second. In the session with
Sending Keys read and write access, all parties can enter data them-
Now you only have to send the SSH ID or URL to the selves. In the restricted session, only the host can write;
other participants of the session. The best way to do the participants remain restricted to reading.
this is to use chat and mail or share via a service such Ifyou no longer need the split terminal, itis advisable
as Nextcloud. The final option you could consider is an to end the session by entering exit. If you just close the
error-prone transmission by telephone. terminal, the other side will still have access to the
The participants you invited and entrusted with an ID computer — a potential security risk.
or URL do not need to install tmate or tmux. You don’t
need to use the same distribution or even use Linux: By Ferdinand Thommes
Any operating system is fine as long as it has an SSH https:/tmate.io/
client (Figure 14). And even the SSH client requirement https:/igithub.com/tmux/tmux/wiki
can be lifted, because tmate also supports web-based https://wmanw.gnu.org/software/screen/
Figure 14

3:4.8.26-1 (489 KB)


Fetched 1.789 48 in 0s (4.461 K8/s)
selecting previously unselected package mc-data
Reading database ... 210596 Files ond directories currently installed.)
Preparing to unpack’ .../ac-dato_33304,8,26-1-a11.deb
unpacking me-dato (3:4.8.26-1)
Selecting previously unsetect
unpacking wc (3:4.8.26-1)
setting up mc-date (3:6.8.26
Setting up me G:4.8.26-1)
Processing triggers for eon
Processing triggers for rat
Processing triggers for desk
Processing triggers for hicol
Processing triggers for gnome

101 LINUX HACKS - 2021 EDITION 55


NETWORKING

> Slow sudo? Check Your Hostname Configuration


While playing with a virtual machine, may cause a delay when you have mismatching infor-
| came across a strange problem: Each time | ran a mation in your network configuration files.
command via sudo, there was an artificial delay of When you notice inexplicable delays, check the con-
about two or three seconds. After some Internet tents of some of your configuration files — even if you
searches and a confirming look at the source code, | don’t think the problem is network-relate
found out that the sudo tool queries the hostname of * /etc/hosts should have an entry for your hostname—
the machine on which it is running, and that operation either pointing to 127.0.0.1 (in that case it will be
placed on the same line as the localhost name) or on
Figure 15 a separate line with some other 127. address.
ae * /etc/hostname should contain the hostname.
* Running the hostnane command should also return
fessergubu2s0 ~$ head -5 /etc/hosts the hostname.
Figure 15 shows a situation (taken from an Ubuntu
le31the foLtowing Lines are destrable for 1ev6 capable hosts 21.04 desktop) in which settings are as expected: All
{p6-Locathost {p6- Loopback three use ubu2164. If you get different results (which
bu2ied:~§ hostnane may happen after you have manually changed the
hostname instead of using your distributions “offi-
cial” configuration tool), fix the situation so that the
new hostname replaces the old one everywhere.
By Hans-Georg EGer

rack BZ Use Network


Manager's CLI
Network Manager, the configuration tool used by most
nmcli dev wifi connect SSID password PASS
(with SSID and PASS replaced, of course). You need not
add sudo, because the tool connects to a daemon that has
current distributions, comes with a command-line pro- the necessary privileges. Actually anyone who is logged
gram called nicl (which is short for the obvious: Net- in to the machine can use nncli or any other program that
work Manager command-line interface). It lets you talks to Network Manager- for some tasks it will explicitly
query some interesting data, including available WLAN request root privileges or fail when run as a regular user.
access points (Figure 16). There is a long list of sub-commands (such as dev and
When you're in a new place like a hotel and you've connection) that you can use with nmcli. Check its man
received a paper slip with an SSID and password, you page or the separate nic! i-examples(5) man page for
can use nicli to connect without going through a further useful examples.
graphical dialog. Just type
By Hans-Georg EGer
Figure 16 https:/wiki. gnome.org/Projects/NetworkManager

[rootespst3:-# ancli dev status


loevice Tyee" staTE "CONNECTION
bip2sd wil connected essernet1
flo Loopback unmanaged =~
MODE CHAN RATE secuRrTy
Tofra 6 138 My
Infra 60405 Mi
Infra 130 Mott/
infra 495 Mbit/s 4
Infra 195 nott/s
Infra 138 wit/s
Mubocsa
Plstanget ts inte 139 Nate/s
cease 130 RaUt/s 3
pea
feotesi3e-

56 101 LINUX HACKS


- 2021 EDITION
ts

v : =

D
a es
s Pgh

eh he ge

* e

. ORDER NOW! °
e https://bit.ly/Archive-DVD +
This is Linux, so you've expected us to talk
about the shell, haven’t you? There are so
many interesting things that you can doina
terminal window that we
could have filled a whole HACK 53
issue. Replace some of the Configure Your Shell History
classic commands with Lr ary
enormously improved Progress Bars for Standard Tools
versions. HACK 55
Replace top with htop
HACK 56
Sees
Xena
eu cg
HACK 58
Pee TOS ics
HACK 59
ASCII Browsing with Browsh

HACK 60
eM ne eee Ley
HACK 61
Highlighting Instead of Grepping
HACK 62
OM AC ROn ela RAST!)
bre ax]
Crane CUucun ctr gusts
HACK 64
The fish Shell
HACK 65
ees
HACK 66
Nereus

58 101 LINUX HACKS


~ 2021 EDITION
SHELL HACKS

Configure Your Shell History $ dnesg -T | tail -2


dmesg: read kernel buffer failed: Operation not permitted
Most tasks are repetitive: You enter the same directory, $ sudo !!
open the same file in your favorite editor, and query sudo duesg -1 | tail -2
your dynamic IP address once again. Typing the re- [sudo] password for esser:
quired commands again and again would be annoying, [Tue Jun 8 06:28:53 2621] r81S2 2-1.4.2:1.8 enx@de@dcc>
but often you won't have to do that: The shell remem- 2de5@: Promiscuous mode enabled
bers your commands and stores them in its history~ [Tue Jun 8 06:39:24 2621] device enx@@e@dcc2deS@ left >
both in memory and (when you exit the shell) ina file in promiscuous mode
your home directory.
Accessing the history is as simple as pressing the Up How old can a command be and still show up in the his-
arrow key: Each keystroke will travel back further in time tory? That depends on how often you use the shell — and
and show the last command, the second to last one, and on the HISTSIZE variable that is typically set to 1880:
so on. When you have found the right command, either
press Return to run it again or editit (like you would edit a $ echo SHISTSIZE
freshly entered command with a typo). 1900
Walking through the history with the Up arrow key
might take too long if the command you want is rather By default, a shell process will remember the last 1,000
old. You can skip the manual search if you know some command lines. If you want to improve the shell’s
part of the command or its argument!s): Just press Ctrl+R memory, just add an:
and type the letters you remember from your command.
IF you cannot make your search expression longer and the export HISTSIZE=20000
current match is not what you're searching for, press
Ctrl+R again to let the shell find an older match — repeat line in your ~/.bashre file (and replace 28888 with the
until you've found the right command. value you want).
Another way to search for and reuse an old command When you increase HISTSIZE, you should also change
is running the history command: This Bash built-in a second variable: HISTFILESIZE controls how many lines
shows the whole history and prefixes every entry with a the shell writes to the ~/.bash_history file when it termi-
number (Figure 1). You can rerun a command from the nates — that is where the shell stores the history so that
list by typing ! and the number, and you can add text be- it can read it back when you start the next shelll session.
fore and after the !-number expression that lets you There are more variables that influence the shell his-
modify the command. In the example in Figure 1, I've tory: For a full list, search for “hist” in the bash(1) man
built a pipeline out of history entry 73 (nodinfo uio) and a page. One last variable that I’d like to mention is HISTTINE-
fresh head -2. FORHAT, which normally is undeclared. If you set it to xF *T
The Bash shell also provides a shortcut (1!) for the (plus a trailing blank), history entries gain a timestamp:
last command ~ why would you need that when the Up
arrow key will bring back the last command? One ex- $ HISTTIMEFORMAT="xF xT "; history | tail -4
ample use is combining the last command with sudo so 975 2021-84-26 18:24:42 echo SHISTCHD
that it runs with root privileges. In the following lines, 976 2021-04-26 18:26:88 history
you can see a failed attempt to show the kernel ring 977 2021-84-26 39 echo SHISTTINEFORNAT
buffer and then a successful one via sudo |!. 978 2021-84-26 18:32:89 HISTTINEFORMAT="%F xT"; 2
Figure 1 history | tail -10
ares The shell will also store those timestamps in the history
See cust) file (see Figure 2).
be By Hans-Georg EGer
SCRUM Tse iets
Crone Figure2
ates
dpkg -l coreutils
sero
nt
history caltrh .config/
Sesame)
eee eed s -altrh .config/fish/
eC eRe er enc ess -config/fish/fishd. 068027493843
Cr C aC echo §X0G_DATA DIRS
Cams slocal/share/fish/
local /share/fish/fish_history
fish

101 LINUX HACKS - 2021 EDITION


SHELL HACKS

HACK 5 4 Replace top with htop


There are few tools more effective HACK I)
Progress Bars for than the venerable top command for
Standard Tools process monitoring and control. This is because it
Almost since the beginning of Unix time, Unix com- can be run from almost anywhere that has a Linux
mand-line tools have done very little to show their command line and gives you an immediate and real-
output. The bearded wisdom is that if you can’t see time overview of what processes are running; how
any output from a command then nothing has gone much memory, swap, and CPU they're consumin:
wrong, and you can assume whatever task you and the ability to kill a process by simply selecting it
started has completed successfully. If you need error and issuing a command. Except that top is perhaps a
and success states, look for exit values and act ac- little too venerable at times, with its minimalist and
cordingly. This principle actually works very well, and austere user interface written for 1984-era Unix rather
it would be lovely if it were adopted by modern tech- than the cloud droplets of the 21st century. htop is a
nology, such as REST websites and convergent mo- drop-in replacement for this fabulous command.
bile apps. But it does leave you with some ambiguity htop adds lots of features lacking in the original,
over whether something is still running, and if itis, and its developers occasionally release new versions
how long until you can go to bed and turn off your PC. to make it adapt to new featuresof the various ker-
This is where progress can help. It works with nels it supports: Besides Linux, htop runs on macOS,
many of the GNU core utilities that most of us take FreeBSD, OpenBSD, and Solaris.
for granted. These core utilities include cp, av, dd, tar, Launched just like top, and with shortcuts and argu-
9zip/gunzip, cat, and many more. You simply run ments that offer the same kind of functions, most new
them alongside the progress command, either after users can simply continue with this new tool just as
the uatch command to present a general overview of they would with the old one. They'll get a much more
core utility commands or forked after the execution reactive curses-based interface and overview of what's
of one specific command. running (Figure 4). Unlike top, there's a function key-
For example, you can monitor the progress of com- driven menu system that can be used to change the
pressing a tar archive with: sort mode, kill processes, and get help. There are lots
of other shortcuts, too ~ such as pressing Shift+H to
gzip /root/usr.
tar & progress -ap $! see threads or S for integrated strace (which requires
running htop as root). I's quick, powerful, and takes
and let progress display the gzip percentages as the very few resources. If you haven't already switched
compressor completes its task (Figure 3). This is use- from top to htop, now is the perfect time to do so.
ful if you're working with slow USB storage devices
on the command line. The tool simply monitors By Graham Morrison
/proc/PID/fd and /proc/PID/fdinfo folders for pro- https:/htop.dev/
cesses it watches: fdinfo shows the current read/write
position. It's a simple solution, but it works well and Figure 4
can be used in a huge variety of tasks, from monitor-
ing a file or web server to the download status of
something you've clicked in Firefox.
On Ubuntu, install the tool via apt install progress.
By Graham Morrison
https:/github.com/Xfennec/progress Astana rs nae
Figure 3

File Edt View Bookmarks Settings Help

Besser: progress | essersbash | Downloads: bash Ml esser:bash | Bll ombp2

60 101 LINUX HACKS


- 2021 EDITION
Super-Fast Terminal Emulator is that this speed comes from a part of your system
you're unlikelyto be fully utilizing while typing on the
We don't often consider the speed of terminal emulators command line, and that’s your GPU. Alacritty uses
like Konsole or xterm. The commands we run in them OpenGL directly to harness the power of your graphics
are nearly always the culprits when it comes to clogging hardware and is capable of rendering around 500 frames
up the system, but that doesn’t stop developers from try- per second with a high-resolution screen full of text, ac-
ing to create the fastest terminal in the land. This is what cording to the developer (Figure 5).
Alacritty is - a terminal emulator that promises “blazing The motivation behind developing Alacritty is to give
fast” speed. It’s even brave enough to claim to be the terminal-intensive applications, such as Vim or tmux, a
fastest terminal emulator available, and | certainly found much needed performance boost, especially when run-
it faster than anything | had installed. But the clever part ning on high-resolution, high-pixel density displays. It
Figure 5 draws a new frame whenever anything changes within
the terminal (and not when the terminal is sitting idle),
and you notice this whenever you deal with screenfuls
of scrolling text. What's even more remarkable is that
Alacritty is written in Rust. Thata new and modern lan-
guage can perform as well as traditionally speedy but
dangerous languages like C or C++ is a sure sign of the
future in terms of both code security and validity. It also
helps that the terminal looks so good, thanks to the sub-
pixel anti-aliasing, which is presumably coming for free
with OpenGL. If you use a terminal all the time, it's only
when you try a super-fast program like Alacritty that you
realize you were using an old one. Ubuntu users can in-
stall a snap via snap install --classic alacritty.
By Graham Morrison
https:/github.com/alacritty/alacritty

Universal Unpacker The tar command, in particular,


regularly challenges users with its
Linux users often have to deal with file archives in ZIP, cryptic syntax. Especially annoying
RAR, or compressed tarball (tar.gz, tar.bz2, tar. x2) for is an archive full of files that are not
mats. The commands for unpacking these archives are stored in a separate subdirectory when unpacked but
as different as the formats: unzip, unrar e, and tar xf. instead clutter the current folder. Such shortcomings
Figure 6 are addressed by the dtrx unpacker— the abbreviation
stands for “do the right extraction.”
lp tar xt badetarbalttarex2
Wt evel All the popular distributions have dtrx in their pack-
Peomlssions Links Size Blocks ser Group Oate Modified None age sources; under Ubuntu, the installation includes a
number of tools for unpacking. On the other hand, with
aK CHANGELOG. nd
Arch, you have to install the necessary tools yourself.
conttg.cont
As a wrapper, dtrx is not able to unpack archives itself,
S travis.cont but it composes the required syntax for you. You only
se LrCeNse. na have to remember dtrx file_name to unpack an archive.
amt reofetch.1 Figure 6 shows dtrx in action: The badly built
bad-tarbal |. tar. xz tarball does not contain a base sub-
directory, so all the data would end up in the current
dre badetarbatttar axe folder when unpacking with tar xf. Additionally, tar
BM srtevetee
Permissions Links Size Blocks User Group Date Hoditied Hane adopts the file permissions without changes - in the
example, you are not allowed to edit the files without
mx : ChwnceL06.nd first modifying the permissions using chmod or a file
License. manager. dtrx corrects all of this in one command.
reoteteh.1 By Christoph Langner
https:/Mdirectory.fsf.org/wiki/Dtrx

101 LINUX HACKS - 2021 EDITION 61


SHELL HACKS

Listing Files with Style Figure 7


The 1s command, which lists the content of a directory, Prrmisrae torrLioks’ningSizeT Blocks Wer Group Oate
Permissions Modtied Nase
is one of the most common Bash commands. If you're ae 2 ry
1
.
8
Cee eee a-scret
24 Jan 2013 andyshooter
looking for more information, try extending the simple 1 8 ‘4 Jon 2014 auagrossnachketn,sh
a1 86 rs 166 Okt 2015 backup-
1s command with Is -alh. The -alh options turn the palais Sep 18:42 dies
simple list into a complete overview, including file per- 1
1
6
8
2 Hal
12 Fed
2010
2013.
dvext
echo te.py
missions, ownership, file size, and more. The com- 1 s 21 Dez 2011 fsh
1 6 tor 20 Jon 2012 tpwedcan.sh
mand also outputs hidden files and directories. 1 8 es 7 Mat 2612 Lnmount
The Is command also supports colors but usually lp oa 15 Dez 2011 Lnmunount
2m 8 25 Feb 2016 Ww
only color highlighting for directories and links. The al- maw 1 8 21 Aug 16:00 make-arttkel
Mewxr-xex 8 29 Jon 2013 maxdone-desktop
ternative exa, which is written in Rust, offers signifi- liamr-xrx@
sn 1
4
3
+ 25 Feb
1515 MatMat
14:23
2014
pishrink-sh
pna2pg
cantly more convenience. Many distributions offer exa ws 1 8
15 Mat
2014.
2614
png2pq-400
pg? pa-768
in their package sources: Ubuntu and openSUSE do, 1 8
1 8 15 Mat 2014 pnazipo-
and you will also find exa in the Arch User Repository 1 8 1 Mar 2013 qreodegenerator
1 8 sr 20 Apr 2012 rainbow
(AUR). If your distro doesn’t provide a package, check 1 6 Feb 11:37 ef
out the project homepage, where the developer pro-
vides a zipped binary for 64-bit systems, which you
can simply copy as exa to /usr/local/bin/ or »/bin/.
The output of the exa command roughly corresponds to re
9:59:28 LOTT =§ exa “TL --Level=?
38 Nov 19:35
the output of Is, except that exa adds more colors to the ne 1G 1 13 Mar 20:31 | 1gbyte.bin
overview (see Figure 7). For example, it highlights ar- Wr--r--@ 17k 31 Mar 2016 |— Alle Daten_private.pem
lweronr-@ 37k 9 Aug 18:40 [—
chives in red, images in light purple, videos in dark pur- * 8,2 (0) 1B Mat 2015 a
ple, backup copies in gray, and directories in light blue. war xe
“x 11 Mar 2016 }—
nimar 2016 |
Android
— sak
exa gets even more interesting when you enable further wx =x 15 Hat _2014 | Arbettstuache
ba exr—xr-x 21 Okt 22:48 |= Artikel
options (see Table 1). For example, with exa -bghilS, exa war ox 11 Sep 17:12 logtnabox
displays the file permissions, including file sizes, affilia- bs wxoxr ox 21 Okt 22:49 eters
wx =x 12 sep 15:47 | | countdown
tions, and the last modification data, in a neatly sorted list. bs wxr-xrox 8 Sep 14:59 eydock
bi war-xr=x 8 Sep 12:38 | [- Lightpack
Other colors help you keep track of things such as bs wx oxox
wwarx
18 Sep 16:12
17 Feb 2016 |—
plxtend
Autnahoen
file permissions. If you decide on a version of the com- |. w-'--r=-@ 49% | 10 Mat 12:34 | auto Backup 26170510 0954-201705100954.pr
mand you like best, create an alias for it wit lw. uk 7 Jan 2:36 | bewerbung. tex
war -xrox 30 Nov 13:36 | Bttder
owt 2016 |
alias 11="exa -bghHIS' 29 bez 2015

and place the alias in the ~/.bashre file. The above alias exa's ability to display entire folder structures recursively
would let you call the command by simply typing 11. in a tree view is also practical. To display a tree, supple-
ment the call with exa --tree or exa -T.
Table 1: Important exa Options You can limit the tree depth with the
Bic ee ues Cees --level=<n> option, where <n> is the
Dioceses number of levels you want to display.
1 oneline ‘Shows each file and folder in a new line Alternatively, switch off the tree view
4 ~long and let exalist just the subfolders with
Displays metadata, such as file permissions
and size the -R or --recurse switch. Again, you
R ~recurse Lists the contents of subdirectories recursively can restrict the depth with the ~-level
(depth option: level=<level_number>) option (Figure 8).
T ~tree Displays a tree structure (depth option: The shortcuts for sorting the output
~level=<level_number>) also make everyday life in the shell
--color=<when> Color output is never, always, or automatic easier. For example,to find the largest
~color-scale Highlights the display of the file size in color files in a folder quickly, call exa like this:
for large files
ieee exa -Ir ~-sort=size
a ~all Shows hidden files and folders
-d ~list-dirs Treats directories like files The -r switch reverses the order of
+ reverse Reverses the sort order the output so that the largest files.
are at the beginning of the list.
-s<option> ~sort=<option> Sorts by name, size, created, newest, or oldest,
By Christoph Langner
among other options
~group-directories-first Lists directories before files https:/the.exa.website/

62 101 LINUX HACKS


- 2021 EDITION
ASCII Browsing with Browsh
Despite the World Wide Web demanding more and
more of our systems, many of us just want a simple
browsing experience that neither detracts from the in-
formation we want nor diverts system resources. For
elated, but it’s also clear enough
to be navigable (Figure 9). Vi-
a)
tally, the text is still raw text, which means that reading a
page of content on the terminal is often clearer than
this reason, a web browser running in a terminal win- reading the same content on a design-heavy site.
dow is very attractive. Ideally, it would focus on the text Instead of packages, Browsh is a downloadable static
and ignore both the images and wider site design, let- 64-bit binary that runs on all Linux versions. Tip: Press
ting you read and download only the parts that matter. Ctrl+Qto leave the program.
This would be brilliant if you're also on a low-bandwidth
connection or connecting via SSH to a headless low- By Graham Morrison
powered server such as a Raspberry Pi. But the absolute httpsi/www..brow.sh/
minimalism of console browsers like Links,
Lynx, ELinks, and w3m is often too much Figure 9
for a modern site, both in the way their lim-
ited rendering makes a complex site diffi
cult to navigate, and in their compatibility
with modern web technologies like HTMLS,
CSS3, JavaScript, video, and even WebGL.
It’s these problems that Browsh attempts
to solve, albeit in an unconventional way.
The unconventional way is that while it
does run from the command line, it still re-
quires you to have Firefox 57 or later in-
stalled. This is because Browsh uses Firefox
to render the pages you request before ren-
dering them as ASCII for use within your
terminal. It may sound like a cheat, but it
works perfectly and means that Browsh is
compatible with every site that's compati-
ble with Firefox — a huge advantage! The
rendering is obviously blocky and pi

Pera

Keep your finger on the


eT -Mel mm LeU

Too busy to wade through press releases and chatty tech news sites?
Let us deliver the most relevant news, technical articles, and tool tips — straight to
your Inbox.

Admin and HPC: https://bit.ly/HPC-ADMIN-Update


Linux Update: _https://bit.ly/Linux-Update
Command References at cheat.sh
love using the command line. It's where | spend scriptions. You can even list the cheat
most of my time, and I'll go out of my way to find a sheets that may be available for your favor-
command-line solution, even when there's a poten- ite programming language. Typing:
tially easier-to-use desktop application that does
the same thing. But my memory is rubbish, and un- curl cht. sh/cpp/: list
less | use something every day, | soon forget com-
mands and shortcuts for doing things in the utili- for instance, lists 30 documents on C++, from arrays
ties and languages | don’t use that often. What | to logical and bitwise operators. If you don’t like this
need is universal access to a cheat sheet system remote curl approach, you can easily download a
that enables me to quickly see the most commonly command-line client, cht. sh. You can then run that
used command shortcuts and arguments for the client locally to access the same information, and
tools | want to use. you can even integrate the search and results into
cheat. sh is that tool (Figure 10), developed to hit editors like Vim and Emacs, which is perfect for peo-
seven noble targets: ple like me who can never even remember a simple
for loop’s syntax or have the Vim commands from
It’s concise, only containing the details you want. within Vim itself!
It's fast, delivering results on the command line
almost instantly. By Graham Morrison
WN

It's comprehensive, with access to plenty of tools https:/github.com/chubin/cheat.sh


and information.
It’s universal, avail- Figure 10
able everywhere.
NOOR

It's unobtrusive when


you're working.
Ithelps you learn. ra

It is inconspicuous.
cheat.sh is a GitHub repos-
itory that delivers on all of
these promises by allow-
ing you to grab pre-pre-
pared text documents
that ee
help you to work with the
tools you commonly use. eI eas ayCas csc)
Type: c al Met atc se}
BUmers:
hen curling)
curl https: //cheat.sh/ssh
cee aeiets ee uN usec
for example, and you'll
seeSSHquick examples ofthe
command complete
Ease Ea
i)
with single-sentence
de- [is tos
Re Cresco rt instant

Tyrer)

64 101 LINUX HACKS


- 2021 EDITION
HACK 6 1
Highlighting Instead of Grepping Save it as /usr/local /bin/hl and make it executable
(chmod ax /usr/local/bin/hl). For both actions, you will
The grep command can highlight the parts of output need root privileges.
lines that match your search expression. To make that You can only use the new tool as a filter, unlike grep,
happen, you only need to provide the --color option. In which also accepts filename arguments. So replacing:
fact, some Linux distributions set up an alias:
sonetool | grep keyword
alias grep='grep --color=auto’
with:
(and further ones to upgrade egrep and fgrep to colored
output, too). Seeing the search term emphasized in the sometool | hi keyword
output is so useful that it started to bother me that the sim-
ple cat tool cannot highlight expressions. So | searched for is fine, but if you want to output a file and highlight a
atool that combines cat and grep --color: It should output keyword, either create a “useless use of cat” expres-
alllines but highlight a given keyword. Figure 11 shows a sion, such as:
terminal running dnesg -u continuously and highlighting all
occurrences of usb or eth?, ignoring case. cat filename | hl keyword
Figure 11
or redirect standard input via the < opera-
| tor (hl keyword < filename).
NIC Linkinesync,1S UpvgeveTinesyneworker?
1000 vps Futl Duplex,RadtcatFlow C Rs REchange: 19 Since hi simply forwards all options to
ins Guesttast=! 580 268698 188 851 s Tne’
eetTinetestuoopetrve.) grep, you can use advanced features such
nk ts Down
as searching for regular expressions or
contrat
contrat USDStopping alt guest,
guest ttles
processes asking the tool to ignore case. Highlighting
Closing
few fulleapeed deviceattnusber 5 Using’ dhel-p USB and network events took a simple:
Newodet:Ust device strings! frat
Use
Manufacturer:
n't set contig Virtualtox
ai. error -32 dnesg -u | hl -iuE “usb/eth.”
1agb4 tinesyne VveT eesyneworuers Rad\cal nse ine change: 318 271 775,
nesyne.GuestLastet
vgaveT neSynciorker?
356 385.901 Rasteat.
646 382°9Qu os sett
ange: 338 283 68 |
where -i asks grep (and thus hl) to ignore
lower/uppercase differences, -u restricts
matches to full words (so that ethé will
Performing this task boils down to inspecting every match, but ethernet will not), -E enables extended regular
single line, attempting to grep the search term in it expressions, and the “usb eth." defines that we're looking
(with coloring) — and, in case of failure, echoing it. Put for either usb or eth? (with exactly one character after eth).
the following code lines in a Bash script: If you want to build a (very) simple syntax highlighter
fora programming language, just provide hi with a list
#!/Din/bash of all reserved keywords. In Figure 12, you can see parts
uhile read -r; do of the output of:
Vine="SREPLY"
(echo "“sline" | grep --color $@ ) || echo "s1ine" hl -uE "for |do|done|exit |case|esacluhilelififilelse
done leliflecholexport
|alias| Funct ion|test|unset” < /ete/?
bash. bashre
Figure 12
Actually, it doesn’t take a script like hl at
all, if you can live with the restriction that
every search term must be a regular ex-
pression. In that case, grep can already
do the job on its own. Just add *| before
your search patterns, for example:
daesg -w | grep --color -iue “*Jusbleth.”
Every line is matched by *, so grep discards
Peer nothing, but coloring only happens to
Cro tas
lines with “proper” search results.

By Hans-Georg EBer

101 LINUX HACKS - 2021 EDITION 65


SHELL HACKS

Add File Type Icons to Your File Listing


The first time in our lives we got to a black-and-white sembles that in Figure 14 — note the cute icons and
Linux or Unix shell, most of us probably typed Is first. A bright colors. Light-shy workers can choose a variant
new implementation of this standard tool adds icons to optimized for dark terminals by specifying --dark. Figure
the output. colors is written in Ruby. If you don’t have 15 shows what a tree view (with --tree) looks like.
this language on your system yet, install it quickly. For
example, Ubuntu and Mint users would type: No Blind Faith in Color
Speaking of the downside: colors is a new implementa-
sudo apt install ruby ruby-dev ruby-colorize tion of Is, which does not support all options identically
and some not at all. My big favorites, -1 and --sort=size,
or, for openSUSE: fortunately work. If you type -f, colorls only displays
files; -d only displays directories. If | want to see both, |
sudo zypper in -t pattern devel_¢_C++ devel_basis have the choice between --sd (directories first - note the
sudo zypper in ruby ruby-devel two dashes!) and --sf (files first).
If you would like a brightly colored Is but have prob-
Then you download a TrueType font that you like from lems with coloris because of missing parameters,
Nerd Fonts - say, Roboto Mono Nerd Font Regular. After schedule a test run with exa (see Hack 58).
unpacking the ZIP file, | moved the . ttf files to the /usr/
share/fonts/truetype/roboto/ directory on my Ubuntu By Charly Kihnast
desktop; users of other distributions may need to httpsi/github.com/athityakumar/colorls
change this path or use a graphical font installer such as httpsi/inerdfonts.com/
KDE's kfont inst. Close and restart your terminal pro- Figure 14
gramafter the font installation.
Why do | even get this font when there are a few |cherdyefunghs:~/dump1e9e8 coloris ~-Light ~-sd
dozen others preinstalled? Because Nerd Font's char- '® pthreads/
& relsar/
public ntml/
& tesefiies/
acter sets are more extensive, containing more sym- & tools/ @ anet.c
Benet. anet.o
Figure 13 BB coasia00.003
B cunpte9e
coaa.h
‘ump1090.<
Bump 1090. 409 ‘dump 1898. dsw
> i} B dunp1290.n
mp1898. 3h
‘dunp1¢90.0
ddump1696-win.1.69.0608.14.21
pee ee ae eee) nteractive.c anteractive.o
Cott roe Cro (e75a) akedump1 690 Makefile
‘akeppupte90 akeview1090
(or) @ mode-ac.c fmode_ac.0
@ mode-s-c ode_s.0
@ net_io-e net_io.0
© ppup1090.c Bi ppupi090.n
q Et we © ppuptese.sh
& 000
README nd
B vieno90
nee eee) as emer @ view090.c view1898.asp
irom (ers) visualstudio (e76c) ‘vaew1990.h B viei990-0
(e721) (erm) B winstups.n
chor lyefungha :~/dunp10908

bols, special characters, glyphs, and emojis than Figure 15


usual (Figure 13). Now| select the new font in my ter- ee ash wane
minal's preferences. This fulfills the preconditions, BDB Screenshot
resetter2.pngfrom 2019-84-24 11-37-09.png
and | can proceed to install color!s by typing:
&BS Screenshot
stocert-png from 2019-04-26 16-54-37. png
sudo gem instal! coloris BBD stacer2 png
xscreensaver-contig.png
© Public?
Ubuntu and Mint users can at once use color's. If you & sre/
& gnome-she11-mousewhee]-z00n/
run openSUSE, the tool's file name is coloris.ruby2.5. A com. tobiasquinn.mousewheelzoom.gschema xml
The developers know that nobody types colors 50 & debian/
B changelog
times a day. | recommend that you create an Ic alias in
your */.bashre:
‘gnome-shell-nousewheel-zoom.install
alias lc='colorls' # or colorls.ruby2.5 hideonzoom.py
Eo PPrOrrer

makefile
mousenheelz0on
If you use a light terminal background, you should al- mousewheelzoom.desktop
ways specify --1 ight or, preferably, make it permanent ‘mousenheelzoom.vala
PKGBUTLD
by appending itto the .bashre alias. The output then re- PKGBUILD. from.git
README md

66 101 LINUX HACKS


- 2021 EDITION
cere Le)
Linux distribut
ee

et

h Shell HACK 64 .....: a


The default shell on Linux is Bash, but there are
some classical alternatives like Zsh or Csh. The fish :
shell is yet another shell, but it's different from allthe Sav aaseeuaieaD
others. Pe an A
Fish offers some very helpful command-line pat Mes aE aE Ee
completion features. For example, when you start FEE NeE oucEe Tre Ia at
typing a command, you get suggestions for old pee Z ie rs
commands from your history. The shell shows fates
how the letters you typed so far could be com- oa nie
pleted to form your old command, with the miss- FEMI
ing bits in light gray, so you know what's already
there and what's a suggestion. Press the Up arrow
key to go back to older history entries. mentation in a browser. Looking at the list of internal
Or press Tab to see which binaries in your $PATH start commands reveals interesting additions; for exam-
with the letters you entered so far. If there are many ple, the cdh (cd history) command shows all folders
possible completions, fish will only display a few of you've cé’ed to in the past and lets you pick one with
them —to get the full list, press Tab again. If you think _the cursor keys.
that Bash does that, too, that’s only half correct, be- There's a lot more to discover, and if you like to write
cause fish will add information from the program's shell scripts, fish has its own scripting language. Many
man pages (Figure 17) so that you can quickly check distributions have fish packages in their repositories~
whether you really want one of the commands from the _ for example, try sudo apt install fish for Ubuntu and
list. Autocompletion will also suggest options when Mint or sudo zypper in fish for openSUSE.
you press Tab after entering one or two minus signs.
Ask the fish shell for information about an internal By wens Genie EGer
command via help command, and it will open the docu- _httpsi/fishshell.com/

101 LINUX HACKS - 2021 EDITION 67


SHELL HACKS

Moh)
Using a Sub-Shell or modify variables that might influence the shells be-
havior. For example, deleting the PATH variable (via unset
When you're working in the shell and you type bash, PATH) renders the shell almost useless since it cannot
nothing happens — apparently. The shell prompt returns find binaries (unless you specify the full path).
at once, and you can continue
to enter commands. But You may also start a sub-shell if you want to “hide”
when you try to run a command from the history, you commands: The shell writes the command history from
will notice that it is somehow outdated (and especially memory to disk when it terminates. The commands saved
the bash command that you've just typed will not appear by the sub-shell will be lost when the parent shell exits.
in the history). Another reason fora sub-shell is staying in a directory
That's because you're no longer working in the shell with a long path that you don’t want to memorize: Just
that was active when you typed the bash command: start a sub-shell, cd out of the current directory to do
You have started a sub-shell in a child process, and the some other work, and when you want to return, simply
original shell has been suspended until you leave the exit the sub-shell with Ctrl+D. Of course, there's also the
newshell with exit. Running ps --forest will reveal the directory stack that was invented for exactly this pur-
parent-child pose- so if you know the pushd, popd, and dirs com-
Figure 18 relationship of mands, it is better to use those. If you don’t, a sub-shell
the two shells does the job, too.
esser@susei5ib:~> ps --forest (Figure 18). You can even temporarily suspend a sub-shell (using
PID TTY TIME CHO is the suspend command) so that you can use the parent
26263 pts/1 3:00:08 bash But what is
28015 pts/1 00:00:08 \_ ps that good for? shell; entering fg brings you back to the sub-shell.
bash
See ig in a
Working When you use a desktop environment, you're more
sub-shell is a likely to simply open more terminals instead of starting
good idea sub-shells. But if you often log into remote machines via
28032 pts/1 when you SSH, knowledge of sub-shells can come in handy.
esseresusei5ib:~> lf Wantroteee
i en shell options By Hans-Georg EGer

Start the Right App HACK 66


When I'm navigating through my folder hierarchy, | Gnome users type gio open filename. On older
tend to find files that | cannot remember creating — and Gnome versions and on Linux Mint’s Cinnamon desk-
the file name does not help either. | want to look at the top, you can try gvfs-open. Xfce has its own tool, too:
contents (and possibly decide to delete the file or move It is called exo-open. There's also a generic tool called
it elsewhere). xdg-open. You may have several *open tools installed;
If this sounds familiar, then how do you open such Figure 19 shows what happens when you run gio
files from the command line? You could launch the open and kde-open on the same text document. Nor-
right application from the desktop's program menu, mally, it’s best to stick with the tool tailored to your
use a command like echo $PHD/fi lenane to find the full favorite desktop.
path of the file, and paste that into the opening dialog.
Or, if you happen to knowthe file name for the program By Hans-Georg EBer
binary (like soffice for LibreOffice), you Figure 19
can type soffice filename.
In most cases, your desktop knows
which applications could open your files:
Double-clicking them in the file manager
will normally start some program. You
can use that knowledge in the terminal,
too. For example, as a KDE user you can
run the kde-open filename command to
have KDE's MIME type configuration sort
it out for you. Depending on your distri-
bution and KDE version, the tool may be
called kde-opens.

68 101 LINUX HACKS


- 2021 EDITION
MN) REAL SOLUTIONS
Soe REAL NETWORKS
ADMIN is your source
for technical solutions
to real-world problems.
Put an end to fake
certificates Improve your admin
1308 and Flatcar skills with practical
ain microdistributon
articles on:
‘Automated
Seep wn eas a:
f e Security
© Cloud computing
e DevOps
¢ HPC
e Storage and more!

with a digital : e
subscription! 6 issues per year!
ORDER NOW
shop.linuxnewmedia.com
PUB MRISHL.......
You run a website or you produce content for it: 7
The best hacks mean knowing the right tools. For 2
example, you don’t need to do a regular install of 2
a CMS for testing: Just run a Docker container and 2
get rid of it when you're done. 4

HACK 67
Seu EMO Eee?
Ne a i:9
items an cer en Ag

HACK 69
eC laura UR Me at Cis

Eee}
erent ( rte MASS
HACK 71
Ler MeN a CC)
LT Ne ara
Chase canes)

HACK 73
SCO COE SAM ULC
HACK 74
De ae Olea ee

70 101 LINUX HACKS


- 2021 EDITION
PUBLISH OR PERISH ~~

Install the draw.io Diagram Editor Locally


Draw.io has been around for years as a website. If you generate diagrams of this quality so quickly, and
ever need to draw a diagram or flow chart, or even a none with the same powerful design and symbol library
circuit, it's indispensable. Many users now rely on it for that can output in so many different formats.
their last-minute presentations, their documentation Diagrams aren't necessarily the most exciting thing
projects, and project planning, because draw.io’s great to spend your time creating, which is precisely why
strength is that it offers many different symbols in draw.io is so good. It handles the tedious parts, so you
many different categories, making it capable of draw- can spend less time drawing and more time moving on
ing many different kinds of charts. You don’t have to to the implementation (or at least arguing over the im-
create your own icons, steal images from the Internet, plementation shown in your awesome diagrams).
or rely on Inkscape for your arrowheads. Instead, you Figure 1 shows what draw.io offers:
simply drag and drop symbols, join them together, and Symbol library: Drag and drop from a huge variety
then use draw.io’s wonderful styling, arrangement, and of diagram icons.

ONOORPWHN=
node options to create a final file that you can save on- Connections: Components can be dragged, and
line or locally. The only downside is that the website their connections remain intact.
version requires running it online. Edit: Scale, drag, rotate, and group elements on
But draw.io is an open source project, and there's now a your canvas.
desktop version you can run on your local computer, Style: Use a color palette for fill styles, plus control
which is perfect for last-minute cramming on that train fonts and labels separately.
with abysmal connectivity. There's an executable App- Properties: If the mouse isn’t good enough, type in
Image, as well as DEB, RPM, and even Chrome OS files. exact values.
With the application installed, you can create diagrams Transparency: Make and mix your colors with opac-
without the online tether. There's a huge number of sym- ity values.
bols to choose from, with additional custom symbols em- Shape categories: Symbols cover a huge range of
bedded within many of the template New projects you diagram types.
can open. The Google Cloud Platform (GCP) templates, Custom libraries: Include your own symbols, such
for example, include many GCP-centric symbols and lay- as GCP or AWS shapes, to accompany your own
ers for use within your charts. Further examples include diagrams.
Venn diagrams, mind maps, Unified Modeling Language
(UML) diagrams, flow charts, and isometric network dia- By Graham Morrison
grams
— with 3D symbols for Amazon Web Services https:/diagrams.ney/
(AWS) infrastructure.
Although not as powerful Figure 1
as Inkscape for drawing, text,
or arrangement options, you
have more than enough tools
here to create the perfect dia-
gram, as well as group, layer,
and align, for instance. If you
need more control, you can
save as an SVG file and edit
within Inkscape. | tested this,
and it worked perfectly.
There's even beta support for
VSDX output if you need to
import your file into Micro-
soft's Visio. The UI still feels
web-based, and native desk-
top widgets would be prefer-
able, but this is an important
application with few desktop
rivals - I can’t think of any
Linux tools that are able to

101 LINUX HACKS - 2021 EDITION 71


PUBLIS

CValeig Record Screencasts w' Peek


Ascreencast shows what happens Debian, or Solus, the developer provides instructions
on the desktop. Peek lets you create for installation on the project page.
‘screencasts in the blink of an eye and What is currently causing Peek difficulties is the
export them to popular formats. Com- change to the new display server, Wayland. For secu-
pared with other screencast tools, Peek has a very rity reasons, Wayland isolates individual applications
small feature set, but the program is not trying to com- ‘on the desktop from each other. Software is not al-
pete with the more established applications. Originally, lowed to read the content of another program’s win-
it simply recorded the desktop as a GIF, thus producing dow. Thus, screenshots of the entire desktop are no
videos that were easy to embed into web pages. How- longer easily achievable. But that’s a problem for
ever, Peek now also supports more traditional video many other tools, too.
formats such as WebM and MP4. Unless you launch Gnome under the classic X server
In terms of the interface, Peek is deliberately oriented via the display manager using Gnome on Xorg, Peek
on the LICEcap screencast tool for Windows. The pro- needs to revert to the XWayland compatibility layer,
gram shows a scalable transparent window that is al- which happens automatically when you start Way-
ways in the foreground on top of all your other applica- land; however, if needed, you can call the application
tions. Everything inside the window frame is grabbed directly under XWayland with GOK_BACKEND=x11 peek.
as a video by the software when you click Record. After Note, however, that in our tests on Ubuntu 21.04
pressing Stop, Peek immediately saves the results on (Gnome) and openSUSE 15.3 (KDE), both in Wayland
the hard disk. mode, Peek produced completely black videos. The
To set the output format, click on the Peek icon in the mouse movements were visible, but nothing else.
upper left corner and choose Preferences. Adjust addi- Your mileage may vary. The default solution to this
tional parameters, if necessary, such as the Delay in problem is, of course, to log into a normal X session.
seconds before the recording starts and the Frame rate,
or influence the size of the recording with Resolution
downsampling. https:/github.com/phw/peek
For the GIF format, especially, you should keep in http:/www.cockos.com/licecap
mind that it was not designed for
recording: Capturing the entire Figure 2
desktop in Full HD at 30fps will
result in huge files. Therefore,
choose only the snippet that you
actually want to view later. When
scaling the window, the size dis-
play can help you align the frame
precisely (Figure 2). Additionally,
you can reduce the frame rate to
about 10fps, and, if necessary,
use the Resolution down-
sampling option to scale the re-
cording by an integer factor.
Installation
For Ubuntu and Linux Mint, the
default repositories have Peek
packages that you can get via
sudo apt install peek. On Arch
Linux, you can install the applica-
tion from the Arch User Reposi-
tory (AUR), and if you use open-
SUSE, you can run the sudo zyp-
per in Peek command. For other
distributions, such as Fedora,

72 101 LINUX HACKS


- 2021 EDITION
aC 6
Edit Your Videos with VidCutter
Creating Long
If you create lots of videos, such as screencasts of
your desktop (see hack 68 featuring Peek), you often Documents with Styles
need to cut bits out of them. That's an essential part Some documents that | create in LibreOffice Writer
of both the recording and editing process. Editing is are “throw-away” documents: | type a few lines, add
obviously the central process in all video editors, but some quick formatting, print the document, and then
often all you want is the video equivalent of selecting save the file or just close the program and discard it
a piece of text and pressing delete. all. That's the one case where it doesn’t make sense
VidCutter aims to do just that: make practical edits to work with styles.
quick and easy. The Ul is refreshingly simple. Most But most documents are different: You create them
videos load without conversion, thanks to the libmpv one day, and weeks, months, or years later you edit
back end, and you can immediately start playing with them again or create a copy to which you add new
the edits. The basic process mimics that of fully text. The longer those documents become and the
fledged editors while restricting options to a mini- more they are structured (into chapters, sections,
mum. You go through a file creating clips by selecting etc.), the more it becomes vital to format them with
the start point and end point of each clip. The mouse proper styles. For example, automatic generation of
wheel or Left/Right cursor keys can be used to step a a table of contents is only possible when you've as-
single frame forward or backward, which is excellent, signed a headline style to every headline.
while Up and Down keys will skip five seconds. The Using styles also guarantees that you can keep a
Return key can be used to quickly create a start or uniform look throughout the whole document:
end marker for a clip, and a thumbnail of each clip ap- Headlines on page two will look the same as those
pears on the right after being defined. on page 102~ same font, same size, same color (if
You can reorder the clips by dragging and dropping that’s something you do to your headlines). Also,
them within the panel, and when you've finished mak- exporting the document into a format that can be
ing clips and dragging them into a sequence, clicking used for web publishing is much easier when you
Save will output the final version (Figure 3). On Ubun- stick to using styles.
tu, try the AppImage; the Snap package was broken. Figure 4 shows two headlines in a document - but
only the second one is a real headline. When you
By Graham Morrison modify the headline style settings, only the real one
https:/{github.com/ozmartian/videutter will show the changes, while the faulty first headline
will remain unchanged.
Figure 3
By Hans-Georg EGer

Figure 4

This looks like a headline

This is a headline

101 LINUX HACKS - 2021 EDITION 73


PUBLISH OR PERISH

Edi ing HTML with Live Preview in Brackets


Brackets is an open source text editor targeted at web stopped development and will end support in September
design. There's obviously a Linux version, but the part 2021. The final Linux release (1.14.1) dates back to 2019
that makes Brackets unusual is that it's been developed and works well on Ubuntu when installed as a Snap
by Adobe, and they worked on it from 2014 to 2020. package (sudo snap install --classic brackets).
Even though the code is now orphaned, it's worth trying Figure 5 highlights some important features of
out because Brackets is rather brilliant. The first thing Brackets:
you notice when you launch the application is that it 1 Live preview: Changes made to the raw text
looks nothing like a typical Adobe application. It actually source of a site update the preview.
looks good, and its user interface doesn’t impinge on us- Multiple files: Tab between open files or create
ability, with a large text pane holding the editor itself, both vertical and horizontal split:
complete with beautifully rendered text using whichever Code highlighting: Text looks crisp and easy on
F WN
font you prefer. Start typing into an HTML document, the eye, and HTML colors are previewed in small
and the autocomplete helps you start and finish ele- ow ‘swatches.
ments, fixes indentation, and subtly highlights the tags Distraction free: A simple mode can be enabled to
from the text. This helpful functionality extends to col- remove all the window furniture so you can focus
ors, where you add the hex value for a specific hue and on the code.
the editor will show you the color you've selected. Extensions: Augment your editing environment with
But its smartest feature is the live preview. Selecting dozens of easily installed plugins and extensions.
this will open a Chrome browser window containing Code completion: Use the drop-down menu to
the rendered output of the HTML and CSS files you are help with element memory.
editing. The clever part is that as you edit the source Multiple languages: Designed for the web, but you
text files, the live preview updates instantly to reflect can use Brackets with many different languages.
Refactor and linting: Change names easily, and
aN

those changes. It feels like the developer modes you


find in popular web browsers, where you can tempo- check and even fix common errors automatically.
rarily change how a page is rendered, but the differ-
ence here is that your changes are saved to the files By Graham Morrison
used to build your eventual site. Thanks to its age and http:/fbrackets.io/
provenance, there are also dozens of add-ons that can https:/github.com/adobe/brackets/
be installed, allowing you to
add themes, watch videos, Figure 5
make notes, and even turn
the editor into a fully fledged oe
IDE. While the emphasis is
obviously on CSS and HTML, SL oe
Brackets also supports a huge
variety of formats and pro-
gramming languages, from
Bash to YAML, where you can
take advantage of its excellent
font rendering, refactoring,
and split panes. It’s a clean
and effective editor. Although
it cannot replace something
like Dreamweaver when it
comes to designing a website
without touching the source,
it’s perfectly suited to the mod-
ern role of web developer.
Brackets is available under
an MIT license, and it runs on
Linux, Windows, and macOS.
But note that Adobe has

74 101 LINUX HACKS - 2021 EDITION


PUBLISH OR PERISH

Create E-Books with Sigil


Online book sellers and the self-pub- and all kinds of tools to help you carve your raw words
lishing revolution have changed the into something that will work on a Kindle.
publishing landscape for book authors. The editor has a tabbed view for open files and in-
No longer are the keys to the printing press cludes toolbars for all the common markup, along with a
held bythe few, and success is no longer limited to clips pane that lists the most common elements. It oper-
those with a publishing agent and book deal. In the 21st ates very much like an old-fashioned HTML editor, which
century, anyone can publish anything. There are obvi- isn’t a bad way
to think about the ePub publishing for-
ous negatives, too; there’s a lot of rubbish out there, mat- simple HTML and a handful of stylesheets. You
and the ratio between poverty and success is similar to can create an index, manage the table of contents, edit
that of winning the lottery. But it is possible, and suc- the stylesheets, and validate the syntax. You can then
cess can be measured in many different ways. generate an ePub from your work and save this as a
There are a few things you need if you're going to checkpoint so you can compare it against further edits
publish your own book, apart from the talent, drive, and you might make. It can still be intimidating to use, but
commitment to write the thing in the first place. The first you can also learn from others by opening other EPUB
is a decent writing environment. This is a tough one be- files in Sigil to see how they're put together. Either way,
cause every writer is different. Some will write notes on Sigil covers all the technical aspects of putting an ebook
paper, while others will use Emacs Org mode. But either together and is the last step between your book only ex-
way, Linux is equipped with plenty of options. The only isting on your Linux machine and world domination.
potential omission is that there isn’t a writer's “IDE” that
can incorporate and organize your notes, pages, files,
jottings, outlines, characters, and the layers of minutiae https://sigil-ebook.com/
that typically come together to
form a book. A few years ago, Figure 6
there was a preview version 1, Tabbed view: Work on more than one chapter at once. 2. Formatting tools: Just
for Linux of the excellent, and like an old-school HTML editor, Sigil gives quick access to every indent and align-
proprietary, Scrivener, a tool ment element. 3. Spelicheck: Keep checking your spelling, because errors will con-
that encompasses everything tinue to creep through. 4. Plugins: Use Python to filter and process your own text
from note collation and orga- files. 5. Preview: An integrated ebook reader lets you see what your book will look
nization through to ebook like. 6. Table of contents: Add pages to the table of contents and preview what it's
publishing. But Scrivener’s de- going to look like. 7. Editor: Here's where you tweak your XHTML to look good.
velopers have seemingly 8. Clips: Quickly access common elements to add and view within your book.
abandoned the Linux version organizer: Sigil isa little like an IDE for all the files that go into an ebook.
in favor of its macOS and Win-
dows users, leaving us with-
out a decent ebook generator.
This is where Sigil can help.
Sigil is not an all-encompass-
ing book-writing tool like Scriv-
ener, but it does give you
hands-on access to the tools
and protocols that will turn
your already written words into
an ebook you can publish and
sell. The amazing calibre ebook
manager can do this too, but
calibre does little more than
compile a collection of files
intoa single file. Sigil, on the
other hand, offers an XHTML
editor for the content, Python
plugins for your own macros,
the ubiquitous output preview,

101 LINUX HACKS - 2021 EDITION


"PUBLISH OR PERISH

Test Alternative docker-conpose -f stack.ynl up


HACK VS CMSs with Docker you get two images (one with Apache and WordPress,
Docker is the tool for what experts call container vir- the other with a MySQL database) and a working sys-
tualization. While the technical details are interest- tem — just login via http:/localhost:8080, choose a user-
ing, what's more important is that you can download name/password combination, and you're ready to use
and run working instances of complex software pack- the fresh WordPress (Figure 7).
ages in seconds.
This makes Docker interesting for all sorts of appli- By Hans-Georg EGer
cations, and it is especially helpful for website owners https:/ww.docker.com/
who think about switching to a different content man- https:/hub.docker.com/_/wordpress
agement system (CMS). If that’s you, you're likely to
read about the alternatives, but nothing helps you Figure 7
more with the decision than actually running the sys-
tems. Now setting up a CMS plus all the database ta-
bles, new virtual host, and more takes time. Once you
decide to remove it again, it is likely that bits and
pieces will remain and waste space on your server.
Instead, use Dockerto install a test system on your
computerat home: Just visit the Docker Hub and
search for “content management.” The first hits give
you official Docker images of WordPress, Maven,
Joomla, Drupal, Plone, and Nuxeo. For example, when
you write 20 lines into a docker-compose file stack. yal as
described on Docker's WordPress page and run

How Fast Is Your Server?


httpstat is a special stopwatch you can use to discover https: // for web pages se-
how long web servers take to serve a page: Visible cured with TLS.
performance lags indicate optimization potential. The Figure 8 shows httpstat measuring an
Python script wraps itself around cur!. Apart from Py- unencrypted call. Four milliseconds for a DNS reply
thon 2 or 3 and curl, it has no other dependencies. You is a really good value, but | cheated: The name is in my
can retrieve it from the GitHub repository and call it local cache. As soon as my computer has to turn to my
using python httpstat.py <URL>. If the Python installer provider's DNS, the value rises to 80-200ms. The TCP.
pip is present on your system, you can use that to in- handshake is 22ms, which is about par for the course.
stall nttpstat and call it directly by its name. While you The time the server needs to create the page (Server
can leave http:// out of the URL, you must specify Processing) shows whether it has some tuning poten-
tial that | have not tapped. My example is not represen-
Figure 8 tative, because instead of HTML the server simply out-
puts 301 Moved Permanently, which means | should
icharlygfunghi:=$ httpstat http://sensorenhein.de have called the page using HTTPS.
lconne ted to 372170.191.252:00 frow 10 45296 When requesting the same page using HTTPS, the
lookup and TCP values remain the same, but the
TLS Handshake takes forever for this static page.
The value can go up to several seconds for a big site
Leap emp Toedgt with a large volume of dynamic content and adver-
tising banners.
By Charly Kiihnast
https:/github.com/reorx/httpstat

76 101 LINUX HACKS - 2021 EDITION


2
2

.
DEF Here, we get technical. Reboot a non-responding system,
5 loop-mount zip and tar.gz archives, make files append-only
5 or fully immutable, and copy program binaries from one
5 distribution to another — but don’t forget to bring their
libraries, too.

HACK 75
Safely Powering Off Your Machine
Xe ari}
Make Files Immutable or Append-Only
HACK 77
Mount tar.gz and zip Archives
HACK 78
Liem Mla RU 9
and TestDisk
HACK 79
CEI ea ORS CC MP eed
HACK 80
EST MLC Cool ATUN Ng USCS
LNG Gi
Run Binaries from a Different Linux Installation
LN G74
ete Seu

101 LINUX HACKS - 2021 EDITION ihe


DEEP HACKS

HACK i) i) Safely Powering Off Your Machine


Turning off your Linux com- * 16-enable sync command
puter by cutting off the power is a bad idea: The system * 32-enable remount read-only
wants to shut down properly so that it terminates all run- * 128 ~allow reboot/poweroff
ning processes and unmounts the filesystems. If you sim- To check whether these values are set you can either
ply pull the plug, you risk losing data or corrupting the manually perform bitwise AND operations or use the
filesystem. Thanks to journaling, the repair procedure is shell. For example, the following commands check
quick, but you still should avoid a hard shut down. whether 32 is part of the sum - the result is either 0
However, sometimes a regular shutdown procedure or 32:
takes too long. If you need to leave a room very sud-
denly and take your machine with you, waiting that one $ a=$(cat /proc/sys/kernel/sysrq)
minute until shutdoun -h nou completes may not be an $ echo $((a832))
option. Maybe you have already heard of the magic 32
SysRq key it can help you.
If enabled, Linux responds to key combinations that Ubuntu sets the value to 176 which is 16+32+128 and
begin with pressing Alt+SysRq. (The SysRq key might precisely what you need to safely reboot the system.
be called PrintScreen on your keyboard or have both If you need to change the value, either echo it into /
names. On a keyboard with a standard layout, you will proc/sys/kernel /sysrq or use the sysctl tool (Figure 2).
find it next to F12, see Figure 1.) Keep Alt (or both In both cases, you will need root privileges.
keys) pressed, and then press a command key to make There are more magic SysRq features besides pre-
the kernel perform some action. How should you use paring and performing the reboot, but most of them
it? Just remember the following sequenc are rarely needed. Check the official kernel documen-
* Sync (S)- write buffered data to open files tation (see link below) for a full description.
+ Unmount (U) - remount filesystems in read-only
mode By Hans-Georg EGer
* Boot (B) ~ force reboot https:/www.kernel.org/doc/htmI/latest/admin-guide/sysrq.htm|
Thus, press Alt+SysRq+S, Alt+SysRq+U, and
Alt+SysRq+B for fast and safe rebooting.
Will It Work? Figure2
Check the contents of /proc/sys/kernel/sysrq— if it's 6,
then the magic key combinations are turned off com-
pletely, and pressing Alt+SysRq will have no effect at
all. If the answer is 1, all hotkeys are enabled.
Itis more likely that specific functions are enabled and
others are not: In that case, the result will be a sum of
some powers of 2 (namely, 2, 4, 8, 16, 32, 64, 128, and
256). Comments in Ubuntu’s /etc/sysct.d/18-
tmagic-sysrq. conf file explain what each number means;
for this hack, we only show three lines:
Figure 1

78 101 LINUX HACKS


- 2021 EDITION
DEEP HACKS

Make Files Immutable


mA
or Append-Only
If you have some files that you want to stay on the
Mount tar.gz and
disk, no matter what erroneous commands you zip Archives
might issue, make them immutable: All it takes is the | often find that a file | search for has been tucked
chattr tool, which changes file attributes. away in some .zip, .targz, or similar archive file. Con-
The normal way to protect a file is to make it read- sequently, a typical sequence before accessing the
only (i.e., remove its “writable” bits for all users). In needed file would be the following:
the terminal, chmod a-w file does this job. But some * tar tzf file. tar.gz (to check whether unpacking
programs override the read-only flag. For example, will dump everything in the current folder or — as is
the Vim editor will perform the following steps when proper —in a subdirectory)
you use the u! command with a read-only file: kdir tmp; cd tap (to avoid the dump action)
‘1 Rename file to file». tar xzf .../file. tar.gz (to actually unpack the archive)
2 Create an empty new file and write the memory Access the file
contents to it. * cd out of the temporary folder and remove it
3 Set access rights to 0444 (read-only). However, this is not the best way. A tool called ar~
4 Close it. chivenount improves the situation by allowing you to
5 Delete the renamed read-only file. loop-mount archive files (like you would loop-mount
Renaming and deleting do not require changing the an ISO image). Mounting does not require root privi-
access rights, which are still set to read-only! To leges. As archivenount is not a standard tool, you'll
make a long story short, sometimes Linux (tools) have to install it. For openSUSE or Ubuntu/Mint, the
will delete files even though you think you've pro- Zypper in archivenount or apt install archivemount
tected them. commands will do that.
Now mounting an archive is as simple as
Please Don’t Delete Me
There is a solution, namely, the “immutable” attri- archivenount file.tar.gz ant/
bute. Set it via:
sudo chattr +i file where nnt/ is some path that must exist. Figure 4
shows how this simplifies access; for the screenshot,
The command requires root privileges even when Ichose a .zip archive.
you make this change to your own file. From now on, For unmounting, use fusermount -u ant/. The man
whatever you try to do to the file will fail; you cannot page suggests using the regular unount command in-
even move it to a different folder (Figure 3). You can stead. While that is not wrong, it is not helpful, either, as
later get rid of the attribute via sudo chattr -i file. unount requires root privileges and fusersount does not.
If the file you want to protect is a logfile, there’s an While the tool is helpful, here's a warning: In my
even better change you can make. Set the “append- test with version 0.8.7 (which is what you get on
only” attribute via: openSUSE and Ubuntu), changes in the mount folder
sudo chattr +a file
of a .zip file led to creation of a new version of the
.Zip file — but in . tar format, despite naming it .zip!
Then programs with otherwise sufficient write access
can still append new log entries to the file, but it can- By Hans-Georg EGer
not be modified in the middle, shortened, or deleted. https://mw.cybernoia.de/software/archivemount.htm|
To find out whether a file has some of the attributes
that you can set with chattr, use the Isattr command. Figure 4
By Hans-Georg EGer

Figure 3
26 18:38 hacnoas=nistory/mtaeria
3 ites
arentvenount
seer nack808.249 mnt

© S01 20 $162
3826 Apr
Apr 2626 18:40
18:39 nackaee-ntstory.nac.txt
hackeeg.ntstory txt
91829
24187 hor
Apr 2626 18:38
16:36 §
Shett igure
Cont Hacks Your shell History
sseresuselsibi=>
101 LINUX HACKS - 2021 EDITION
DEEP HACKS

Recover Deleted les with PhotoRec and TestDisk


Undeleting files - that is, undoing a remove (rm) or un- a trade-off against the “undo-
link command ~is a very filesystem-specific task. Its ing” of valid transactions. A deleted
chances of success depend on the structure and fea- file is unlinked from the data metastructure
tures of the filesystem. We'll look at one of the most quickly, so it is quite difficult to find old entries once
simple filesystems first - FAT32 — which stores filesys- the filesystem tree is automatically optimized. Only
tem information in a simple table. The earliest FAT file- very recent changes, which are kept in the journal, can
systems were only able to handle file names with eight be replayed or reversed with special, filesystem-spe-
uppercase letters, and an additional three-letter exten- cific software. Unfortunately, any references to file
sion. This scheme is still used in the modern FAT, but it names and file metadata — like timestamps- disap-
also supports long filenames with fewer limitations. pear very quickly in modern filesystems after the file
‘An example disk contains just three files, with file- has been deleted, so you might still be able to recover
names lecturef{1,2,3}.pdf. After deleting lecture2.
pdf the file data, but you won't get back its name.
(with rm -f lecture2. pdf) and releasing the filesystem If you care more about the data of a single file than
with unount, thus writing back all changes, the raw view about retrieving the complete filesystem and directory
of the directory entries looks like Figure 5. structure, you can try PhotoRec instead of TestDisk to
The most obvious change is the replacement of the get your data back. PhotoRec scans raw data and finds
filename's first letter, L, by character hex OxE5. This is. file contents based on header signatures (Figure 6). In
how FAT first “hides” deleted files, before they are some cases, the file content also reveals the original
eventually overwritten by newly created files. In this file name, even if the file no longer appears in the file
stage, recovering the file is easily done by replacing system organizational structure, so you can get back
the OxES character with a letter (for example, back to the file with its (almost) original name. However, in
the original L). After doing this, the deleted file is back most cases, such as pictures or videos, the file name is
when the filesystem is mounted again. Recovery pro- no longer associated with the data after file removal, so
grams for DOS or Windows do exactly that. A good re- you have to search or guess from the recovered files’
covery tool for Linux is TestDisk: It knows about the sizes and block positions on disk, which are used by
specifics of file deletion and recovery for many filesys- PhotoRec to assign new names to files recovered and
tems. On Ubuntu, you get the program with sudo apt saved to a new partition or medium.
install testdisk; on openSUSE, run the sudo zypper in PhotoRec scans files regardless of which filesystem is
testdisk command. The testdisk command needs root used on the source partition, but it honors filesystem-
privileges. specific data links and file fragments if the filesystem is
Although recovering files in a FAT filesystem is com- known or specified in the initial configuration options.
parably easy, the file's data and metadata will only stay
intact as long as no new file claims the same directory By Klaus Knopper
entry or overwrites the file's data blocks. If this hap- httpsi/aw.cgsecurity.org/wiki/TestDisk
pens, the file and its contents are really gone for good. https://www.cgsecurity.org/wiki/PhotoRec
Native Linux filesystems, such as ext4 or Btrfs, use
more complex data structures than FAT; they support Figure 6
more file attributes and mechanisms like journaling
(which allows for quick repair of the filesystem in the
case of unfinished file operations or a crash before the
filesystem is unmounted properly) or “copy on write.”
The advantages of modern journaling filesystems are
Figure 5

asseessesssze3|
sesesesesyees3|

Srsasesascsasy|
Eussuusssuesss|
peesueesucrsy!
Susueesseesze
Stauseauszazsy

Seae
&*
Eta
6%
Sea
5

80 101 LINUX HACKS


- 2021 EDITION
DEEP HACKS

Change Root into Second Distro


uacx 7D
On my test machines, | tend to have several Linux dis- first responding with Ubuntu 21.04 and then, after chroot,
tributions installed on the same disk, with a GRUB with openSUSE Leap 15.3. In the window below, you can
menu that lets me decide which one | want to boot. also see the root directory property of the “chrooted”
However, | regularly find that the “wrong” distribution ‘shell and a normal shell. With a little effort it’s even possi-
is running — not the one that | need just then. ble to run graphical apps from the chrooted distribution.
Instead of rebooting, it is often enough to chroot
(change root) into the other distribution, which works By Hans-Georg EBer
as follows: Figure 7
* Mount the other distribution’s root partition (e.g.,
under /ant/dist)
cd /nnt/dist
mount -o bind /proc proc; mount -o bind /sys sys
mount -o bind /dev dev; mount -t devpts pts dev/pts
And if you need networking, also copy /ete/resoly. conf
to /ant/dist/ete/ (which for some distros requires de-
leting the file in the target folder first).
* Finally run chroot /mnt/dist bash -1 to starta login
shell in the other distribution.
The chroot tool starts the Bash shell with its root directory
property set to /ant/dist (whereas normal processes
have / as their root directory). Figure 7 shows Isb_release

Bind Mount a Directory with New Permissions


You may know the mount option --bind (or -o bind) that bindfs packages in the Ubuntu
lets you mount some directory to a second place in the 21.04 and openSUSE 15.3 repos.
filesystem hierarchy. We've also used it in the previous As a first example, the following
hack (which used chroot to jump into a different distri- will give you an alternative folder to ac-
bution). While classical bind mounts are often useful, cess your documents - but all set to read-only:
the feature is not very flexible and also requires root cd»
privileges. bindfs, which is a FUSE-based filesystem kdir ro_Documents
driver, lets you perform bind mounts in much more bindfs -r -p a-w --no-allou-other Documents ro_ocunents
flexible ways.
You can grab and unpack the source code and then The second example is even more useful: When you
run nake to build the binary, or - if you're lucky — install mounta /hone partition from an old Linux installation,
a package from the repositories. In my tests, there were user IDs likely don’t match your current settings, so you
Figure 8 cannot access the files without becoming root. bindfs
lets you switch UIDs:
{esserexpsi3:nJ9 c8 (rot/stst/nne/esseroocunents/ sudo bindfs --map=580/1001 /mnt/olddisk /ant/bindfs
(essereapsi3:Docunents}s Us =t
jars 13 Jun 15 12:19 hello. txt 500 is no valid UID This will create a new view in /ant/bindfs where UID
ts)5 cat hello. txt ‘on this system; 500 is globally replaced with UID 1001 (Figure 8). This
‘cannot access file
assumes that 500 was your UID on the old system and
1001 is your current UID.
By Hans-Georg EGer
(eidelisers 13 2 15 12:19 heto.txt_—_ binds creates a https:/bindfs.org/
t5)8 cat hello. bet new "view" with
modified access https:/github.com/libfuse/libfuse
rights

101 LINUX HACKS - 2021 EDITION 81


DEEP HACKS

Run Binaries from a \ Try to launch the program copy in the current di-
rectory and check the error message. In the exam-
Different Linux Installation ple, xv was missing the file 1 ibpngl6.so. 16. But it’s right
Software installation has become so simple with the ad- here: You copied it from the source system. So add that
vent of repositories and management tools like Apt, Zyp- (with its absolute path) to LO_PRELOAD by typing
per, Yum/DNF, and so on: Just pick a package you want LD_PRELOAD="$PHD/1ibpngié.so.
16" . /xv
and let the package manager figure out what other pack-
ages (dependencies) it needs and install all of it in one go. This might lead to another (new) error message com-
Sadly, not every application appears in every Linux plaining about some other file. For the xv example, the
distribution’s repositories. For example, the image next command was
viewer xv is one of my favorite tools, because it is incred-
LD_PRELOAD="$PHD/1ibpng.so.16 $PHD/1ibz.50. xv.
ibly fast. But it's also very old and has not seen any up-
dates since 1994. Its source code is available, but it has a and that finally started the tool (Figure 10). Note how the
habit of not compiling. Some distributors (for example file names have to be separated by a blank character, and
openSUSE) have managed to get it running and provide the whole argument is put inside double quotation marks.
packages in their repositories. Others, like Ubuntu, do For other programs, constructing the command line
not. So how about just copying the binary file from a might take longer, and there are going to be problems
openSUSE system to an Ubuntu installation? if you want to use this method to make a 32-bit binary
Well, that is likely to cause problems; in most cases, run ona 64-bit system. At least, those can normally be
attempting to run the binary will produce an error mes- solved by installing the 32-bit compatibility layer. The
sage that complains about missing libraries. In that other way (moving a 64-bit binary to a 32-bit machine)
case, don’t start searching for them on the target sys- is technically impossible.
tem. They are either missing, or they have been in-
stalled with the wrong version numbers. Or Use LD_LIBRARY_PATH?
Instead, go back to the source system, and search for If you're aware of the LD_LIBRARY_PATH variable in which
the library files there. You can use Idd to get a list by typ- you can add directories with libraries that the program
ing Idd /usr/bin/xv (for the xv example; Figure 9). Now loader will search before the default folders, you might be
quickly build a ZIP archive by supplying the program tempted to simply setit to the local directory that has all
and the whole output of Idd as the argument list for zip: the needed libraries in them: I tried that, too. Turns out, it
Zip xv.zip /usr/bin/xv $(1dd /usr/bin/xv) did not work with the example files, because the GNU C
Library was incompatible with the running kernel. But
This will generate many error messages, because there's you can start with that approach, too: Run the command
more than file names in the output, but it does not matter: LD_LIBRARY_PATH=SPHD . /xv
zip will happily put everything it recognizes as a file into
the new ZIP file. Copy that one over to the target machine. and then, step by step, delete all libraries that the
On the target machine, create a new folder for your loader complains about until those error messages
program, move the program binary itself into that stop and your program starts. Read the Id.so man page
folder, and unzip the file with if you want to find out more about how loading a pro-
unzip -j xv.zip gram works on Linux.
The -j option makes unzip lose the path information, so. By Hans-Georg EGer
it simply drops all files in the current directory. http:/wwrwctrilon.com/xv/
Now you're almost there: Start an incremental process
in which you add library files to the LO_PRELOAD variable. Figure 10
Figure 9

Sos16 oy{aefst)
[Most b jooprah.
s0.8 (Oaneae2 36 (Oxo00 BATT000)FTO)
Mego.)
Mow = (Lies /tib.so.t
s0's &a /Ubea/tbeso.6 (Que
(Sane eaTtdea00)
feu7foso08)
Ubeise.6 /Ubed/ttbe.s0.6 (Soe 0,1 ax(noe feto0e) 420%0)
© >usr
fose UbUeto?
(Aitea/ ibn (eens eat? 25000),
Moe/ lies 0,6 (00085706000)
Moree
Ublano soeso =>=>> fostfsr/Ue4/
tbe Baye s.3 U BICE,s0.6 (none 4aTea9000)
Jar LEAT Eg 202 (GrOETEEAI200) (Ord087IBaTec3F00)

Ubpthread.so.8 > /Lib64/LUbptiread, 50.6 (Ox08087F837e487880)


Serban

82 101 LINUX HACKS


- 2021 EDITION
DEEP HACKS

Don’t Be So Now the ciopfs driver follows these rules:


* Files that already exist in folder! and whose file
ACK oS Case-Sensitive names are all lowercase appear in folder2 with the
We all know the eternal Unix rule: File names are case- same spelling — other files are left out completely.
sensitive. That means, Makefile is not makefile. While it * Files that you create in folder2 — with whatever mix of
would be bad practice to have both in the same folder, upper/lowercase letters
— will show up in folder! in all
you could do it, and it has been done. lowercase (Figure 11).
When you leave the Linux world, the situation be-
comes complicated: Windows stores file names the Adjusting a Folder
way you typed them at file creation, and that’s the way So how can you convert a folder’s file names to all
you will see them in the file manager or in the shell — lowercase? If you don't, files with uppercase letters
but the system does not care what spelling you use for will not show up under the ciopfs mount point. Sev-
accessing them. This means that you can not have eral solutions have been discussed on Stack Overflow
akef ile and nakefi le in the same directory on an NTFS — the overall idea is to let find run a breadth-first
or FAT partition. Then again, Windows is not a Unix-like search over the directory tree with
system. But turn to macOS, which is partly based on find . -depth -exec mksmall {} \;
BSD, yet also ignores upper/lowercase differences in
file names - the old Unix rule is not valid for macOS. where nksmal is a shell script that will update the file
This is relevant to Linux users who use Wine to run name. Listing 1 shows an example implementation; it
Windows applications on their Linux machine. Some uses a collection of classic command-line tools:
Windows apps have problems with the Linux way of ex- * dirname extracts the directory part from a file's path
pecting the precise spelling of a file name and may break. * basenanie extracts the file name
If you've encountered this problem, then there is a solu- * tr exchanges one set of letters with another one, in
tion: ciopfs (which stands for case insensitive on purpose this case uppercase (A-Z) with lowercase letters (2-2)
file system), a FUSE filesystem driver. It allows you to * test compares two strings
perform an action similar to a bind-mount (see Hack 80), Ciopfs, like archi vemount and bindfs, is one of many
but with an important difference: When you try to access FUSE-based filesystems. The FUSE project page lists
files under the new mount point, case doesn’t matter. several more - maybe you'll find some other interest-
Ofcourse, you're not restricted to using ciopfs with a ing drivers (e.g., ClamFS, which integrates antivirus
Wine installation. If you're also a macOS user and often scanning).
switch between the two Unix-like environments, you By Hans-Georg EBer
may want to unify the experience and make Linux be-
have like macOS. http:/ww.brain-dump.org/projects/ciopts/
https:/wiki.winehq.org/Case_Insensitive_ Filenames
Installation https:/stackoverflow.com/questions/152514/
If you're running Ubuntu or Linux Mint, you can just https:/github.com/libfuse/libfuse/wiki/Filesystems
type sudo apt install ciopfs. | could not find any RPM
packages, and | tested source code compilation on an
openSUSE Leap 15.3 machine. If you have an open-
SUSE system, get the source archive from the project
website, unzip it, and run the following commands bin/bash
(which assume that you're still in the directory that FILE="$@"
holds the ZIP archive): DIR-S(dirname “SFILE")
BASE=S(basename "SFILE")
sudo zypper in make gcc fuse-devel glib2-devel 2 NEWBASE=S(echo | tr A-z a-z)
libattr-devel
cd ciopfs-0.4; make && sudo >
make install Figure 11
Type ciopfs ~-version to check
whether you've been successful.
Using the new tool is ex-
tremely simple: Just type ciopfs
folder1 folder2 where folder! is
the original directory that holds
files, and folder2 is an empty
directory that’s used as the
mount point.
folder # makes nothing new

101 LINUX HACKS - 2021 EDITION 83


WORKING
PJIAIA2jR7j3j0
FF

What's your favorite language? We can’t help you there, but


¢

we can suggest some editors to try. If your code eventually


oe 6

compiles to a binary, you might want to attack it with a hex


editor, a dynamic code analyzer, or perhaps a line count tool.
©
©
4

HACK 83 HACK 89
4 Run C Code from the Command Line Textadept Works in Graphics
c

ETM yea ites


Xe S29
desire aa AS HACK 90
HACK 85 Pea meu UENSeaT
1 aca LU COTTA) ecu
SNe @: 1) LXe el
Manage Your git Repository with GRV eo aan aa (ae
HACK 87 HACK 92
Make git Interactive era MU ue UC Lt)
HACK 88
Reece est nce

84 101 LINUX HACKS


- 2021 EDITION
WORKING WITH CODE ———

Save this file as ~/bin/runc and


Run C Code from the Command Line make it executable. (Use a dif-
Sometimes you want to use functionality that is famil- ferent filename if you use the
iar from C programming, but you cannot find a corre- opencontainers.org runc tool for
sponding too! that you could call from a shell script. For starting containers.) Also check that the C compiler
example, the getsid() and getpgid() functions (which gcc is installed.
return the running task’s session and process group You can now run C commands via runc. For example,
IDs) have no shell programming equivalent. in order to identify the session ID of process 1292, type:
Ofcourse, you could write a small C program that rune ‘printf (“xd\n", getsid(1292))"
calls the function of interest for you, but then you'd
have to include parameter evaluation. Abetter way is Figure 1 shows this (and a getpgid() call) in action for the
to use a simple wrapper script that takes a string ofC lic process with PID 26815. Of course, | could have asked
code, puts it into a C source code file, and then com- ps to show the information viaps -h -o sess -p 26815 (-h
piles and runs it. The following five lines do just that: equals no header, -o sess equals only the session ID col-
#1/bin/bash umn, and -p equals only the process with this PID) and
msg="$@"
via ps -h -o pgid -p 26815, but | knew neither the -h op-
fname=/tmp/_run_
tion nor the session ID column code by memory.
printf “int main () { 5 ; };" "$msg" > ${fname}.c More Examples
gcc -o ${fname} ${fname}.c 2> /dev/null && ${fname}
You can use more complex code blocks including
rn -f ${fname} ${fname}.c
loops. For example:
Figure 1 rune "for(int i=; i<1888; i++)printf("xd ",{);printf("\n")’
[esser@xpsi3:~]$ jobs -1 will printa sequence of numbers (just like seq -s "" @ 999
[[1]+ 79948 Stopped mic (wd: ~/bin) does). Itis also possible to use code that stretches across
[lesser@xpsi3:~]$ ps -e0 pid,sess,pgid,conmand | egrep "$$| COMMAND" several lines: When you start the C string with the ‘ charac-
PID SESS _PGID COMMAND ter (like in the examples), you can press Return as often as
74405 74405 74495 bash
79948 74405 79948 mc you like — until you end the string with another ' symbol.
30002 74405 86002 ps -e0 pid,sess,pgid,connand As a fun example, in order to generate a segmentation
99003, 74405 80002 grep -E --color=auto 74405 | COMMAND
lesser@xps13:~]$ runc 'printf("xd\n" ,getsid(79948))" fault, just try an assembler instruction that would disable
174405 interrupts: rune ‘asa("cli")' cannot be run successfully
[esser@xps13:~]$ runc 'printf("xd\n" ,getpgid(79948))' because cli is a privileged instruction that can only run
in kernel mode.
By Hans-Georg EGer

HACK S41, Edit Binary Files with hx defaults to hexadecimal values, or base 16, representing
Even if you're not a developer or a the raw binary contents of a file. Thanks to your comput-
“hacker,” sooner or later you'll need to use a hex editor. er's binary logic, this single hex value is a “nibble” of
This is primarily because a hex editor is a bridge between data, usually grouped into pairs to form a “byte.” Bytes
the worlds of code, binary, and content, allowing you to are also turned into ASCII text, so you can read raw data
open and view a file regardless of its format or whether if necessary, and those bytes in turn are grouped into
the file is corrupt or complete or not. The file could be an columns containing 64 bits per column. This makes find-
executable binary in which you search for some string. ing a specific location or offset much easier, whether
Ahex editor will gladly display any file's contents that's in your computer's raw memory or within a file.
where a classical text editor won't. That display usually You can download (or git clone), unpack, and compile
Figure2 the source with make —that should work on any system
with basic development packages installed. Ignore com-
piler warnings related to the strnpy function. The editor is
Vim-like, so you can switch between insert and command
modes. Navigation and search keys are also the same as.
in Vim, and you should be able to start editing without re-
ferring to the excellent man page if you're already familiar
with Vim. This means you can search, update, edit, insert,
and replace right from the command line, working with
binary files just as you can with text. Figure 2 shows the
successful detection of a hidden password in a binary file.
By Graham Morrison
https://github.com/krpors/hx
2400 bytes write
101 LINUX HACKS - 2021 EDITION 85
Edit Your Text Files with Textosaurus
Yes, there are many, many text editors for Linux. But there cursor editing. The editor is available as an Applmage, so
isn't a Linux equivalentto the venerable Notepad++ on you can take it for a test ride without installing a pack-
Windows. Textosaurus attempts to fill the void. Thanks to. age. Just download the textosaurus-*-I inux64. Applmage
being built on both Qt and the Scintilla text-editing frame- file, make it executable, and run it.
work, it's completely cross-platform, so it can replace By Graham Morrison
Notepad++ on Windows as well as it does on Linux. It https://notepad-plus-plus.org/
even features a very similar layout and design. https://github.com/martinrotter/textosaurus
To help with its cross-platform credentials, it uses
UTF-8 internally, so your text should remain legible Figure3
whatever platform or locale you're using, and many
input encodings are supported. It also features menu
options to convert end-of-line characters into some-
thing that works, which is often still a problem when
working with text files generated in Windows. The syn-
tax highlighting looks fantastic and will even print,
while the UI remains very easy to use. (On our test ma-
chine, syntax highlighting did not work until we
changed the editor color theme; Figure 3 shows the So-
larized Dark theme.) You can move parts of the UI
around, as you can with many KDE apps, but Qt and the
bundled Scintilla are the only dependencies.
There are lots of small utility functions too, such as a
menu full of MIME tools, JSON beautifying, and Mark-
down preview. You'll also find advanced features, such as
the ability to record and play back macros and multiple

WACK
Manage Your git the repository are captured by monitoring the filesys-
Repository with GRV SG tem and updating the Ul automatically. This means it
works well in a separate tmux panel, for example, cap-
So many of us now use git on the command line that it’s turing changes as you make them or as they're pulled
difficult to contemplate using a GUI tool to make access- from upstream. git is complicated. While GRV is never
ing git repositories easier. The context shift from com- going to make the learning curve any easier, it's a fan-
mand line to desktop is often enough to break your train tastic tool for confirming that what you think is happen-
of thought or concentration, but there is a helpful tool ing is actually happening, as well as for helping you to
that’s worth using: Git Repository Viewer (GRV) effec- visualize how your projects are developing.
tively builds an entire GUI on the command line around By Graham Morrison
your local git repositories. The main view, called the His- https:/github.com/rgburke/grv
tory View, consists of three panels (Figure 4). On the left is
a pane for branches, tags, and remote references, and in Figure4
the middle is a list of commits for your chosen branch.
The pane on the right side lists the changes, as a diff, for
that specific commit. The other view is Status View, which
gives an overview of what's changed in your local branch
since the last push. If you're already familiar with git, this
makes complete sense. It's wonderful to see your work
presented in such aclear way, just as you likely imagine
the whole repository hanging somewhere.
GRV is also deep. It defaults to using Vim key bind-
ings and makes a wonderful partner to programming in
the editor. There's even theme support and the ability
to filter through the data using a query language rather
than simple searches. In the background, changes to

86 101 LINUX HACKS


- 2021 EDITION
HACK §$37/
Make git Interactive
Tools for navigating git repositories, their history, and
Replace
hexdump with
me 23
their branches are becoming almost as common as a Colorful Tool
CPU monitors. And like CPU monitors, they also hap-
pen to be very useful. Having more options to choose When viewing binary files in hexadecimal, you're
from means you're more likely to find a tool to fit your able to decode more than the literal value for any one
exact requirements. One fully fledged option is GRV location. You're actually able to see patterns and even
(see Hack 86), which runs from the command line and raw data emerge because the view can represent the
features several different view modes. way data is physically passing through memory. This
At the other end of the feature spectrum, gitinis is why a hexadecimal viewer is an essential utility to
another great option. Unlike GRY, gitin isn’t an appli- have at hand, especially if you're interested in how
cation in which you spend time; instead, it works best files are stored or how an executable may work.
as a form of wrapper around the git commands you One such tool, hexyl, couldn't be any simpler (Fig-
might use anyway. Its principle functions allow you ure 6). It's driven from the command line and takes a
to work with branches, check the status of a reposi- filename as an argument. The only other potential ar-
tory, and view the logs, which are all you need ina gument is a value to adjust the number of bytes read
tool because you don’t want to duplicate what git al- from the input. This is useful if you're trying to view
ready does so well. something large, such as a swap file or even a virtual
Type gitin 10g within a repository, for instance, and device such as memory. But the best thing about
you see a list of the most recent commits. Using the hexyl is how clean the output is. There’s no superflu-
cursor keys to scroll through them updates details on ous detail, with the same three columns you tradi:
each commit, and pressing Return dives into which tionally see in hexadecimal viewers and editors - the
files have changed. Select a file, and you get the tradi- starting location for a row, the hexadecimal value for
tional diff view of what's changed within that file each location for the input shown on the left, and an
(Figure 5). It’s minimal and effective and, most impor- ASCII rendering of those locations on the right. Loca-
tantly, doesn’t detract from the work you're likely try- tions are colored according to their type: NULL bytes,
ing to do in the same terminal. It just lets you see the printable ASCII characters, ASCII white-space charac-
same details git can provide in a more convenient and ters, other ASCII characters, and non-ASCII.
interactive way that’s also quicker than trying to work On Ubuntu, install the package with apt install
out the commands using git alone. The use of color is hexyl. On other distributions, unpack the hexyl-
also very effective and helps especially in the diff view v0.8.0-x86_64-unknown-linux-gnu.tar.gz archive that
where the red ofa remove line and the green of anew you find on the project's releases page.
line is far easier to see than the - and +.
By Graham Morrison
By Graham Morrison https:/github.com/sharkdp/hexy!
https:/github.ce sacikgoz/gitin
Figure 6
Figure5
aes eo ey

een Cr aeseme meee Cla

101 LINUX HACKS - 2021 EDITION 87


~ WORKING WITH CODE

Textadept Works in Graphics and Text Mode


Not many other software categories offer such breadth don't find in most editors is changing the
of choice as text editors. Textadept is one promising font size individually for each open file (Figure 7).
speed and distraction-free design without sacrificing When you use a machine remotely, you can also run a
essential features. It is available for Linux, macOS, and terminal version of Textadept called textadept-curses.
Windows.
Textadept is certainly mature: Its development started By Graham Morrison
in 2007, and the developers have released a new ver- https:/orbitalquark.github.io/textadept/
sion every two months through- Figure 7
out the past ten years. Textadept ‘ine Tetdepe (home jesse) vane
can be runeither as a curses bi- te oot soren IE ete von ve
nary within the command line or Tor aa Td = WAX ADOR SPACES
as a GUI application. The execut- Af (address. spaces(id) .status | AS Tey
FREE) (
able is around 3MB and can be Ust address space (id)
run offa USB stick. Into this tiny
space, it's not only capable of meu_p (addr space id id
cramming in lightning-fast syn- pageno) {
tax highlighting (for around 100 Péindex = pageno/
ptindex = pagen o
page direc tory “pd = addre ss_sp aces|
languages) but, more impor- If (| pd->ptds(pdindex! present ) { id) pd
tantly, code completion, too. For ) else {
those of us without photographic page (pd->pt4s
PHYSICAL table “pt [pdindex).trane_addr
= (page tables <<
memories, this feature is essen- ‘siptindexl.present ) (
tial. Autocompletion via Ctrl+ >pds{ptindex}, frame addr:
Enter works with symbols within
the files you're editing, as well as
cas” eee
symbols for the language you're ‘7y-ova Cane Coen Fenoved
working with, complete with ‘penaddress mau (addr space id id, memaddress voddress) (
‘unsigned int tap = immup (id, (vaddress >> 12)):
links to the API documentation. Af (tmp == -1)
return -2; Wetese
The editor is also almost en- z else
tirely keyboard driven, completely return (tep'<e-12)/ 4: (VaddressW PAGE:STZE)
themable, and well documented. ner) (
An interesting feature that you

Perform Dynamic Code Analysis with SystemTap


In multithreaded programs, the order of statements in SystemTap lets you write small
the sources is different from the order of execution. So, scripts called probes and attach
merely looking at the code doesn't reveal the sequence them to various events happening in
of the program’s operations. You want some tools for user space and in the kernel. It was designedto be safe
live introspection, also called dynamic code analysis. for use on production systems, so you can study non-
SystemTap is one such tool, and stap is its main exe- trivial situations, such as deadlocks, in the wild.
cutable. On Ubuntu and openSUSE you can find systen- One of the things that SystemTap can do is help deter-
tap packages in the default repos. You need the kernel mine “contended locks.” You can find many examples in
debug info which can be hard to install, depending on Just/local /share/doc/systentap/exanples. One of these is
the distribution you use. On Ubuntu 21.04, installation the process/futexes. stp script. It traces the futex system
via apt resulted in a broken (and useless) SystemTap, call and dumps how many times the thread had to sleep
and after a bit of tweaking we can suggest these steps waiting for the lock and for how long. Run it as root and
instead: Add a new package source as described in the stop it after a few seconds; it will output observations
wiki page Debug Symbol Packages, then run: like VirtualBox[63297] lock x55557e2b18c8 contended 1
times, 89519 avg us — lower values are generally better.
sudo apt install g++ make git libelf-dev libdu-dey 2
linux-image-$ (uname -r)-dbgsym By Valentine Sinitsyn and Hans-Georg EBer
git clone git://sourceuare. org/git/systentap. git https://sourceware.org/systemtap/
cd systemtap; ./configure && make && sudo make install https://wiki.ubuntu.com/Debug%20Symbol%20Packages

838 101 LINUX HACKS - 2021 EDITION


WORKING WITH CODE ~~

Count Lines of Code in Your Project


HACK 9 1
Are you interested in statistics about your coding pro- projects. The practical helper counts blank lines and
jects? You could process your source files with uc -1 to comments, as well as real lines of code (Figure 8). It
geta line count, but that simple tool does not know the writes the statistical analysis to the standard output. cloc
difference between comments and real code. We sug- requires Perl §.6 or later. On Ubuntu you can apt install
gest that you use something better. cloc— which stands the cloc package; on other distros use git clone.
for count lines of code- gives you an overview of your cloc understands more than 250 different program-
ming languages. You can obtain a full list using cloc
Figure 8 =-shou-lang.
You can specify individual files or entire directories to
be counted. cloc also understands compressed TAR or
[[esser@xpsi3:ulix]$ cloc .
8 text files. ZIP archives; the tool can receive optional help when un-
8 unique files. packing via --extract-with. The Perl program also tracks
@ Files tgnored.
changes between two files, directories, or archives. Its
man page lists various diff parameters with examples.
You can save the results from cloc’s evaluation in
CSV, XML, or YAML format, and via --sql=fi lenane it
will generate INSERT statements for an SOL database.

By Uwe Vollbracht
http://github.com/AlDanial/cloc

Fix Disturl g Indentation and More


Aclassic developer tool is the “indenter,” a program Once it's installed, grab a
that takes a source code file and creates a new version suitable source file and run:
where indentation and brace placement follow some uncrustify -c linux.cfg testfile.c
fixed rules. To see an old example program from this
category, look at indent. The Unix original is from the This will create a new file testfile.c.uncrust
ify. | tried it
late 70s, and on Linux you can install GNU indent, on auto-generated (and poorly formatted) code with
which was last updated in 2008. some success, as you can see in Figure 9.
For a more flexible approach, have a look at the un- By Hans-Georg EGer
crust ify tool: It can do a bit more than indent, and you
can configure it by writing a complex config file. The httpsi/en.wikipedia.org/wiki/indent_(Unix)
program supports the C, C++, C#, Objective C, D, Java, http:/uncrustify. sourceforge.net/
Pawn, and Vala languages. To get you started, there's a http:/uncrustify.sourceforge.net/linux.cfg.txt
sample file (search for linux.cfg in the package igure9
contents or on the project web page).
Ifound an old openSUSE package and none at
all for Ubuntu in the regular repositories. But it's
easy to compile it from the sources. You can
check out the current version vi
git clone git://github. com/uncrust ify/uncrustify. git
In my test, | was able to build the project with:
ed uncrustify; mkdir build; ed build
cmake .. @& make && sudo make install
run in the unerustify folder. (On Ubuntu, run apt
install cnake to get that particular build tool.)

101 LINUX HACKS - 2021 EDITION


COceccoccocok

Is it a hack to bring back the old DOS editor EDIT for


editing your config files? Or to run an old BBS like they
did in the '80s? Yes, those are hacks. Also, did you like
the old “3D Pipes” screensaver? Read on...

SPIAPIIIIIIAIIIIIIIIAIIIIIIA

66
6

HACK 93
TC CUM Ream
OA SIC LES

HACK 94
STC UMUTM ciMelg UL camer a Aled

HACK 95
Drive Your Moon Lander —in ASCII!
HACK 96
Run Your Own BBS
Tey]
Explore, Expand, Exterminate: Play Star Ruler2
HACK 98
Seite secu CCF
HACK 99
ECO) AUT =se1e).<3)
LP NeL att)
ae
NCL aC)
BURR MLM aU R Ey

101 LINUX HACKS - 2021 EDITION


HAVING FUN

Interesting Terminal Output for Your Visitors


When you have friends or colleagues com- Other than producing interesting output and (when
ing over, do you want to impress them with inter- programming) seeing stuff in octal, knowing od is help-
esting and mysterious stuff happening on your com- ful when you prepare for the LPI tests: It's listed in the
puter screens when they take a tour of the house? Then curriculum, and that is why | know it.
you have lots of options.
Create Slowly Scrolling Output
Glitch in the Matrix You know those movies where hackers sit in a dark
Let me introduce to you the od program. The name is room behind a big screen and occasionally you get a
short for “octal dump,” and the tool works like hexdunp glimpse of what's happening on the screen. In some
but uses octal numbers (0-7) instead of hexadecimal window, there's always some scrolling output. That
ones. Let it output /dev/urandom to get a (very cheap) could be C compiler messages, diesg lines, or just some
text mode version of the scrolling symbols from The random JavaScript and HTML from a web page - it
Matrix movies. If you want to get rid of the space signs, doesn’t really matter (to the film directors) as long as it
remove them with tr: looks geeky.
Now you want to have this on your screen, but sim-
od /dev/urandom | tr “\n" " | tr -d" ply running dnesg or cat source.c in a terminal window
lets the text scroll far too fast. The following code re-
Run the od output through lolcat to get the colorful places cat as a filter and introduces a short sleep after
version shown in Figure 1. Some distributions carry a every lin
lolcat package; if yours does not, you can install it
manually. uhile read -r; do echo "$REPLYS"; sleep .@2; done

Figure 1 Combine it with something that produces colors for


an even nicer effect; my favorite is a colored dnesg
(Figure 2):
dmesg -L=aluays | uhile read -r; do echo "SREPLY$"; 2
sleep .82; done
(Even if your daesg is colored by default, you will need
the -L option because daesg notices that output is not
going to a terminal but into a pipe, which will turn col-
ors off. Run diesg with sudo if you're not root.)
If that’s not enough, install the aalib (openSUSE),
libaa-bin (Ubuntu), or a similar package, which contains
a library for rendering graphics (and videos) as ASCII
output. There's an example program called aafire that
turns your terminal window into a fireplace.
By Hans-Georg EBer
https://github.com/busyloop/lolcat

101 LINUX HACKS - 2021 EDITION


HAVING FUN

MK Scan the Network Like a Script Kiddie


The nap (network mapper) tool searches for open
ports in a computer network or on a specific machine,
rity focus — as well as for hackers gone bad who attack
machines for evil purposes. The second group in-
and it can even find out which operating system and cludes script kiddies.
version is running on a remote computer. That makes True script kiddies like to see their texts in leetspeak
it an important tool for IT professionals with a secu- (or 138375p34k). Since they are likely to (mis-)use the
‘nap tool, it provides a leetspeak option to
Figure3 make them comfortable. You can feel like
a script kiddie, too: Just run the mapper
with the option -0S to change the output
format to “Script kiddie” - the result will
look like Figure 3.
The -o option has further, more legiti-
mate parameters as well: -oX switches to
XML output and -06 to a format that can
easily be filtered with grep. But where's the
fun in that?
By Hans-Georg EBer
https://nmap.org/
https:/en.wikipedia.org/wiki/Leet

Drive Your Moon Lander - in ASCII! HACKS) 5


When you think of games made with ASCII characters, engine than the original. However, in this case, it makes
you typically start with Snake and end with NetHack, the graphics utterly enchanting. You'll be hooked from
both of which are brilliant in their own way. You don’t the moment you launch the game and the moon buggy
typically think of something with refined arcade-quality scrolls smoothly from one side of the screen to the other
playability and design. And yet that exactly describes (Figure 4). On Ubuntu, sudo snap instal! asci-patrol.
Ascii Patrol, an interpretation of the arcade classic, Pressing any key from the title screen takes you to an
Moon Patrol, recreated in text characters to run ona overview screen, which includes a player profile and
console. Outside of '80s-era home computer arcade editable avatar, a campaign overview complete with a
conversions, it's one of the few modern recreations of map, and an online leaderboard, plus there’s a handy
an old game built atop an even more limited graphics controls overview. It's like an AAA game on Xbox Live.
Press the spacebar, and you're playing the game. As
Figure 4 with the original, the action comes from a side-scrolling
obstacle course where you accelerate and decelerate
your buggy, jump, and shoot at things while avoiding
rocks and crevasses. Your score is based on how far
you get. It's deceptively tricky and very addictive, and
you soon forget the entire game is being rendered
using only ASCII characters. It plays brilliantly, and it's
just as addictive and as playable as the original, with
the new/old graphics being part of the charm, rather
than a compromise.
By Graham Morrison
http:/ascit-patrol.com/

92 101 LINUX HACKS


- 2021 EDITION
While it’s sad when a company gives up on gam-
ing, if they choose to do the right thing with the
code, it benefits a much wider audience. Star Ruler 2
TA ) ° is a great example (Figure 6). A popular real-time
strategy (RTS) game from 2015, it's still available on
Steam, but the studio behind it, Blind Mind Studios,
has been inactive for a few years. Rather than drop
Those of a certain age will remember a time before off the radar completely and alienate its players, the
the Internet: If you wanted your computer to commu- studio decided to open source both its game and the
nicate with other computers, you did it on a 1:1 basis expansion pack.
across a telephone line. You dialed a number, and an- You can install the game with just a single com-
other computer answered before proceeding to ne- mand, sudo snap install starruler2, if your system
gotiate a stream of ASCII going back and forth down supports snaps. You get a major multiplayer RTS
the line. There were many popular “online” services on Linux for free, and that's never a bad thing.
that you could pay to access, but perhaps the best
use of this technology was the humble bulletin board
system (BBS). These were portals for files, messages,
and games that were usually run from a home com-
puter with nothing more than one or two phone lines
that became available in the middle of the night.
The Internet killed the BBS scene, but it's now hav-
ing a slight renaissance, partly for nostalgia, but also
because the web has become hugely distracting.
These new BBSs, and even the old ones restored
from backups, are accessible over a simple Telnet
connection (and sometimes SSH); you can even be-
come the sysop of your domain. MBSE BBS is a mod-
ern BBS (Figure 5) you can install that's still being up-
dated, but it takes some setting up. If you try it, your
users will be able to create accounts and log in, leave
messages, download and upload curated files, and
chat with each other. You can even allow as many
concurrent users as you need. Set in space, the game itself is known as a “4x”
RTS game, meaning your role as the ruler of the gal-
axy is to explore, expand, exploit, and exterminate.
https://sourceforge.net/projects/mbsebbs/ There are seven different races with different attri-
butes, and you can create your own. With that done,
you're dumped into space where you need to man-
age your finances and local resources to build an em-
a a Ree ee eee net pire. You map resources between systems by drag-
see et err aren a ETE Tere Tera ARs ging lines between them, creating networks for im-
ports and exports. You use your fleet of ships to ex-
o Pen plore and colonize just as you do with other RTS
games. As you play, you acquire influence points that
can be used in diplomacy, and you can even design
your own ships. The game isa lot of fun, and it’s pol-
ished, just as you’d expect with a commercial game.

http://starruler2.comy

101 LINUX HACKS - 2021 EDITION 93


HAVING FUN

Edit Files Like It’s the '90s Again


Look at Figure 7, which shows good old EDIT from DOS file into /tmp. You will find a new BIN sub-
editing a file. If you want to replace all other editors folder that contains EDIT.£XE and EDIT. HLP. Copy
with this classic tool, there’s a way. To prepare, first in- those to ~/dos.
stall DOSBox (the dosbox package) and create a dos Also copy the text file you want to edit to ~/dos/file.
folder in your home directory. Then grab an image ofa txt. Now you can boot DOS and let it execute EDIT. EXE
MS-DOS clone, such as FreeDOS 1.2. Mount the CD- by typing:
ROM image (F012C0. iso) and unpack the BASE/EDIT.
ZIP
dosbox -c “mount ¢ ~/dos" -c ~c “edit file.txt" -c exit
Figure 7
which brings back the glorious old look and edits your
file. You can access the menu entries by pressing Alt
and then using the cursor keys, or via Alt+F (File), Alt+E
(Edit), etc., or even by using the mouse. (If your mouse
gets stuck inside DOSBox, press Ctrl+F10 to release it.)
When you're done, press Alt+X to exit both the editor
and the DOS emulator.
It’s only a little more work to create a script that will
copy a text file to the »/dos folder, launch the emulation,
and then copy it back.
By Hans-Georg EBer
https:/www.dosbox.com/
https:/mww.freedos.org/

Read Old U Books pen to all documentation. While a KDE book


from the late '90s has lost all usefulness (except
Reading a good book is always worth- as a picture album to see what desktops looked
while, but computing literature tends to age in like in the old days), you can always grab a good intro-
away that makes most practical descriptions obsolete duction to the shell - for example, the article “The
within a decade. In the case of Linux, that doesn’t hap- UNIX Shell” from Stephen R. Bourne, who developed
the Bourne shell (sh), an ancestor of the Bash
Figure 8 shell. After all, Bash is an acronym meaning
roy “Bourne-again shell.”
The article was published in 1978. Grab a
eeo Ga copy from archive.org
and read the introduc-
ae set in a pofle which is executed when
on to variables
1 ser logs these
‘Typically, tion to using the shell, working with variables,
UN writing shell scripts with for and uhi le loops,
‘suat
specified by this va pipelines, and much more (Figure 8). Travel-
this fle bas been
the shell prins the message you have mall and then ing back in time 40 years does not change
‘prompts
“The defaitfortheargument
next command
(home directory) fot the ed com- shell usage a lot. Of course, a modern Bash
‘mand. The cutrent drecory is used to resolve has more features and offers more comfort,
fname references that do not begin with a /, and
changed using the ed command but the basics have remained the same.
1 list of directories that contain commands (the search
path). 1 4 command is executed by the shel,
{Tis of Each
directories searched for an executable le. If By Hans-Georg EBer
‘Seat isnot set, then the current directory, bin, and
Zusr?oin are searched by default Otherwise SPATH https:/archive.org/details/bstj57-6-1971
consists of ditetory names separated by :. For exam
meine redraft
secs that the current ditecory (the null sting

94 101 LINUX HACKS


- 2021 EDITION
Pick a Retro Screensaver HACK 100
There are two things you might miss from working with Click on Pipesto start a good approximation of the 3D
Windows, especially the older versions: the 3D Pipes Pipes from Windows (Figure 10). You can configure this
screensaver and the occasional display of the famous screensaver via the Settings button; there are a few in-
Blue Screen of Death (BSoD). Sadly, modern Windows teresting options. Figure 10
versions do not suffer from the same stability issues. If If you want to
you remember Windows 95 and 98, you know what I'm see a screen-
talking about. saver in full-
Everything you need to celebrate your nostalgia is screen mode,
available in XScreenSaver and add-on packages. You you'll have to
only need to install and configure them. The names of start the previ-
the required packages differ from distro to distro. For ously mentioned
example, on Ubuntu or Mint type: daemon. Click on
Preview and the
sudo apt install xscreensaver xscreensaver-g] 2 warning dialog
xscreensaver-gl-extra xscreensaver-screensaver-bsod
will reappear.
to get the packages. OpenSUSE users run the command: This time, start the daemon. In my tests, | had to click
sudo zypper in xscreensaver xscreensaver-data 2 on Preview again.
When you've found your favorite, check the process
xscreensaver-data-extra list (or tree, with pstree) to find its program name. You
and Fedora wants you to type: can find individual screensaver binaries in various fold-
sudo dnf install xscreensaver ers, depending on your distribution. For example:
* /usr/libexec/xscreensaver/ (Fedora)
Once the files are on the disk, you can decide whether * /usr/1ib64/xscreensaver/ (openSUSE)
you just want to play with the screensavers or really in- * /usr/1ib/xscreensaver/ (Ubuntu)
stall one (so that it will start up aftera few minutes of
inactivity). Make It Permanent
To install a screensaver from this collection as your regu-
Just Playing lar screensaver (instead of the desktop’s standard tool),
If you just want to have a look at the screensavers, run make sure that the desktop’s screensaver and/or locking
the xscreensaver-deno program. You'll get a warning dia- mechanism is off, that XScreenSaver starts automati-
log from which you can launch the XScreenSaver dae- cally when you log in, and that it’s properly configured.
mon - for testing purposes, click Cancel. On KDE, disable the built-in Screen Locking in the
From the list on the left side (Figure 9), selecta KDE system settings. Then make sure that the
screensaver and see what it looks like on the right side. XScreenSaver daemon starts when you log in: Open
The BSOD entry holds more than just a blue screen KDE's Autostart settings, click Add Program, type
from Windows: There are all kinds of operating system xscreensaver in the input field, and click OK. Check that
crashes from various architectures, some of them ani- it works by logging out and in again, and then search
mated. The Windows 10 bluescreen even displays a QR the process table for xscreensaver.
code (Figure 9). If you encounter it, quickly start the OR When using Gnome, uninstall the gnome-screensaver
code viewer app on your phone. | don’t want to ruin the package (if installed). Make xscreensaver an autostart
experience for you by telling what you'll get. program (open Startup Applications, click Add, enter
xscreensaver in both the Name and Command fields,
Figure9 and click Add). Then log out and in again; you should
see a splash screen.
For Mint's Cinnamon desktop, disable the Cinnamon
screensaver and then create a hard link like this:
sudo In -sf /usr/bin/xscreensaver-conmand 2
/usr/bin/cinnanon-screensaver-conmand
When you want to both auto-activate the screensaver and
make it lock the screen, use XScreenSaver's settings dia-
log (that you start with xscreensaver-deno) and set two
timeouts in the Blank After and Lock Screen After fields.
By Hans-Georg EBer
https://nww.jwz.org/xscreensaver/

101 LINUX HACKS - 2021 EDITION 95


HAVING FUN

The Good Old Days: Linux From the 1990s


Many users feel that their Linux experience is already some problems, but you should always be
sufficiently retro when they switch to pure text mode able to get it to run in text mode. But where can you
(Ctrl+Alt+F1) and log into their systems the old-fash- get the installation media that you need for a virtual ma-
ioned way. chine?
For users who want to, though, you can still dive into + The Internet Archive (archive.org, the site that also
the world of Linux as it was 10 or 20 years ago. Of provides the Wayback Machine) is a huge repository
course, you'll get the best experience if you have an old of obsolete software. Just use their search dialog if
computer that's still functional and search eBay for a you want to download a specific Linux system. Figure
classic Linux box set. At the time of writing there were 12 shows some of the search results for “Red Hat
several Red Hat Linux 6.x and 7.x boxes for sale, com- Linux.” If you need some inspiration, go to the “Linux
plete with CDs and a printed manual - maybe you'll Distributions” page on the Internet Archive. If you
even find a box with (floppy) boot disks. The earliest want to play with the MS-DOS or CP/M operating sys-
Linux systems had to be installed from dozens of flop- tem, you can find many versions of those systems and
pies because those new-fangled compact disc drives also applications that run on them in the archive.
had not yet become popular. But finding a working set + Asecond interesting source is the Archive of Operat-
of floppies might turn into a challenge, so | would sug- ing Systems, which specializes in Linux distributions
gest you stick to distros with CD-ROM installation (and some other systems) which no longer exist. So
media. In Figure 11 you can see an old machine that| you won't find Ubuntu or openSUSE on their site but
Figure 11 use for retro ex- will find many other Linuxes from the past.
periments; it When you configure a virtual machine for an old Linux,
has a CD-ROM avoid SATA hard disks and choose classical IDE disks in-
drive and floppy stead: Old Linux kernels will not recognize modern
drives for both SATA controllers. Figure 13 shows the Red Hat Linux 6.2
3.5" and 5.25” installer running on VirtualBox. During my tests, | had
media. to change some more VM settings: | exchanged the de-
Ifusing an fault network adapter with a virtual PCnet-PCI Il, and
aged physical then the Red Hat system successfully acquired an IP ad-
machine is not dress via DHCP. | also played around with the virtual
an option, you graphics cards that VirtualBox allows you to choose but
can always try did not get that part to work. You could, however, en-
virtualization. able an SSH daemon, log in to the VM with X forward-
Getting the ing, and then launch a fresh terminal or other program
graphical desk- from the past that you want to use.
top of avery old Many other outdated operating systems can also be
Linux to run on found on the Internet, for example, MS-DOS and the
the current Vir- early DOS-based Windows versions, and also other
tualBox or VM- Unix-like systems such as the BSDs or Solaris / SunOS.
ware Player If you want to go back in time even further, you leave
may cause the PCs behind and enter the home computer sphere:
Say hello to the Commodore C64, C128, and Amiga; the
Sinclair ZX Spectrum; the Amstrad CPC; and the various
Figure 13
ed Wat Linus 62 Running

DORs SeML Bronce

96 101 LINUX HACKS


- 2021 EDITION
HAVING FUN

tions (like the ZX-Uno, see Figure 14, or the Spectrum


Next), and it handles virtual extras such as a tape or disk
drive or joysticks very well.
If you want to replay classic home computer games,
you should try the MAME emulator system. On Ubuntu,
apt install the gnome-video-arcade package (which in-
cludes MAME); however, it will take some time to set
this up properly. Another option is to try out RetroPie.
While that software is intended to run on the Raspberry
Pi, the developers have also created a PC version which
works on various Linux distributions, including Ubuntu.
Whether it's an old Linux system, another old OS for
IBM-compatible computers, or an emulated home com-
puter all the way back from the '80s, current Linux sys-
tems let you travel back in time when you install the
right software. Enjoy the journey!

Atari systems - to mention only a few of them. Almost https:/archive.org/


all classic home computers can be emulated on Linux. https:/archive.org/details/linux_distributions
One current emulator that | find particularly pleasing https://archiveos.org/linux/
is Retro Virtual Machine 2. It is not open source, and it is https://en. wikipedia.org wiki/SunOS
limited to just two computer families (Amstrad CPC and https:/www.retrovirtualmachine.org/
ZX Spectrum), but it can handle modern re-implementa- httos://www.mamedev.org/

Linux Magazine is your guide to the world


of Linux. Look inside for advanced technical
information you won't find anywhere else!

In-depth articles on trending topics, including


Bitcoin, ransomware, cloud computing, and more!
How-tos and tutorials on useful tools that will
save you time and protect your data
Troubleshooting and optimization tips
Insightful news on crucial developments
in the world of open source
ux Cool projects for Raspberry Pi, Arduino,
and other maker-board systems

Subscribe now!
shop.linuxnewmedia.com/subs
~ MASTHEAD / AUTHORS

WRI RUS
We are always looking for good articles on Linux and the The technical level of the article should be consistent
tools of the Linux environment. Although we will consider _ with what you normally read in Linux Magazine. Re-
any topic, the following themes are of special interest: member that Linux Magazine is read in many countries,
* System administration s0 it is best to avoid using slang andidioms that might
* Useful tips and tools
not be understood by all readers.
Be careful when referring to dates or events in the future.
* Security, both news and techniques
Many weeks could pass between your manuscript sub-
* Product reviews, especially from real-world experience mission and the final copy reaching the reader's hands.
* Community news and projects When submitting proposals or manuscripts, please use a
If you have an idea, send a proposal subject line in your email message that helps us identify
withran outline, anestinate bfthe your message as an article proposal. Screenshots and
lengthy a description cfyour back other supporting materials are always welcome.
ground, and contact informationto Additional information is available at:
[email protected]. Attp:/www..linux-magazine.com/contact/write_for_us.

Editor-in-Chief While every care has been taken in the content of the
Hans-Georg EGer magazine, the publishers cannot be held responsible
Senior Editor for the accuracy ofthe information contained within it
Joe Casad or any consequences arising from the use of it The use
Managing Editor of the DVD provided with the magazine or any material
Lori White provided on tis at our own risk
Localization & Translation
lan Travis, Copyright and Trademarks ©2021 Linux New Media
Copy Editors USA, LLC
‘ape‘Amy Pettle, Aubrey Vaughn No material may be reproduced in any form whatso:
Dena Friesen, Lori White ever in wholeor in part without the written permis
Erik Barwaldt sion of the publishers, Itis assumed that all corre
Cover Design
Paul Brown Dena Friesen, ilustration based on graphics spondence sent, for example, letters, email, faxes,
Bruce Byfield by Maxim Popov, 123RF.com photographs, articles, drawings, are supplied for
Advertising publication or license to third parties on a non-exclu:
Hans-Georg ERer Brian Osborn, [email protected] sive worldwide basis by Linux New Media unless
Frank Hofmann phone +498093 7673420 otherwise stated in writing
Marketing Communications
Klaus Knopper en Clark, gota [email protected] Linux Magazine Special (ISSN 1757-6369) is published
Publisher by Linux New Media USA, LLC, 4840 Bob Billings
Charly Kiihnast Brian Osborn Parkway, Ste 104, Lawrence, KS 66049, USA.
Christoph Langner Customer Service / Subscription Allbrand or product names are trademarksof their re
For USA and Canada: spective : owners, Contact us if we haven't credited your
Graham Morrison Email: [email protected]
Phone: 1-868-247-2802 copyright will always correct any oversight.
Tim Schiirmann (tol -fre from the US and Canada) Printed in Germany on FSC ind PEFC certified paper.
Valentine Sinitsyn Forall other countri
Email; [email protected] Distributed by Seymour Distribution Ltd, United
Ferdinand Thommes Linux New Media USA, LLC kingdom
Daniel Tibi 484 Ste 104,
Lawrence, KS 66049, USA. Published in Europeby: Sparkhaus Media GmbH,
Uwe Vollbracht wwwlinux-magazine.com Bialasstr 1a, 85625 Glonn, Germany.

98 101 LINUX HACKS - 2021 EDITION


THINK LIKE THE EXPERTS
Linux Shell Handbook 2021 Edition

This new edition is packed with the most important


utilities for configuring and troubleshooting systems.

HANDBOOK=... UM
Ma
YOUR
as Ce seuGee
LINUX SKILLS inside:
Power at Your © Customizing Bash
Fingertips , i:
¢ Pipe and redirect output i ie Els 1341 C S(O)
© Monitor processes e Systemd
© Create custom scripts
e Bash Scripting
LC eT Cy
as a permanent e Networking Tools
Ws Cu Tecds es e And much more!
SYSTEMD
EES
Pa =m) e CIES
Ceo eee et

Co) Pl mela H
shop.linuxnewmedia.com/specials
Sharpen your view!
TUXEDO InfinityBook Pro 14

BZA [7] =

TUXEDO
COMPUTERS
\B tuxedocomputers.com

You might also like