Linux Ulitimate Guide Cheat Sheet Edition Pd3ywv
Linux Ulitimate Guide Cheat Sheet Edition Pd3ywv
1
Chapter 20: Automating System Tasks............................................................................ 45
Chapter 21: Real-world Examples and Case Studies ....................................................... 45
Cron Job Syntax Cheat Sheet ........................................................................................... 47
PART V: System Administration ............................................................................................ 48
Chapter 22: User and Group Management ...................................................................... 48
User Management, Group Management, and File Permissions Cheat Sheet .................. 49
Chapter 23: Package Management................................................................................... 50
APT, YUM, and SNAP Commands Cheat Sheet ............................................................ 51
Chapter 24: Disk Management ........................................................................................ 52
Disk Usage, Disk Partitioning, and Mounting Filesystems Commands Cheat Sheet ...... 53
Chapter 25: Network Management .................................................................................. 54
Network Configuration, Network Monitoring, and Nmap Commands Cheat Sheet ....... 55
Chapter 26: System Monitoring and Performance Tuning .............................................. 56
System Monitoring, Htop, and Performance Tuning Commands Cheat Sheet ............... 57
Chapter 27: Security and Access Control ........................................................................ 58
SSH Configuration, UFW, and SELinux Commands Cheat Sheet ................................. 59
Chapter 28: Case Studies and Real-world Applications .................................................. 61
PART VI: Advanced Topics .................................................................................................... 62
Chapter 29: Advanced File System Management ............................................................ 62
RAID and LVM Commands Cheat Sheet ........................................................................ 64
Chapter 30: Kernel Tuning and Optimization ................................................................. 65
sysctl Commands Cheat Sheet ......................................................................................... 66
Chapter 31: Virtualization and Containers ...................................................................... 67
Docker Commands Cheat Sheet ...................................................................................... 69
Chapter 32: High Availability and Load Balancing ........................................................ 70
Chapter 33: Security and Hardening ................................................................................ 72
SELinux Commands Cheat Sheet .................................................................................... 73
Chapter 34: Troubleshooting and Optimization .............................................................. 74
PART VII: Case Studies and Practical Examples.................................................................... 78
Chapter 36: Automating Daily System Tasks .................................................................. 78
Cron Expressions and Mail Command Options Cheat Sheet .......................................... 78
Chapter 37: Network Administration............................................................................... 79
iftop and nmap Command Cheat Sheet ........................................................................... 79
Chapter 38: Web Server Administration.......................................................................... 80
Chapter 39: Database Management ................................................................................. 82
Chapter 40: Security and Compliance ............................................................................. 84
Chapter 41: Advanced Scripting and Automation ........................................................... 86
2
PART VIII: Cheat Sheets and Resources ................................................................................ 88
Chapter 42: Basic Linux Commands Cheat Sheet ........................................................... 88
Chapter 43: Advanced Linux Commands Cheat Sheet .................................................... 89
Chapter 44: Shell Scripting Cheat Sheet .......................................................................... 89
Chapter 45: Network Administration Cheat Sheet .......................................................... 91
Chapter 46: System Administration Cheat Sheet............................................................. 91
Chapter 47: Security and Compliance Cheat Sheet ......................................................... 93
Chapter 48: Performance Tuning Cheat Sheet................................................................. 93
Chapter 49: Scripting and Automation Tools Cheat Sheet .............................................. 95
Chapter 50: Additional Resources ................................................................................... 96
PART IX: Appendices ............................................................................................................. 97
Chapter 51: Appendix A: Mathematical Foundations ..................................................... 97
Chapter 52: Appendix B: Shell Scripting Reference ....................................................... 98
Chapter 53: Appendix C: Linux Resources ..................................................................... 99
Chapter 54: Appendix D: Glossary of Terms ................................................................ 100
3
PART I: Introduction to Linux
Chapter 1: Overview of Linux
bash
bash
Linux Distributions
bash
4
• Differences and Use Cases for Each Distribution
o Ubuntu: Great for everyday use, multimedia, and general-purpose computing.
o Fedora: Preferred for development environments and testing new features.
o CentOS: Suited for enterprise environments requiring long-term support.
o Debian: Used in environments where stability and software freedom are
prioritized.
bash
# Fedora
sudo dnf install <package_name>
# CentOS
sudo yum install <package_name>
Linux Kernel
bash
bash
5
Chapter 2: Getting Started with Linux
Introduction
This chapter covers the essentials of getting started with Linux, including installing and
configuring Linux on various platforms, understanding the Linux directory structure, and
basic navigation and file management commands.
Installing Linux
powershell
bash
bash
6
• Installing Ubuntu on a Virtual Machine
1. Download and Install VirtualBox
▪ Download VirtualBox from the official site.
▪ Install VirtualBox following the on-screen instructions.
2. Create a New Virtual Machine
▪ Open VirtualBox and click "New".
▪ Follow the prompts to create a new virtual machine, selecting Ubuntu
as the OS.
3. Install Ubuntu
▪ Start the virtual machine and follow the on-screen instructions to
install Ubuntu.
bash
bash
7
Basic Navigation and File Management Commands
• Navigation Commands
o pwd: Print working directory.
o ls: List directory contents.
o cd: Change directory.
bash
bash
8
Chapter 3: Linux Environment
Introduction
This chapter explores the Linux environment, focusing on the shell as the primary interface
for interacting with the system. We'll discuss different shell types, shell features, scripting
basics, and how to write and execute simple scripts.
bash
bash
• Zsh (Z Shell)
o An extended Bourne shell with many improvements.
o Features include powerful scripting language, enhanced completion, spell
checking, and themes.
o Highly customizable with frameworks like Oh My Zsh.
bash
bash
# Install Oh My Zsh
sh -c "$(curl -fsSL
https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/instal
l.sh)"
9
• Fish (Friendly Interactive Shell)
o User-friendly shell with helpful command suggestions and intuitive syntax.
o Focuses on user experience and ease of use.
o Includes features like autosuggestions and syntax highlighting out of the box.
bash
fish
bash
• Scripting Basics
o Shebang: The #! line at the beginning of a script specifying the interpreter.
bash
bash
bash
# If statement in Bash
10
if [ "$MY_VAR" == "Hello, World!" ]; then
echo "The variable is set to 'Hello, World!'"
fi
bash
bash
bash
#!/bin/bash
echo "This is a simple script."
MY_VAR="Hello, World!"
echo $MY_VAR
bash
bash
11
PART II: Basic Linux Commands
Chapter 4: File and Directory Management
bash
• Managing Files
o Commands: touch, cp, mv, rm
bash
• Managing Directories
o Commands: mkdir, rmdir, rm -r
bash
12
Cheat Sheet:
13
Chapter 5: File Permissions and Ownership
bash
bash
o Explanation: chmod changes file permissions. Symbolic mode (e.g., u+x) adds
execute permission for the user. Numeric mode (e.g., 755) sets permissions
directly.
• Changing File Ownership
o Commands: chown, chgrp
bash
o Explanation: chown changes the owner of a file, chgrp changes the group of a
file.
14
Linux File Permissions Cheat Sheet
Symbol Meaning
r Read permission
w Write permission
x Execute permission
- No permission
15
Changing Permissions with chmod
16
Chapter 6: Basic Text Processing
bash
o Explanation: cat displays file contents, less and more allow paginated
viewing.
• Searching Within Files
o Commands: grep
bash
bash
o Explanation: head and tail view the beginning and end of a file, cut extracts
columns, sort sorts file contents.
17
Linux Text Processing Commands Cheat Sheet
18
Chapter 7: Networking Basics
bash
bash
# Ping a host
ping google.com
# Trace the route to a host
traceroute google.com
bash
19
Linux networking commands cheat sheet
20
wpa_supplicant Wi-Fi Protected Access wpa_supplicant -B -i wlan0 -c
/etc/wpa_supplicant.conf
client and IEEE 802.1X
supplicant
ip a Show all network ip a
interfaces and their
addresses
ip link Show/manage network ip link show
devices
ip route Show/manipulate the ip route show
routing table
netcat (nc) Utility for reading from nc -zv 192.168.1.1 22
and writing to network
connections using TCP or
UDP
arp Manipulate the system arp -a
ARP cache
mtr Network diagnostic tool mtr google.com
combining ping and
traceroute
iptables Administration tool for iptables -L
IPv4 packet filtering and
NAT
21
Chapter 8: System Monitoring and Process Management
bash
bash
bash
22
Linux System Monitoring Commands Cheat Sheet
23
Additional Elements
Case Studies
bash
#!/bin/bash
# Daily backup script
rsync -avz /source/directory /backup/directory
Diagrams
Summary
24
PART III: Advanced Linux Commands
Chapter 9: Advanced File Operations
bash
o Explanation: find searches for files and directories based on various criteria,
locate searches for files using a prebuilt database.
bash
• Comparing Files
o Commands: diff, cmp
bash
o Explanation: diff shows differences between text files, cmp compares binary
files byte by byte.
25
Cheat Sheet for find, sed, awk, and diff Commands
26
Chapter 10: Advanced Networking
• Network Configuration
o Commands: ifconfig, ip
bash
• Network Troubleshooting
o Commands: netstat, ss
bash
bash
o Explanation: ssh allows secure access to remote systems, scp securely copies
files between systems.
27
Cheat Sheet for SSH, ip, and netstat Commands
28
Chapter 11: System Administration
bash
bash
# Start a service
sudo systemctl start nginx
# Stop a service
sudo systemctl stop nginx
# Check status of a service
sudo systemctl status nginx
• Package Management
o Commands: apt-get, yum
bash
o Explanation: apt-get and yum are package management tools for installing,
updating, and removing software packages.
29
Cheat Sheet for User Management, systemctl, and apt-get Commands
30
Chapter 12: Advanced Scripting
• Bash Scripting
o Example Script: Backup Script
bash
#!/bin/bash
# Backup script
# Perform backup
rsync -avz $SRC $DEST
bash
#!/bin/bash
# Script to demonstrate variables
NAME="John Doe"
echo "Hello, $NAME"
bash
#!/bin/bash
# Loop example
for i in {1..5}
do
echo "Iteration $i"
done
o Explanation: This script uses a for loop to iterate and print numbers from 1 to
5.
31
• Debugging Scripts
o Commands: bash -x, set -x
bash
Additional Elements
Case Studies
bash
#!/bin/bash
# Server maintenance script
Diagrams
32
Cheat Sheet for Bash Scripting and Bash Debugging Commands
33
PS4='+ Customize the PS4='+ $BASH_SOURCE:$LINENO:
$BASH_SOURCE:$LINENO: ' '
debugging prompt
bash -x script.sh Execute a script in bash -x myscript.sh
debug mode
bash -n script.sh Check a script for bash -n myscript.sh
syntax errors without
executing it
exec 3>&1 4>&2 Save file descriptors exec 3>&1 4>&2
1 and 2
exec 1>output.log Redirect stdout and exec 1>output.log 2>error.log
2>error.log
stderr to files
exec 1>&3 2>&4 Restore file exec 1>&3 2>&4
descriptors 1 and 2
select var in list; do Select loop for select opt in Start Stop
... done Exit; do echo $opt; done
creating simple
menus
Summary
This expanded section on Advanced Linux Commands covers a wide range of advanced
topics, from sophisticated file operations and networking to system administration and
advanced scripting. Each chapter includes detailed explanations, practical examples, cheat
sheets, and diagrams to enhance understanding and application.
34
PART IV: Shell Scripting
Chapter 13: Introduction to Shell Scripting
bash
#!/bin/bash
echo "Hello, World!"
o Explanation: This is the simplest shell script that prints "Hello, World!" to the
terminal.
• Making a Script Executable
o Command: chmod
bash
chmod +x script.sh
35
Basic Shell Commands Cheat Sheet and Basic Shell Script Structure
36
Chapter 15: Variables and User Input
• Using Variables
o Example Script: Simple Variable
bash
#!/bin/bash
NAME="John"
echo "Hello, $NAME"
o Explanation: Variables store data that can be used later in the script.
bash
#!/bin/bash
echo "Enter your name:"
read NAME
echo "Hello, $NAME"
37
${variable/pattern/replacement} String echo ${name/Al/Bob}
replacement
export variable Export a variable export
PATH=$PATH:/new/path
to the
environment
$variable Access a variable echo $name
$variable/default Use default value echo ${name:-"Default"}
if variable is
unset
${variable:=default} Set variable to echo ${name:="Default"}
default if unset
${variable:+replacement} Use replacement echo ${name:+"Hello,
$name"}
if variable is set
${variable:?error_message} Display error echo ${name:?"Name is
not set"}
message if
variable is unset
`var=$(echo $variable tr 'a-z' 'A-Z')` Transform variable content to
uppercase
$1, $2, ... Positional echo "First arg: $1"
parameters
(arguments)
$@ All arguments echo "All args: $@"
$# Number of echo "Number of args:
$#"
arguments
$? Exit status of last echo "Last command exit
status: $?"
command
$$ Process ID of the echo "Script PID: $$"
script
$! PID of the last sleep 10 & echo "Last
background job PID: $!"
background job
$_ Last argument of echo "Last argument: $_"
the previous
command
38
Chapter 16: Control Structures
• Conditional Statements
o Example Script: If-Else Statement
bash
#!/bin/bash
if [ $1 -gt 100 ]
then
echo "The number is greater than 100"
else
echo "The number is less than or equal to 100"
fi
• Loops
o Example Script: For Loop
bash
#!/bin/bash
for i in {1..5}
do
echo "Iteration $i"
done
bash
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 5 ]
do
echo "Counter: $COUNTER"
let COUNTER=COUNTER+1
done
39
Shell Script Conditional Statements Cheat Sheet
40
Chapter 17: Functions
bash
#!/bin/bash
greet() {
echo "Hello, $1"
}
greet "World"
41
Chapter 18: Error Handling
bash
#!/bin/bash
cp /nonexistent/file /tmp/
if [ $? -ne 0 ]; then
echo "Error occurred while copying file"
fi
42
Chapter 19: Advanced Scripting Techniques
bash
#!/bin/bash
FRUITS=("Apple" "Banana" "Cherry")
for FRUIT in "${FRUITS[@]}"
do
echo "Fruit: $FRUIT"
done
• String Manipulation
o Example Script: String Operations
bash
#!/bin/bash
STR="Hello World"
echo "Length: ${#STR}"
echo "Substring: ${STR:0:5}"
43
Shell Script String Operations Cheat Sheet
44
Chapter 20: Automating System Tasks
bash
• Automating Backups
o Example Script: Backup Script
bash
#!/bin/bash
tar -czf /backup/home_$(date +%F).tar.gz /home/user
bash
#!/bin/bash
sudo apt-get update && sudo apt-get upgrade -y
sudo reboot
45
Server maintenance workflow diagram
bash
#!/bin/bash
LOG_FILE="/var/log/myapp.log"
mv $LOG_FILE $LOG_FILE.$(date +%F)
touch $LOG_FILE
46
Cron Job Syntax Cheat Sheet
Summary
This expanded section on Shell Scripting covers fundamental to advanced topics with
practical examples and scripts. Each chapter includes detailed explanations, commands, cheat
sheets, diagrams, and real-world case studies to ensure a thorough understanding and
application of shell scripting.
47
PART V: System Administration
Chapter 22: User and Group Management
bash
#!/bin/bash
sudo useradd -m -s /bin/bash newuser
sudo passwd newuser
o Explanation: useradd creates a new user with a home directory and bash
shell.
bash
#!/bin/bash
sudo groupadd newgroup
sudo usermod -aG newgroup newuser
o Explanation: groupadd creates a new group and usermod -aG adds the user to
the group.
• Managing Permissions
o Example Script: Change File Permissions
bash
#!/bin/bash
sudo chmod 755 /path/to/file
sudo chown user:group /path/to/file
48
User Management, Group Management, and File Permissions Cheat Sheet
49
Chapter 23: Package Management
bash
#!/bin/bash
sudo apt-get update
sudo apt-get install -y package_name
sudo apt-get upgrade -y
bash
#!/bin/bash
sudo yum update
sudo yum install -y package_name
sudo yum upgrade
bash
#!/bin/bash
sudo snap install package_name
sudo snap refresh
50
APT, YUM, and SNAP Commands Cheat Sheet
51
Chapter 24: Disk Management
bash
#!/bin/bash
df -h
du -sh /path/to/directory
bash
#!/bin/bash
sudo fdisk /dev/sdX
sudo mkfs.ext4 /dev/sdX1
bash
#!/bin/bash
sudo mount /dev/sdX1 /mnt
sudo umount /mnt
52
Disk Usage, Disk Partitioning, and Mounting Filesystems Commands Cheat
Sheet
53
Chapter 25: Network Management
bash
#!/bin/bash
sudo ip addr add 192.168.1.100/24 dev eth0
sudo ip link set eth0 up
bash
#!/bin/bash
sudo iftop
bash
#!/bin/bash
sudo nmap -sP 192.168.1.0/24
54
Network Configuration, Network Monitoring, and Nmap Commands Cheat
Sheet
55
Chapter 26: System Monitoring and Performance Tuning
bash
#!/bin/bash
top
bash
#!/bin/bash
sudo apt-get install -y htop
htop
bash
#!/bin/bash
sudo sysctl -w net.ipv4.tcp_syncookies=1
sudo sysctl -p
56
System Monitoring, Htop, and Performance Tuning Commands Cheat Sheet
57
Chapter 27: Security and Access Control
• Configuring SSH
o Example Script: Configure SSH Server
bash
#!/bin/bash
sudo apt-get install -y openssh-server
sudo systemctl enable ssh
sudo systemctl start ssh
bash
#!/bin/bash
sudo ufw allow 22
sudo ufw enable
sudo ufw status
bash
#!/bin/bash
sudo setenforce 1
sudo getenforce
58
SSH Configuration, UFW, and SELinux Commands Cheat Sheet
59
Deny a port sudo ufw deny 22 Denies traffic on
port 22.
Allow specific sudo ufw allow from 192.168.1.100 Allows traffic
IP from a specific IP
address.
Deny specific sudo ufw deny from 192.168.1.100 Denies traffic
IP from a specific IP
address.
Allow a port sudo ufw allow 3000:4000/tcp Allows traffic on
range a range of ports
(3000-4000) for
TCP.
Delete a rule sudo ufw delete allow 22 Deletes the rule
allowing traffic on
port 22.
SELinux
Commands
Check sestatus Displays the
SELinux current status and
status mode of SELinux.
Set SELinux sudo setenforce 0 Sets SELinux to
mode to permissive mode
permissive temporarily.
Set SELinux sudo setenforce 1 Sets SELinux to
mode to enforcing mode
enforcing temporarily.
Make sudo sed -i Sets SELinux to
's/SELINUX=enforcing/SELINUX=permissive/'
SELinux permissive mode
/etc/selinux/config
permissive permanently by
permanently editing the config
file.
Relabel sudo touch /.autorelabel && sudo reboot Forces SELinux
filesystem to relabel the
filesystem on next
reboot.
List SELinux sudo semanage policy -l Lists all loaded
policies SELinux policies.
Add SELinux sudo semanage port -a -t http_port_t -p Adds a port
tcp 8080
port context context for
SELinux (e.g.,
allowing HTTP
on port 8080).
Modify sudo setsebool -P Changes the state
httpd_can_network_connect on
SELinux of an SELinux
boolean boolean (e.g.,
allowing HTTPD
to connect to the
network).
60
Chapter 28: Case Studies and Real-world Applications
bash
#!/bin/bash
sudo apt-get update
sudo apt-get install -y apache2
sudo systemctl enable apache2
sudo systemctl start apache2
bash
#!/bin/bash
tar -czf /backup/home_$(date +%F).tar.gz /home/user
bash
#!/bin/bash
sudo apt-get install -y isc-dhcp-server
sudo systemctl enable isc-dhcp-server
sudo systemctl start isc-dhcp-server
Summary
This expanded section on System Administration covers essential topics with practical
examples and scripts. Each chapter includes detailed explanations, commands, cheat sheets,
diagrams, and real-world case studies to ensure a comprehensive understanding and
application of system administration tasks.
61
PART VI: Advanced Topics
Chapter 29: Advanced File System Management
• Configuring RAID
o Example Script: Configure RAID 1
bash
#!/bin/bash
sudo mdadm --create --verbose /dev/md0 --level=1 --raid-
devices=2 /dev/sdX /dev/sdY
sudo mkfs.ext4 /dev/md0
sudo mount /dev/md0 /mnt
o Explanation: mdadm creates a RAID array, mkfs.ext4 formats it, and mount
attaches it to the filesystem.
62
• LVM (Logical Volume Management)
o Example Script: Create and Manage LVM
bash
#!/bin/bash
sudo pvcreate /dev/sdX
sudo vgcreate vg0 /dev/sdX
sudo lvcreate -L 10G -n lv0 vg0
sudo mkfs.ext4 /dev/vg0/lv0
sudo mount /dev/vg0/lv0 /mnt
63
RAID and LVM Commands Cheat Sheet
64
Chapter 30: Kernel Tuning and Optimization
bash
#!/bin/bash
sudo sysctl -w vm.swappiness=10
sudo sysctl -w net.ipv4.tcp_rmem='4096 87380 6291456'
sudo sysctl -p
bash
#!/bin/bash
wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-
5.10.tar.xz
tar -xf linux-5.10.tar.xz
cd linux-5.10
make menuconfig
make -j$(nproc)
sudo make modules_install
sudo make install
65
sysctl Commands Cheat Sheet
66
Chapter 31: Virtualization and Containers
bash
#!/bin/bash
sudo apt-get install -y qemu-kvm libvirt-daemon-system libvirt-
clients bridge-utils
sudo systemctl enable libvirtd
sudo systemctl start libvirtd
sudo virsh list --all
bash
#!/bin/bash
sudo apt-get install -y docker.io
sudo systemctl start docker
sudo docker run hello-world
sudo docker ps -a
67
o Explanation: Install Docker, run a test container, and list containers.
bash
#!/bin/bash
sudo apt-get install -y docker-compose
cat > docker-compose.yml <<EOF
version: '3'
services:
web:
image: nginx
ports:
- "80:80"
EOF
sudo docker-compose up
68
Docker Commands Cheat Sheet
69
Chapter 32: High Availability and Load Balancing
bash
#!/bin/bash
sudo apt-get install -y haproxy
sudo tee /etc/haproxy/haproxy.cfg <<EOF
frontend http_front
bind *:80
default_backend http_back
backend http_back
balance roundrobin
server server1 192.168.1.2:80 check
server server2 192.168.1.3:80 check
EOF
sudo systemctl restart haproxy
70
• Configuring High Availability with Keepalived
o Example Script: Set Up Keepalived
bash
#!/bin/bash
sudo apt-get install -y keepalived
sudo tee /etc/keepalived/keepalived.conf <<EOF
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 101
advert_int 1
authentication {
auth_type PASS
auth_pass 1234
}
virtual_ipaddress {
192.168.1.100
}
}
EOF
sudo systemctl restart keepalived
71
Keepalived high availability diagram
bash
#!/bin/bash
sudo setenforce 1
sudo semanage fcontext -a -t httpd_sys_content_t
'/var/www/html(/.*)?'
sudo restorecon -R /var/www/html
o Explanation: Enable SELinux and set security contexts for web directories.
bash
#!/bin/bash
sudo apt-get install -y apparmor apparmor-utils
sudo aa-enforce /etc/apparmor.d/usr.sbin.nginx
sudo aa-status
bash
#!/bin/bash
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -j DROP
sudo iptables-save | sudo tee /etc/iptables/rules.v4
o Explanation: Create and save iptables rules for allowing SSH and HTTP
traffic while dropping all others.
72
SELinux Commands Cheat Sheet
73
Chapter 34: Troubleshooting and Optimization
bash
#!/bin/bash
sudo journalctl -u apache2
sudo journalctl --since "2023-01-01" --until "2023-01-31"
o Explanation: Use journalctl to view logs for specific services and time
ranges.
bash
#!/bin/bash
sudo apt-get install -y pcp
sudo systemctl start pmcd
sudo pmstat
bash
#!/bin/bash
sudo sysctl -w vm.dirty_ratio=10
sudo sysctl -w vm.dirty_background_ratio=5
sudo sysctl -p
74
Command Example Description
journalctl
Commands
View all logs journalctl Displays all logs from the
systemd journal.
View logs for a journalctl -u <unit_name> Displays logs for a specific
specific unit systemd unit (e.g., journalctl -
u nginx).
View logs by journalctl -p <priority> Displays logs of a specified
priority priority (e.g., journalctl -p
err).
View logs within journalctl --since "2021- Displays logs within a specific
01-01" --until "2021-01-02"
a time range time range.
Follow live logs journalctl -f Continuously displays new log
entries (similar to tail -f).
View kernel logs journalctl -k Displays only kernel log
messages.
View logs for the journalctl -b Displays logs from the current
current boot boot.
View logs for a journalctl -b -1 Displays logs from the previous
specific boot boot (use -2, -3, etc. for earlier
boots).
Clear all journal journalctl --vacuum-time=1s Deletes all journal logs older than
logs 1 second.
View logs for a journalctl _UID=<user_id> Displays logs for a specific user
specific user by UID.
75
Chapter 35: Real-life Applications and Case Studies
bash
#!/bin/bash
sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get autoremove -y
sudo reboot
bash
#!/bin/bash
sudo apt-get install -y nginx
sudo systemctl start nginx
sudo apt-get install -y certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com
sudo systemctl reload nginx
o Explanation: Steps to install and secure Nginx with SSL/TLS certificates from
Let's Encrypt.
76
• Case Study: Configuring a VPN Server
o Example Script: Install and Configure OpenVPN
bash
#!/bin/bash
sudo apt-get install -y openvpn easy-rsa
make-cadir ~/openvpn-ca
cd ~/openvpn-ca
source vars
./build-ca
./build-key-server server
./build-dh
openvpn --genkey --secret keys/ta.key
cd keys
sudo cp ca.crt server.crt server.key dh2048.pem ta.key
/etc/openvpn
sudo cp /usr/share/doc/openvpn/examples/sample-config-
files/server.conf.gz /etc/openvpn
cd /etc/openvpn
sudo gzip -d server.conf.gz
sudo systemctl start openvpn@server
sudo systemctl enable openvpn@server
Summary
This expanded section on Advanced Topics delves into sophisticated aspects of Linux
administration, providing practical scripts, explanations, commands, cheat sheets, diagrams,
and case studies. Each chapter equips readers with the necessary knowledge and tools to
handle complex system administration tasks effectively.
77
PART VII: Case Studies and Practical Examples
Chapter 36: Automating Daily System Tasks
bash
#!/bin/bash
crontab -l > mycron
echo "0 2 * * * /usr/bin/rsync -a /home/user/
/backup/home/user/" >> mycron
crontab mycron
rm mycron
bash
#!/bin/bash
df -h | mail -s "Disk Usage Report" [email protected]
free -m | mail -s "Memory Usage Report" [email protected]
o Explanation: This script checks disk and memory usage and emails the report
to the system admin.
78
Chapter 37: Network Administration
bash
#!/bin/bash
sudo apt-get install -y iftop
sudo iftop -n -B -i eth0
bash
#!/bin/bash
sudo apt-get install -y nmap
nmap -sP 192.168.1.0/24
o Explanation: This script installs nmap and scans the local network for active
hosts and open ports.
79
Chapter 38: Web Server Administration
bash
#!/bin/bash
sudo apt-get install -y apache2 mysql-server php libapache2-
mod-php php-mysql
sudo systemctl start apache2
sudo mysql_secure_installation
o Explanation: This script installs Apache, MySQL, and PHP, and secures the
MySQL installation.
bash
#!/bin/bash
sudo apt-get install -y certbot python-certbot-apache
sudo certbot --apache -d example.com
sudo systemctl reload apache2
o Explanation: This script uses Certbot to obtain and install a Let's Encrypt SSL
certificate for Apache.
80
LAMP Stack Commands Cheat Sheet and Certbot Commands Cheat Sheet
81
Chapter 39: Database Management
bash
#!/bin/bash
sudo mysql -e "SET GLOBAL innodb_buffer_pool_size = 2G;"
sudo mysql -e "SET GLOBAL query_cache_size = 256M;"
bash
#!/bin/bash
mysqldump -u root -p database_name > backup.sql
mysql -u root -p database_name < backup.sql
82
MySQL Optimization Commands Cheat Sheet and mysqldump Commands Cheat
Sheet
83
Chapter 40: Security and Compliance
bash
#!/bin/bash
sudo setenforce 1
sudo semanage fcontext -a -t httpd_sys_content_t
'/var/www/html(/.*)?'
sudo restorecon -R /var/www/html
o Explanation: This script enables SELinux and configures security contexts for
a web directory.
bash
#!/bin/bash
sudo sed -i 's/#PermitRootLogin yes/PermitRootLogin no/'
/etc/ssh/sshd_config
sudo sed -i 's/#PasswordAuthentication
yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo systemctl restart sshd
o Explanation: This script hardens SSH by disabling root login and password
authentication.
84
SELinux Commands Cheat Sheet and SSH Configuration Cheat Sheet
85
Chapter 41: Advanced Scripting and Automation
bash
#!/bin/bash
sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get autoremove -y
yaml
---
- hosts: all
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
86
apt-get Commands Cheat Sheet
Summary
This expanded section on Case Studies and Practical Examples provides comprehensive
scripts, explanations, commands, cheat sheets, and diagrams for various real-world scenarios
in Linux administration. Each chapter equips readers with practical knowledge and tools to
automate tasks, manage networks, administer web servers, handle databases, ensure security,
and utilize advanced scripting techniques effectively.
87
PART VIII: Cheat Sheets and Resources
Chapter 42: Basic Linux Commands Cheat Sheet
bash
ls -la
cd /path/to/directory
cp file1.txt file2.txt
mv file1.txt /path/to/destination/
rm file1.txt
chmod 755 script.sh
chown user:group file1.txt
88
Chapter 43: Advanced Linux Commands Cheat Sheet
bash
bash
#!/bin/bash
echo "Hello, World!"
for i in {1..5}; do
echo "Iteration $i"
done
if [ -f "file.txt" ]; then
echo "File exists."
fi
function greet {
echo "Hello, $1!"
}
greet "Alice"
89
grep, awk, sed Cheat Sheet
90
Chapter 45: Network Administration Cheat Sheet
bash
ping -c 4 example.com
traceroute example.com
netstat -tuln
nmap -sP 192.168.1.0/24
ssh [email protected]
bash
91
nmap SSH Cheat Sheet
92
Chapter 47: Security and Compliance Cheat Sheet
bash
iptables -L
firewall-cmd --list-all
fail2ban-client status
sudo setenforce 1
sudo vi /etc/ssh/sshd_config
bash
top
htop
iotop
vmstat 1
iostat -x 1
sar -u 1
93
iptables firewalld fail2ban Cheat Sheet
94
Chapter 49: Scripting and Automation Tools Cheat Sheet
bash
crontab -e
anacron -d
at now + 5 minutes
systemctl list-timers
95
Chapter 50: Additional Resources
Summary
This expanded section on Cheat Sheets and Resources provides detailed, quick reference
guides for a variety of Linux commands and tools, complete with scripts, explanations,
commands, cheat sheets, and diagrams for better understanding. Each chapter equips readers
with the essential commands and tools they need to efficiently manage and troubleshoot
Linux systems.
96
PART IX: Appendices
Chapter 51: Appendix A: Mathematical Foundations
• Subsections:
1. Basic Arithmetic and Algebra
▪ Explanation: Fundamental concepts of arithmetic and algebra relevant
to computing and scripting.
▪ Example:
bash
bash
bash
97
Chapter 52: Appendix B: Shell Scripting Reference
• Subsections:
1. Built-in Shell Variables
▪ Explanation: Common built-in shell variables and their uses.
▪ Example:
bash
bash
3. Regular Expressions
▪ Explanation: Use of regular expressions in shell scripting for pattern
matching.
▪ Example:
bash
Shell Variables Cheat Sheet and Shell Special Characters Cheat Sheet
98
Chapter 53: Appendix C: Linux Resources
• Subsections:
1. Books and Guides
▪ Explanation: Recommended books and guides for further reading on
Linux and shell scripting.
▪ Example:
▪ Books:
▪ "The Linux Command Line" by William Shotts
▪ "Linux Pocket Guide" by Daniel J. Barrett
2. Online Tutorials and Documentation
▪ Explanation: Useful websites and online resources for learning and
troubleshooting.
▪ Example:
▪ Websites:
▪ Linux Documentation Project
▪ Stack Overflow
3. Communities and Forums
▪ Explanation: Online communities and forums where users can ask
questions and share knowledge.
▪ Example:
▪ Communities:
▪ Reddit: r/linux
▪ LinuxQuestions.org
4. Linux Distributions
▪ Explanation: Overview of popular Linux distributions and their
specific uses.
▪ Example:
▪ Distributions:
▪ Ubuntu
▪ Fedora
▪ CentOS
99
Chapter 54: Appendix D: Glossary of Terms
• Subsections:
1. Linux Terminology
▪ Explanation: Definitions of common Linux terms and jargon.
▪ Example:
▪ Kernel: The core component of a Linux operating system,
managing hardware and system processes.
▪ Shell: The interface that allows users to interact with the
operating system via commands.
2. Scripting Terminology
▪ Explanation: Definitions of common scripting terms and jargon.
▪ Example:
▪ Script: A file containing a series of commands that are
executed by the shell.
▪ Variable: A storage location identified by a name that holds
data.
3. Networking Terms
▪ Explanation: Definitions of common networking terms used in Linux
networking.
▪ Example:
▪ IP Address: A unique string of numbers separated by periods
that identifies each computer using the Internet Protocol to
communicate over a network.
▪ Port: A communication endpoint used by applications to
exchange data.
4. System Administration Terms
▪ Explanation: Definitions of common system administration terms.
▪ Example:
▪ Daemon: A background process that runs continuously to
handle periodic service requests.
▪ Cron: A time-based job scheduler in Unix-like operating
systems.
Summary
This expanded section on Appendices provides detailed reference material to supplement the
core content of the book. Each chapter is designed to give readers quick access to essential
information, scripts, explanations, commands, cheat sheets, and diagrams, helping them to
deepen their understanding of Linux and shell scripting.
100
GitLab CI/CD and Shell Scripting Cheatsheet
101
tags Tags to tags: - docker
match jobs to
specific
runners
allow_failure Allows jobs allow_failure: true
to fail
without
failing the
pipeline
dependencies Specifies dependencies: - build
jobs that a
job depends
on
when Defines when: manual
when to run
the job
(on_success
, always,
manual)
retry Defines how retry: 2
many times
to retry a job
on failure
environment Defines environment: production
environment
for a job
$DEPLOY_PROXY_PASSWOR Environment proxy_password="$DEPLOY_PROXY_PASSWOR
D D"
variable
defined in
.gitlab-
ci.yml
if [ -n "$VAR" ] Checks if a if [ -n "$VAR" ]; then echo
"Defined"; fi
variable is
defined and
not null
if [ -z "$VAR" ] Checks if a if [ -z "$VAR" ]; then echo "Not
defined"; fi
variable is
not defined
or is null
echo Prints text to echo "Hello, World!"
the console
#!/bin/bash Shebang to #!/bin/bash (at the top of the script)
specify the
script
interpreter
chmod +x script.sh Makes a chmod +x deploy_script.sh
script
executable
./script.sh Executes a ./deploy_script.sh
script
102
apt-get update Updates the apt-get update
package list
apt-get install Installs a apt-get install -y git
package
export VAR=value Sets an export MY_VAR="value"
environment
variable in a
script
curl -O Downloads a curl -O http://example.com/file.txt
file from a
URL
tar -xzvf Extracts a tar -xzvf archive.tar.gz
tar.gz file
zip -r Creates a zip zip -r archive.zip folder/
archive
scp Copies files scp file.txt user@host:/path/
over SSH
ssh Connects to ssh user@host
a remote host
over SSH
nmap Scans nmap -sP 192.168.0.0/24
network for
hosts and
open ports
ping Checks ping google.com
connectivity
to a host
grep Searches for grep "pattern" file.txt
patterns in
text
sed Stream sed -i 's/old/new/g' file.txt
editor for
modifying
files
awk Text awk '{print $1}' file.txt
processing
and data
extraction
ps aux Lists running ps aux
processes
kill Kills a kill 1234
process by
PID
crontab -e Edits the crontab -e
cron jobs
crontab -l Lists the crontab -l
cron jobs
103
df -h Displays df -h
disk space
usage
du -sh Displays the du -sh /path/to/directory
size of a
directory
top Displays top
running
processes
and system
resource
usage
htop Interactive htop
process
viewer
free -h Displays free -h
memory
usage
ifconfig Displays ifconfig
network
configuration
netstat -tuln Displays netstat -tuln
active
network
connections
iptables Configures iptables -L
the IP packet
filter rules
chmod Changes file chmod 755 script.sh
permissions
chown Changes file chown user:group file.txt
owner and
group
ln -s Creates a ln -s /path/to/file /path/to/link
symbolic
link
find Searches for find /path -name "file.txt"
files and
directories
alias Creates a alias ll="ls -la"
shortcut for a
command
.bashrc Bash ~/.bashrc (edit to add aliases and
configuration environment variables)
file
.zshrc Zsh ~/.zshrc (edit to add aliases and environment
configuration variables)
file
vim Text editor vim file.txt
104
nano Text editor nano file.txt
less Views files less file.txt
one screen at
a time
tail -f Displays the tail -f /var/log/syslog
end of a file
and updates
as it grows
head Displays the head -n 10 file.txt
beginning of
a file
cat Concatenates cat file.txt
and displays
file contents
tee Reads from `echo "Hello"
standard
input and
writes to
standard
output and
files
105