Linux Commands Archive

If you ever need a quick reminder of the commands to check things on Linux systems, this post has you covered. Hope it helps you find what you’re looking for! I’ll keep this post updated — promise! The article covers commands mostly used in RHEL. – hope that does not matter. :/

Organized as:

1. Basic Commands

2. Essential File Management Commands

3. Text Management Commands

4. Essential System Management Commands

5. User and Group Management

6. Permissions Management

7. Configure Networking

8. Commands used to Manage Softwares

9. Managing Processes

10. Working with Systemd

11. Scheduling Tasks

12. Configuring Logging

13. Managing Storage

14. Managing Advanced Storage

15. Basic Kernal Management

16. Managing the Boot Process

17. Essential Troubleshooting Commands

18. Automation with Bash Shell Scripting

19. Configuring SSH

20. Managing Apache HTTP Services

21. Managing SELinux

22. Configuring Firewall

23. Accessing Network Storage

24. Configuring Time Services

25. Managing Containers


1. Basic Commands

CommandArgumentsUse Case / DescriptionImportant Notes
typepwdFinds out whether a command is a Bash internal command or executable file
whichlsFinds out where the shell will get a command from
timelsExecutes command and shows time information
/usr/bin/timelsRuns the external time command (different from internal)
echo$PATHShows contents of PATH variable
ls> /dev/nullRedirects STDOUT to null device
ls ilwehgi2> /dev/nullRedirects STDERR to null device
ls ilwehgi /etc2> /dev/null > outputSends errors to /dev/null and output to file
echo hello> outputOverwrites file contents
ls>> outputAppends output to file
ls -R /| lessShows recursive directory listing in pager
ls> /dev/tty1Redirects output to device file (requires root)
history(none)Shows command history
\!number(e.g., \!31)Executes command with specific number from history
history-d numberDeletes specific command from history
history-cClears current history
history-wWrites current history to history file
vim~/testfileOpens file in vim editor
env(none)Shows current environment variables
echo$LANGReads value of LANG variable
LANG=es_ES.UTF-8(variable assignment)Temporarily sets language to Spanish
manmanOpens man page of man command
manaproposOpens man page of apropos
sudomandbUpdates mandb database as rootmakewhatis command used in previous RHEL versions
pinfo‘(coreutils) ls invocation’Shows info page for ls command

Used Scenarios with Q/A:

QuestionsAnswers
Create a file named “practice.txt” and redirect the output of ls -l to itls -l > practice.txt
Append the current date to “practice.txt” without overwriting existing contentdate >> practice.txt
Use a pipe to count how many lines are in /etc/passwdcat /etc/passwd | wc -l
Create a shell variable named COLOR with value “blue” and display itCOLOR=”blue” && echo $COLOR
Use vim to create a file with 10 lines of text and save it as “testfile”vim testfile (press i, type 10 lines, Esc, :wq)
In vim, delete lines 3-5 from “testfile”In vim: :3,5d then :wq
In vim, replace all occurrences of “old” with “new” in the entire fileIn vim: :%s/old/new/g then :wq
Use history to find and re-execute the last command that contained “ls”Ctrl+R then type ls
Clear your entire command historyhistory -c && history -w
Use man to find which option for ls shows file sizes in human-readable formatman ls shows -h option
Search the man pages for commands related to “partition”man -k partition or apropos partition
Use grep to find all lines in /etc/passwd that contain “root”grep root /etc/passwd
Use grep to find lines in /etc/passwd that do NOT contain “nologin”grep -v nologin /etc/passwd
Create an alias called “ll” that runs “ls -l” and make it permanentalias ll=’ls -l’ and add to ~/.bashrc
Redirect both standard output and standard error of a command to /dev/nullcommand > /dev/null 2>&1
Use tab completion to quickly type a long filenameType partial filename and press Tab
Display the first 5 lines of /etc/passwdhead -5 /etc/passwd
Display the last 3 lines of /etc/passwdtail -3 /etc/passwd
Follow (monitor) new entries in /var/log/messages in real-timetail -f /var/log/messages
Find which command would be executed when you type “ls”which ls or type ls

2. Essential File Management Commands

CommandArgumentsUse Case / DescriptionImportant Notes
mount(none)Shows all mounted devices
df-hTShows disk space with human-readable format and filesystem type
cd(none)Changes to home directory
touchfile1Creates empty file
cd/Changes to root directory
cd/tmpChanges to /tmp directory
mkdirfilesCreates directory (relative path)
mkdir/home/$USER/filesCreates directory (absolute path)
rmdirfilesRemoves empty directory
pwd(none)Shows current directory
ls-lLong listing with file properties
ls-aShows all files including hidden
ls-lrtShows files sorted by modification time (newest last)
ls-dShows directory names, not contents
ls-RRecursively shows directory contents
touch.hiddenCreates hidden file
cp/etc/hosts /tmpCopies file to directory
cp-R /etc /tmpRecursively copies directory
cp-a ~ /tmpArchives copy preserving all attributes
cp-a /somedir/.\* /tmpCopies hidden files (gives errors for directories)
cp-a /somedir/ .Copies entire directory to current directory
cp-a /somedir/. .Copies all files (regular and hidden) to current directory
mvmyfile /tmpMoves file to directory
mkdir somefiles; mv somefiles /tmp(compound command)Creates then moves directory
mvmyfile mynewfileRenames file
rm-rf newfilesRecursively and forcefully removes directory
ln/etc/hosts .Creates hard link to file
ln-s /etc/hosts .Creates symbolic link to file
ln-s /home /tmpCreates symbolic link to directory
\ls-lShows ls output without alias (shows link properties)
tarcvf etc.tar /etcCreates tar archive
fileetc.tarAnalyzes file type
gzipetc.tarCompresses file
tartvf etc.tar.gzShows contents of compressed tar archive
tarxvf etc.tar.gz etc/hostsExtracts specific file from archive
gunzipetc.tar.gzDecompresses file
tarxvf etc.tar -C /tmp etc/passwdExtracts file to specific directory
tarcjvf homes.tar /homeCreates bzip2 compressed archive
rm-f \*gz \*tarRemoves all gz and tar files

Used Scenarios with Q/A:

QuestionsAnswers
/home/student/test/dir1/dir2mkdir -p /home/student/test/dir1/dir2
/etc/hosts to your home directory preserving all attributescp -a /etc/hosts ~/
/tmpmv ~/hosts /tmp/
/etc/passwd in your home directoryln /etc/passwd ~/passwd_link
/etc in your home directoryln -s /etc ~/etc_link
all files in /etc that start with ‘pass’ls -d /etc/pass*
all files in /etc that are exactly 3 characters longfind /etc -maxdepth 1 -name ‘???’
a tar archive of your home directory compressed with gziptar -czf home_backup.tar.gz ~/
the tar archive to /tmptar -xzf home_backup.tar.gz -C /tmp
the contents of the tar archive without extracting ittar -tzf home_backup.tar.gz
the test directory and all its contentsrm -rf /home/student/test
all files in /var/log that were modified in the last 2 daysfind /var/log -mtime -2
all .conf files from /etc to /tmpcp /etc/*.conf /tmp/
disk usage of your home directory in human-readable formatdu -h ~/
the filesystem type used for your root partitiondf -T /
a file with spaces in the name and practice manipulating ittouch ‘file with spaces.txt’ and mv ‘file with spaces.txt’ /tmp/
relative pathnames to navigate the directory structurecd ../somedir or cd ../../otherdir
absolute pathnames to perform operations from any locationcp /etc/hosts /tmp/ (from any location)
available disk space on all mounted filesystemsdf -h
the inode number of a filels -i filename

3. Text Management Commands

CommandArgumentsUse Case / DescriptionImportant Notes
less/etc/passwdOpens file in pager for easy reading
ps aux| lessSends command output to pager
cat/etc/passwdDumps file contents to screen
tac(mentioned)Shows file contents in reverse order
head-n 5 /etc/passwdShows first 5 lines of file
tail-n 2 /etc/passwdShows last 2 lines of file
tail-5 /etc/passwdShows last 5 lines (alternative syntax)
tail-f /var/log/messagesFollows (monitors) file in real time
head-n 11 /etc/passwd | tail -n 1Shows only line 11 of file
cut-d : -f 1 /etc/passwdFilters first field using colon delimiter
sort/etc/passwdSorts file contents
cut -f 1 -d : /etc/passwd| sortSorts first column of file
cut -f 3 -d : /etc/passwd| sort -nSorts third field numerically
du -h| sort -rnSorts disk usage with biggest files first
sort-k3 -t : /etc/passwdSorts third column using colon delimiter
ps aux| sort -k 4 -nSorts processes by memory usage
ps aux| wcCounts lines, words, characters in output
grepanna /etc/passwdSearches for text in file
grep^anna /etc/passwdSearches for lines starting with text
grepash$ /etc/passwdSearches for lines ending with text
grep‘^anna’ /etc/passwdUses escaping for regular expressions
grep-E ‘b.\+t’ regex.txtUses extended regular expressions
grep‘ \#’ /etc/servicesSearches for commented lines
grep-v ‘^\#’ /etc/servicesShows lines NOT starting with #
grep-v ‘^\#’ /etc/services -B 5Shows matching lines plus 5 before
grep-v -e ‘^\#’ -e ‘^$’ /etc/servicesExcludes comments and blank lines
awk-F : ‘{ print $4 }’ /etc/passwdPrints fourth field
awk-F : ‘/user/ { print $4 }’ /etc/passwdSearches for text and prints field
sed-n 5p /etc/passwdPrints fifth line of file
sed-i s/old-text/new-text/g ~/myfileReplaces text in file
sed-i -e ‘2d’ ~/myfileDeletes second line from file
sed-i -e ‘2d;20,25d’ ~/myfileDeletes lines 2 and 20-25

Used Scenarios with Q/A:

QuestionsAnswers
Use grep to find all lines in /etc/services that contain “http”grep http /etc/services
Use grep with regex to find lines starting with “ftp” in /etc/servicesgrep ‘^ftp’ /etc/services
Use cut to display only the usernames from /etc/passwdcut -d: -f1 /etc/passwd
Use sort to sort /etc/passwd by the third field numericallysort -t: -k3 -n /etc/passwd
Count how many user accounts can login with a shell in /etc/passwdgrep -c ‘/bin/bash\|/bin/sh’ /etc/passwd
Use awk to print the first and last fields of /etc/passwdawk -F: ‘{print $1, $NF}’ /etc/passwd
Use sed to replace “root” with “admin” in a test filesed -i ‘s/root/admin/g’ testfile
Display lines 10-20 of /etc/passwd using head and tailhead -20 /etc/passwd | tail -11
Find all files in /etc that contain the word “localhost”grep -r localhost /etc/ 2>/dev/null
Use regular expression to find IP addresses in a filegrep -E ‘([0-9]{1,3}\.){3}[0-9]{1,3}’ file
Sort the output of ps aux by memory usageps aux –sort=-%mem
Filter ps aux to show only processes owned by rootps aux | grep ‘^root’
Use wc to count words in /etc/hostswc -w /etc/hosts
Compare two files and show differencesdiff file1 file2
Use less to search for text in a large fileless /var/log/messages then /searchterm
Extract specific columns from command output using cutps aux | cut -c 1-80 (adjust columns as needed)
Use awk to calculate the total memory used by all processesps aux | awk ‘{sum += $4} END {print sum}’
Use sed to delete empty lines from a filesed -i ‘/^$/d’ file
Create a file with multiple columns and practice sorting by different columnsCreate file with: echo -e “3 apple\n1 banana\n2 cherry” > test.txt then sort -k2 test.txt
Use grep with context options to show lines before and after a matchgrep -A2 -B2 searchterm file

4. Essential System Management Commands

CommandArgumentsUse Case / DescriptionImportant Notes
sudo-iOpens root shell (for authorized users)
suOpens root shell (requires root password)
w(none)Shows logged in users and their terminals
chvt4Switches to virtual terminal 4
systemctlrebootReboots system properly
systemctlhaltHalts system
systemctlpoweroffPowers off system
echo b> /proc/sysrq-triggerEmergency reset (use only as last resort)
systemctlstatus sshdChecks if SSH service is running
ip a| grep ‘inet ‘Shows IP addresses
sshroot@192.168.4.220Connects to remote server as root
ssh-Y linda@server2Connects with X11 forwarding for GUI apps
ssh-vVerbose mode for debugging connections
ssh-p port user@hostSSH connection on non-default port
scp/etc/hosts server2:/tmpSecurely copies file to remote server
scproot@server2:/etc/passwd ~Copies file from remote server
scp-r server2:/etc/ /tmpRecursively copies directory
scp-P port file user@host:/pathSCP on non-default port (uppercase P)
sftpstudent@server2Opens secure FTP session
rsync-rSynchronizes recursively
rsync-lCopies symbolic links as links
rsync-pPreserves permissions
rsync-nDry run (no actual sync)
rsync-aArchive mode (preserves all)
rsync-AArchive mode plus ACLs
rsync-XSynchronizes SELinux context
ssh-keygen(none)Generates SSH key pair
ssh-copy-idserver2Copies public key to remote server
sed-i -e ’25d’ ~/.ssh/known_hostsRemoves line 25 from known_hosts file
tail-f /var/log/secureMonitors security logs in real-time

Used Scenarios with Q/A:

QuestionsAnswers
Generate SSH key pair without passphrasessh-keygen -t rsa -b 2048 -N “” -f ~/.ssh/id_rsa
Copy your public key to another serverssh-copy-id -i ~/.ssh/id_rsa.pub user@remote-server
Connect to another server using SSH without passwordssh -i ~/.ssh/id_rsa user@remote-server
Use scp to copy a file to a remote serverscp file.txt user@remote-server:/path/
Use scp to copy a directory recursively to a remote serverscp -r directory/ user@remote-server:/path/
Use sftp to transfer files interactivelysftp user@remote-server then use commands: put localfile, get remotefile, ls, exit
Configure SSH to use a different portEdit /etc/ssh/sshd_config: change #Port 22 to Port 2222, then systemctl restart sshd
Restrict SSH root login in SSH configurationEdit /etc/ssh/sshd_config: change PermitRootLogin yes to PermitRootLogin no
Use rsync to synchronize directories between two serversrsync -av /local/dir/ user@remote-server:/remote/dir/
Set up SSH X11 forwarding for graphical applicationsssh -X user@remote-server then run graphical commands
Switch between virtual terminals using keyboard shortcutsUse Ctrl+Alt+F2 through Ctrl+Alt+F6 for terminals, Ctrl+Alt+F1 for GUI
Reboot the system properly using systemctlsystemctl reboot or reboot
Shut down the system properly using systemctlsystemctl poweroff or poweroff
Monitor who is logged into the system and what they’re doingw or who
Force kill a frozen SSH session~. (tilde followed by period) in SSH session or find PID with ps aux | grep ssh then kill PID
Configure SSH to use key authentication only (disable passwords)Edit /etc/ssh/sshd_config: set PasswordAuthentication no and PubkeyAuthentication yes
Set up an SSH tunnel for port forwardingssh -L 8080:localhost:80 user@remote-server
Use w to see current system users and their activitiesEdit ~/.ssh/config:

Host myserver
Hostname server.example.com
User myuser
Port 2222
IdentityFile ~/.ssh/id_rsa
Configure SSH client options in ~/.ssh/configssh -v user@remote-server
Troubleshoot SSH connection issuesCheck: systemctl status sshd, ss -tlnp | grep :22, firewall-cmd –list-all

5. User and Group Management

CommandArgumentsUse Case / DescriptionImportant Notes
useraddusernameCreates a new user account
useradd-m -c “User Comment” usernameCreates user with home directory and comment
useradd-s /bin/bash usernameCreates user with specified shell
useradd-m -u UID -G groups usernameCreates user with home dir, UID, and groups
usermod-aG groupname usernameAdds user to supplementary group
usermod-L usernameLocks a user account
usermod-U usernameUnlocks a user account
userdel-r usernameDeletes user and their home directory
groupaddgroupnameCreates a new group
groupmod-n newname oldnameRenames a group
groupdelgroupnameDeletes a group
passwdusernameSets or changes user password
passwd-l usernameLocks user’s password
passwd-u usernameUnlocks user’s password
passwd-n min -w warn -x max usernameSets password aging policies
chage-l usernameLists password aging information
chage-M 90 usernameSets maximum password age to 90 days
chage-E YYYY-MM-DD usernameSets account expiration date
idusernameDisplays user and group information
su– usernameSwitches to another user’s environment
sudocommandExecutes command as another user (typically root)
visudo(none)Edits sudoers file safely
vipw(none)Safely edit /etc/passwd file
vigr(none)Safely edit /etc/group file
groupsusernameShows user’s group memberships
newgrpgroupnameChanges effective primary group temporarily
groupmems-g sales -lLists members of a specific group

Used Scenarios with Q/A:

QuestionsAnswers
Create a new user account with home directoryuseradd -m -c “Test User” testuser
Create a new group called “developers”groupadd developers
Add a user to the “developers” groupusermod -aG developers testuser
Set password aging policies for a user accountchage -M 90 -m 7 -W 14 testuser
Create a user without a home directoryuseradd -M -s /sbin/nologin systemuser
Delete a user account and their home directoryuserdel -r testuser
Modify a user’s login shellusermod -s /bin/csh username
Change a user’s primary groupusermod -g developers username
Lock and unlock a user accountpasswd -l username and passwd -u username
Configure sudo access for a user to run all commandsvisudo add: username ALL=(ALL) ALL
Configure sudo to allow a user to run specific commands onlyvisudo add: username ALL=(ALL) NOPASSWD: /bin/systemctl
Set up passwordless sudo for specific commandsvisudo add: username ALL=(ALL) NOPASSWD: /usr/bin/dnf
Check which groups a user belongs toid username or groups username
Set default user creation parametersuseradd -D to view, edit /etc/default/useradd
Modify user account expiration datechage -E 2024-12-31 username
Create a system account (no login, no home directory)useradd -r -s /sbin/nologin systemaccount
Change user’s UIDusermod -u 1500 username
Change group’s GIDgroupmod -g 1500 groupname
Force user to change password on next loginchage -d 0 username
Backup and restore user home directoriestar -czf user_backup.tar.gz /home/username and tar -xzf user_backup.tar.gz -C /

6. Permissions Management

CommandArgumentsUse Case / DescriptionImportant Notes
chmod755 fileSets rwx for owner, rx for group and others
chmodu+x fileAdds execute permission for owner
chmodg-w fileRemoves write permission for group
chmodo=r fileSets others’ permissions to read only
chmod-R 755 directoryRecursively sets permissions on directory
chmodg+w,o-r fileMultiple permission changes in one command
chmod-R a+X dirRecursively adds execute for directories only
chmodu+s fileSets SUID bit (run as owner)
chmodg+s dirSets SGID bit on directory (inherit group)
chmod+t dirSets sticky bit (only owner can delete)
chownuser:group fileChanges owner and group of file
chown-R user:group directoryRecursively changes owner and group
chownuser fileChanges file owner only
chown:group fileChanges file group only
chgrpgroup fileChanges group of file
umask022Sets default file creation mask
umask(none)Shows current umask setting
setfacl-m u:user:rw fileAdds ACL for user on file
setfacl-m g:group:r fileAdds ACL for group on file
setfacl-x u:user fileRemoves ACL for user from file
getfaclfileDisplays ACL of file
chattr+i fileMakes file immutable
chattr-i fileRemoves immutable attribute
lsattrfileLists file attributes
find/ -user lindaFinds all files owned by specific user
find/ -group usersFinds all files owned by specific group

Used Scenarios with Q/A:

QuestionAnswer
Set read, write, execute permissions for owner on a file using symbolic notationchmod u+rwx filename
Set permissions using octal notation (755, 644, etc.)chmod 755 filename (owner: rwx, group: r-x, others: r-x)
Change file ownership to a different userchown newuser filename
Change file group ownershipchgrp newgroup filename
Set the setuid bit on an executable filechmod u+s filename
Set the setgid bit on a directorychmod g+s directory
Set the sticky bit on a directorychmod +t directory
Set default file creation permissions using umaskumask 022 (files: 644, directories: 755)
Set ACL to give specific user read access to a filesetfacl -m u:username:r filename
Set ACL to give specific group write access to a directorysetfacl -m g:groupname:w directory
Remove specific ACL entries from a filesetfacl -x u:username filename
Set default ACL on a directorysetfacl -d -m g:groupname:rw directory
Check current permissions and ownership of filesls -la filename
Troubleshoot permission denied errorsCheck: ls -la, getfacl filename, verify user/group membership with id username
Recursively change permissions on a directory and its contentschmod -R 755 directory/
Find all setuid files on the systemfind / -perm -4000 2>/dev/null
Find all world-writable filesfind / -perm -o=w 2>/dev/null
Configure permissions to allow group collaboration on fileschmod g+rw shared_file and chgrp developers shared_file
Reset permissions to default valueschmod 644 file and chmod 755 directory (common defaults)
Verify and fix SELinux context on filesrestorecon -R /path/ for SELinux context

7. Configure Networking

CommandArgumentsUse Case / DescriptionImportant Notes
ipaddr showShows IP addresses and network interfaces
ipaddr add 192.168.1.100/24 dev eth0Adds IP address to interfaceEvery change you do using ip is not persistent therefore, use nmtui or nmcli
iproute showShows routing table
iproute add default via 192.168.1.1Adds default route
iplink showShows network link status
ip-s link showShows link statistics
nmclicon showShows NetworkManager connections
nmclicon show ens33Shows all properties of the ens33 connection
nmclicon add con-name “MyConn” type ethernet ifname eth0Adds new connectionExample 1 (dhcp) :
nmcli con add con-name testconn type ethernet ifname ens33 ipv4.method auto

Example 2 (static) :
nmcli con add con-name testconn1 ifname ens33 autoconnect no type ethern
et ipv4.addresses 192.168.199.199/24 gw4 192.168.199.2 ipv4.method manual
nmclicon mod “MyConn” ipv4.addresses 192.168.1.100/24Modifies connection’s IP addressExample 1 (Change Autoconnect) :
nmcli con mod testconn connection.autoconnect no

Example 2 (Change DNS) :
nmcli con mod testconn ipv4.dns 1.1.1.1

Example 3 (Add Second Item) :

nmcli con mod testconn +ipv4.dns 8.8.4.4

nmcli con mod testconn1 +ipv4.addresses 192.168.199.200/24
nmclicon up “MyConn”Activates a connection
nmclidev statusShows network device status
nmclidev show devicenameShows settings for specific device
nmcligeneral permissionsShows current network configuration permissions
nmcliconnection reload en33Reload connection files from disk related to en33
nmtui(none)Text-based UI for NetworkManager
nm-connection-editor(none)Opens the GUI network connection editor
ss-tulnShows listening TCP and UDP ports
ss-ltShows listening TCP ports
netstat(none)Shows active connectionsReplaced by ss command, and this command is mostly obsolete
ping-c 4 192.168.1.1Sends 4 ICMP echo requests to host
ping8.8.8.8Tests network connectivity
hostnamectlset-hostname server1.example.comSets system hostnameConfiguration file location:
/etc/hostname
hostnamectlstatusShows hostname and system information
getenthosts servernameVerifies hostname resolution
cat/etc/NetworkManager/system-connections/
ens160.nmconnection
Views NetworkManager Connection FileIn previous RHEL versions thy was under: /etc/sysconfig/network-scripts
systemctlstatus NetworkManagerShows NetworkManager service status
man5 nm-settingsShows man pages of how to do configuration using nmcli
mannmcli-examplesShows examples of nmcliYou do not need to remember the arguemtns to configure network settings – use this man pages
Configuration File PathUse CaseImportant Notes
/etc/NetworkManager/system-connections/NetworkManager Connection File – contains IP information
/etc/sysconfig/network-scriptsContains IP information – Used in old RHEL versionsNetworkManager uses the following directory:
/etc/NetworkManager/system-connections/
/etc/hostnameContains hostname information
/etc/hostsContains DNS information
/etc/nsswitch.confControls how and in what order system databases (like hosts, passwd, group) are looked upDo not edit this file manually
/etc/resolv.confDNS server configuration file

Used Scenarios with Q/A:

QuestionsAnswers
Configure static IP address using nmclinmcli con add type ethernet con-name static-eth ifname eth0 ip4 192.168.1.100/24 gw4 192.168.1.1
Configure DHCP using nmclinmcli con add type ethernet con-name dhcp-eth ifname eth0
Set system hostnamehostnamectl set-hostname server1.example.com
Configure DNS serversnmcli con mod static-eth ipv4.dns ‘8.8.8.8,8.8.4.4’
Add static host entries to /etc/hostsecho ‘192.168.1.50 server50’ >> /etc/hosts
Troubleshoot network connectivity using pingping -c 4 8.8.8.8 then traceroute 8.8.8.8
Check network interface configurationip addr show or nmcli con show
View routing tableip route show or route -n
Test port connectivity using telnet or ncnc -zv hostname port or telnet hostname port
Configure network bonding/teamingnmcli con add type bond con-name bond0 ifname bond0 bond.options mode=active-backup ip4 192.168.1.100/24 gw4 192.168.1.1
Restart network servicesystemctl restart NetworkManager
Configure network interface to start at bootnmcli con mod con-name connection.autoconnect yes
Change MTU size on network interfacenmcli con mod con-name 802-3-ethernet.mtu 1500
Configure multiple IP addresses on one interfacenmcli con mod con-name +ipv4.addresses ‘192.168.1.101/24’
Set up network routesip route add 10.0.0.0/8 via 192.168.1.1
Monitor network traffic and connectionsss -tuln or netstat -tuln
Configure firewall rules for specific servicesfirewall-cmd –add-service=http –permanent && firewall-cmd –reload
Troubleshoot DNS resolution issuesCheck: ping 8.8.8.8, nslookup google.com, cat /etc/resolv.conf
Configure network interface using nmtui (text UI)nmtui (interactive text UI)
Backup and restore network configurationcp -r /etc/NetworkManager/ ~/network-backup/

8. Commands used to Manage Softwares

CommandArgumentsUse Case / DescriptionImportant Notes
dnfinstall packageInstalls a package
dnfremove packageRemoves a package
dnfupdateUpdates all packages
dnfupdate packageUpdates specific package
dnfsearch keywordSearches for package by keyword
dnfsearch all keywordDeep search in package descriptions
dnfprovides */fileFinds package containing specific file
dnfinfo packageShows detailed package information
dnflist installedLists installed packages
dnflist availableLists available packages
dnflist packageShows installed and available versions
dnfrepolistShows configured repositories
dnfgroup listLists package groups
dnfgroupinstall “Group Name”Installs package group
dnfgroup info “Group Name”Shows package group contents
dnfhistoryShows transaction history
dnfhistory undo IDUndoes specific transaction
dnfclean allClears cached repository data
dnfconfig-manager –add-repo=URLAdds new repository
dnfmodule listLists available modules
dnfmodule info modulenameShows module information
dnfmodule install name:stream/profileInstalls module with specific stream/profile
rpm-qi packageQueries information about installed package
rpm-ql packageLists files in package
rpm-qf /path/to/fileQueries which package owns file
rpm-qc packageShows package configuration files
rpm-qd packageShows package documentation
rpm-q –scripts packageShows scripts in package
rpm-qp –scripts package.rpmShows scripts in package file (not installed)
rpm-qR packageShows package dependencies
rpm-V packageVerifies package integrity
rpm-VaVerifies all installed packages
rpm-qaLists all installed packages
subscription-managerregisterRegisters system with Red Hat
subscription-managerlist –availableLists available subscriptions
subscription-managerattach –autoAttaches available subscription
subscription-managerunregisterUnregisters system

Used Scenarios with Q/A:

QuestionsAnswers
Install a software package using dnfdnf install httpd
Remove a software package using dnfdnf remove httpd
Update all system packages using dnfdnf update
Search for available packagesdnf search python3
Show information about an installed packagednf info httpd
List all installed packagesdnf list installed or rpm -qa
Clean dnf cachednf clean all
Install a package groupdnf groupinstall “Development Tools”
Configure additional software repositoryCreate /etc/yum.repos.d/myrepo.repo:

[myrepo]
name=My Repository
baseurl=file:///path/to/repo
enabled=1
gpgcheck=0
Install local RPM packagednf install /path/to/package.rpm
Verify integrity of installed packagesrpm -V package-name
Check what package provides a specific filednf provides /usr/bin/python3
List files installed by a packagerpm -ql package-name
Check for available updatesdnf check-update
Downgrade a package to previous versiondnf downgrade package-name
Manage dnf history and undo transactionsdnf history then dnf history undo 3
Configure dnf to exclude certain packages from updatesecho “exclude=kernel*” >> /etc/dnf/dnf.conf
Set up automatic updatesdnf install dnf-automatic and configure /etc/dnf/automatic.conf
Work with module streamsdnf module list then dnf module enable nodejs:16
Troubleshoot package dependency issuesdnf deplist package-name to see dependencies

9. Managing Processes

CommandArgumentsUse Case / DescriptionImportant Notes
psauxShows all processes with detailed info
ps-efShows all processes in full format
psfaxShows process hierarchy tree
top(none)Interactive process viewer
htop(none)Enhanced interactive process viewer
killPIDSends TERM signal to process (graceful)
kill-9 PIDSends SIGKILL to process (force stop)
killallprocessnameKills processes by name
pkillprocessnameKills processes by name pattern
nice-n 10 commandStarts command with nice value of 10
renice-n 5 -p PIDChanges nice value of running process
renicevalue PIDChanges nice value (alternative syntax)
jobs(none)Lists background jobs in current shell
bg%1Resumes background job
fg%1Brings background job to foreground
tuned-admprofile profileSets system performance profile
tuned-admlistLists available tuned profiles
tuned-admactiveShows currently active tuned profile

Key Combinations

Key ComboUse Case / Description
Ctrl+ZSuspends current foreground job
Ctrl+CTerminates current job
Ctrl+DSends EOF (End Of File) signal
& (at end of command)Starts command in background
Alt+F1-F6Switches between virtual terminals
Ctrl+Alt+F1-F6Switches from GUI to text terminals

Used Scenarios with Q/A:

QuestionsAnswers
List all processes running on the systemps aux or ps -ef
Find processes using most CPUps aux –sort=-%cpu | head -10
Find processes using most memoryps aux –sort=-%mem | head -10
Kill a process by PIDkill 1234
Kill a process by namepkill process-name or killall process-name
Change process priority using nicenice -n 10 /path/to/command
Change priority of running process using renicerenice -n 10 -p 1234
Run process in backgroundlong-running-command &
Move process between foreground and backgroundfg %1 (bring to foreground), bg %1 (send to background)
List background jobsjobs
Use kill to send different signals to processeskill -1 1234 (HUP), kill -9 1234 (KILL), kill -15 1234 (TERM)
Monitor processes in real-timetop or htop
Find parent-child process relationshipsps -ef –forest or pstree
Identify zombie processesps aux | grep defunct or ps aux | awk ‘$8==”Z” {print $2}’
Set process CPU affinitytaskset -p 1234 (view), taskset -cp 0,1 1234 (set to CPUs 0,1)
Monitor system resource usagevmstat 1, iostat 1, mpstat 1
Configure process limits for usersulimit -a (view), edit /etc/security/limits.conf
Use pstree to view process hierarchypstree -p
Find which process is using a specific portss -tulnp | grep :80 or lsof -i :80
Manage services as processessystemctl status servicename

10. Working with Systemd

CommandArguments / OptionsUse Case / DescriptionImportant Notes
systemctlstart <unit>Starts a service/unit.
systemctlstop <unit>Stops a service/unit.
systemctlrestart <unit>Restarts a service/unit.
systemctlreload <unit>Reloads a service’s configuration.
systemctlenable <unit>Enables a unit to start automatically at boot.
systemctldisable <unit>Disables a unit from starting automatically at boot.
systemctlstatus <unit>Shows the current status of a unit.
systemctlstatus -l <unit>Shows detailed status information.
systemctllist-units -t serviceLists all active service units.
systemctllist-units -t service –allLists all service units, including inactive ones.
systemctl–failed -t serviceShows all services that have failed.
systemctl-t helpShows all available Systemd unit types.
systemctllist-dependencies <unit>Shows the dependencies of a specific unit.
systemctllist-dependencies –reverse <unit>Shows which units depend on a specific unit.
systemctlshow <unit>Shows all available configuration options for a unit.
systemctledit <unit>Creates an override file for a unit in /etc/systemd/system.
systemctlcat <unit>Displays the current, combined configuration of a unit.
systemctlmask <unit>Completely disables a unit, preventing manual and automatic start.
systemctlunmask <unit>Reverses the effect of mask.
systemctldaemon-reloadReloads Systemd manager configuration after changing unit files.
journalctl-u <unit>Shows logs for a specific Systemd unit.
journalctl-fFollows (tails) the journal.
systemd-analyze(none)Shows boot performance statistics.

Used Scenarios with Q/A:

QuestionsAnswers
Start a system servicesystemctl start httpd
Stop a system servicesystemctl stop httpd
Restart a system servicesystemctl restart httpd
Check status of a servicesystemctl status httpd
Enable service to start at bootsystemctl enable httpd
Disable service from starting at bootsystemctl disable httpd
Mask a service to prevent startingsystemctl mask httpd
Unmask a servicesystemctl unmask httpd
View system boot time and performancesystemd-analyze (boot time), systemd-analyze blame (service times)
Change default system target (runlevel)systemctl set-default multi-user.target
List all running servicessystemctl list-units –type=service –state=running
List all failed servicessystemctl –failed
View service dependenciessystemctl list-dependencies httpd
Analyze why a service failed to startjournalctl -u httpd and systemctl status httpd -l
Create a custom systemd serviceCreate /etc/systemd/system/myservice.service:

[Unit]
Description=My Custom Service
[Service]
ExecStart=/path/to/command
[Install]
WantedBy=multi-user.target
Configure service resource limitsAdd to service file: LimitNOFILE=65536
View service logs using journalctljournalctl -u servicename -f
Set service to restart on failureAdd to service file: Restart=on-failure
Work with systemd timersCreate /etc/systemd/system/mytimer.timer and .service files
Troubleshoot systemd service issuesjournalctl -u servicename –since “1 hour ago”

11. Scheduling Tasks

CommandArguments / OptionsUse Case / DescriptionImportant Notes
crontab-eEdits the current user’s crontab file.
crontab-lLists the current user’s crontab entries.
crontab-rDeletes the current user’s crontab.
crontab-u <username> -eEdits the crontab for a specific user (requires root).
atHH:MMSchedules a one-time job for a specific time. Opens an interactive shell.
atq(none)Lists pending at jobs.
atrm<job_id>Removes a scheduled at job.
systemctlstatus atdChecks the status of the at daemon.
systemctlenable crondEnables the cron daemon to start at boot.
systemctlstart crondStarts the cron daemon.
batch(none)Schedules a job to run when system load is low.

Used Scenarios with Q/A:

TaskCommand
Create a user cron job that runs dailycrontab -e add: 0 2 * * * /home/user/backup.sh
Create a system cron jobsudo vim /etc/crontab add: 0 2 * * * root /root/backup.sh
Schedule a one-time task using atecho “tar -czf /backup/backup.tar.gz /home” | at 02:00 tomorrow
List pending at jobsatq
Remove a scheduled at jobatrm 1
Configure cron to run every 5 minutes*/5 * * * * /path/to/script.sh
Configure cron to run on specific days of week0 2 * * 1 /path/to/script.sh
Redirect cron job output to a file0 2 * * * /path/to/script.sh > /var/log/script.log 2>&1
Set up cron job that runs during specific hours only0 9-17 * * * /path/to/script.sh
Configure email notification for cron jobsAdd MAILTO=user@example.com at top of crontab
Restrict cron access for usersecho “username” >> /etc/cron.deny
Backup cron configurationcrontab -l > cron-backup.txt
Troubleshoot why cron job didn’t runCheck: grep CRON /var/log/cron, verify script permissions, PATH
Set up anacron for missed jobsdnf install anacron, configure /etc/anacrontab
Create cron job that runs on first day of month0 0 1 * * /path/to/script.sh
Schedule system maintenance tasks0 2 * * * /usr/bin/updatedb (update locate database)
Monitor cron job executiontail -f /var/log/cron
Configure environment for cron jobsAdd to crontab: SHELL=/bin/bash, PATH=/usr/bin:/bin
Use systemd timers as cron alternativeCreate systemd timer as shown in Chapter 11
Set up log rotation for cron outputConfigure in /etc/logrotate.d/ for the log file

12. Configuring Logging

CommandArguments / OptionsUse Case / DescriptionImportant Notes
journalctl-fFollows (tails) the journal in real-time.
journalctl-u <unit>Shows logs for a specific Systemd unit.
journalctl–since “YYYY-MM-DD HH:MM:SS”Shows logs since a specific time.
journalctl–until “YYYY-MM-DD HH:MM:SS”Shows logs until a specific time.
journalctl-p <priority>Filters logs by priority (e.g., err, info, debug).
journalctl-bShows logs from the current boot only.
journalctl-xAdds explanation messages to the log output.
journalctl-o verboseShows log entries with all available fields.
journalctl_SYSTEMD_UNIT=<unit>Filters logs using specific fields (e.g., by unit).
tail-f /var/log/fileMonitors a log file in real-time.
logger“message”Writes a message to the syslog (and thus the journal).
logger-p <facility.priority> “message”Writes a message with a specific facility and priority.
CommandArguments / OptionsUse Case / Description
journalctl-fFollows (tails) the journal in real-time.
journalctl-u <unit>Shows logs for a specific Systemd unit.
journalctl–since “YYYY-MM-DD HH:MM:SS”Shows logs since a specific time.
journalctl–until “YYYY-MM-DD HH:MM:SS”Shows logs until a specific time.
journalctl-p <priority>Filters logs by priority (e.g., err, info, debug).
journalctl-bShows logs from the current boot only.
journalctl-xAdds explanation messages to the log output.
journalctl-o verboseShows log entries with all available fields.
journalctl_SYSTEMD_UNIT=<unit>Filters logs using specific fields (e.g., by unit).
tail-f /var/log/fileMonitors a log file in real-time.
logger“message”Writes a message to the syslog (and thus the journal).
logger-p <facility.priority> “message”Writes a message with a specific facility and priority.
rsyslogd-vShows the version of rsyslog.
logrotate-f /etc/logrotate.confForces log rotation to happen immediately.

Used Scenarios with Q/A:

QuestionsAnswers
Configure rsyslog to log to a specific filevim /etc/rsyslog.conf add: *.info /var/log/all.log
Set up log rotation for custom application logsCreate /etc/logrotate.d/myapp:

/var/log/myapp.log {
daily
rotate 7
compress
missingok
}
Use journalctl to view system logsjournalctl
Filter journal logs by time periodjournalctl –since “2024-01-01” –until “2024-01-02”
Filter journal logs by service/unitjournalctl -u httpd
Configure persistent journal storagemkdir -p /var/log/journal && systemctl restart systemd-journald
Clear journal logsjournalctl –vacuum-time=1d
Set log retention policyEdit /etc/systemd/journald.conf: SystemMaxUse=1G
Forward logs to remote servervim /etc/rsyslog.conf add: *.* @@remote-server:514
Search for specific error messages in logsjournalctl -p err or grep -i error /var/log/messages
Monitor logs in real-timejournalctl -f
Configure log level for specific servicesEdit service file or use journalctl -p debug
Create custom log filesvim /etc/rsyslog.conf add: local0.* /var/log/myapp.log
Analyze log file permissions and ownershipls -la /var/log/ and getfacl /var/log/messages
Troubleshoot logging issuesCheck: systemctl status rsyslog, disk space, permissions
Use logger to add custom entries to logslogger -p local0.info “Test message”
Configure log rate limitingEdit /etc/rsyslog.conf: $SystemLogRateLimitInterval 0 (disable)
Archive old log filesfind /var/log -name “*.gz” -o -name “*.1”
Set up log monitoring alertsgrep -i “error\|fail” /var/log/messages | mail -s “Errors” admin@example.com
Correlate logs from different servicesjournalctl -u httpd -u mariadb –since “1 hour ago”

13. Managing Storage

CommandArguments / OptionsUse Case / DescriptionImportant Notes
fdisk/dev/sdXPartitions a disk using the MBR partition table scheme.
gdisk/dev/sdXPartitions a disk using the GPT partition table scheme.
parted/dev/sdXA versatile partitioning tool.
parted/dev/sdX mklabel gptCreates a GPT partition table on a disk.
lsblk(none)Lists all block devices in a tree format.
blkid(none)Shows UUIDs, labels, and types of block devices.
mkfs-t xfs /dev/sdX1Creates an XFS filesystem on a partition.
mkfs.xfs/dev/sdX1Creates an XFS filesystem (the RHEL 9 default).
mkfs-t ext4 /dev/sdX1Creates an ext4 filesystem.
mkfs.ext4/dev/sdX1Creates an ext4 filesystem.
mount/dev/sdX1 /mntTemporarily mounts a filesystem.
mount-aMounts all filesystems defined in /etc/fstab.
umount/mnt or /dev/sdX1Unmounts a filesystem.
df-hShows disk space usage of mounted filesystems in human-readable format.
du-sh /pathShows disk usage of a specific directory.
tune2fs-l /dev/sdX1Shows properties and information of an ext2/3/4 filesystem.
xfs_admin-L <label> /dev/sdX1Sets a label on an XFS filesystem.
mkswap/dev/sdX1Formats a partition as swap space.
swapon/dev/sdX1Activates a swap partition.
swapoff/dev/sdX1Deactivates a swap partition.
findmnt–verifyVerifies the correctness of /etc/fstab before rebooting.

Used Scenarios with Q/A:

QuestionsAnswers
Create a new disk partition using fdiskfdisk /dev/sdb → n → p → 1 → Enter → Enter → w
Create a new disk partition using partedparted /dev/sdb mklabel gpt mkpart primary 0% 100%
Create XFS filesystem on a partitionmkfs.xfs /dev/sdb1
Create ext4 filesystem on a partitionmkfs.ext4 /dev/sdb1
Mount filesystem manuallymount /dev/sdb1 /mnt
Configure persistent mounts in /etc/fstabecho “/dev/sdb1 /mnt xfs defaults 0 0” >> /etc/fstab
Use filesystem UUID in fstabblkid /dev/sdb1 then use: UUID=xxx /mnt xfs defaults 0 0
Use filesystem label in fstabxfs_admin -L mylabel /dev/sdb1 then: LABEL=mylabel /mnt xfs defaults 0 0
Add swap space using a partitionmkswap /dev/sdc1 && swapon /dev/sdc1 add to fstab: /dev/sdc1 swap swap defaults 0 0
Add swap space using a filedd if=/dev/zero of=/swapfile bs=1M count=1024 && mkswap /swapfile && swapon /swapfile add to fstab: /swapfile swap swap defaults 0 0
Check filesystem integrityxfs_repair /dev/sdb1 or fsck.ext4 /dev/sdb1
Repair damaged filesystemxfs_repair -L /dev/sdb1 (force repair, may lose data)
Monitor disk space usagedf -h and du -sh /path
Extend existing filesystem (for non-LVM)For XFS: xfs_growfs /mountpoint, for ext4: resize2fs /dev/partition
Create encrypted filesystemcryptsetup luksFormat /dev/sdb1 then cryptsetup luksOpen /dev/sdb1 encrypted_vol
Backup and restore filesystemxfsdump -l 0 -f backup.xfsdump /dev/sdb1 and xfsrestore -f backup.xfsdump /mnt
Check disk health with SMARTsmartctl -a /dev/sda
Mount network filesystemsmount -t nfs server:/export /mnt
Set filesystem mount optionsmount -o noatime,nodiratime /dev/sdb1 /mnt
Troubleshoot mount issuesCheck: dmesg | grep sdb, mount, /etc/fstab syntax

14. Managing Advanced Storage

CommandArguments / OptionsUse Case / DescriptionImportant Notes
pvcreate/dev/sdX1Initializes a partition or disk as an LVM Physical Volume (PV).
pvs(none)Provides a summary of Physical Volumes.
pvdisplay(none)Provides detailed information about Physical Volumes.
vgcreatevg_name /dev/sdX1Creates a Volume Group (VG) named vg_name with an initial PV.
vgextendvg_name /dev/sdY1Adds a new PV to an existing VG.
vgreducevg_name /dev/sdY1Removes a PV from a VG (must be unused or data moved first).
vgs(none)Provides a summary of Volume Groups.
vgdisplay(none)Provides detailed information about Volume Groups.
lvcreate-L 10G -n lv_name vg_nameCreates a Logical Volume (LV) of 10GB.
lvcreate-l 50%FREE -n lv_name vg_nameCreates an LV using 50% of the free space in the VG.
lvextend-L +5G /dev/vg_name/lv_nameExtends an LV by 5GB.
lvextend / lvresize-r -L +5G /dev/vg_name/lv_nameExtends an LV and resizes the filesystem within it.
lvs(none)Provides a summary of Logical Volumes.
lvdisplay(none)Provides detailed information about Logical Volumes.
xfs_growfs/mount/pointGrows an XFS filesystem to the size of its underlying LV.
resize2fs/dev/vg_name/lv_nameResizes an ext4 filesystem to the size of its underlying LV.
pvmove/dev/sdY1 /dev/sdX1Moves data from one PV to another within the same VG.
stratispool create pool_name /dev/sdXCreates a Stratis pool on a block device.
stratisfs create pool_name fs_nameCreates a filesystem in a Stratis pool.
stratisfs listLists all Stratis filesystems.
stratisfilesystem snapshot pool_name origin_fs snapshot_fsCreates a snapshot of a Stratis filesystem.

Used Scenarios with Q/A:

QuestionsAnswers
Create physical volumepvcreate /dev/sdb
Create volume groupvgcreate myvg /dev/sdb
Create logical volumelvcreate -n mylv -L 10G myvg
Extend logical volumelvextend -L +5G /dev/myvg/mylv then xfs_growfs /dev/myvg/mylv
Reduce logical volumelvreduce -L -2G /dev/myvg/mylv (unmount and resize filesystem first)
Extend volume groupvgextend myvg /dev/sdc
Reduce volume groupvgreduce myvg /dev/sdc (move data first with pvmove)
Create snapshot of logical volumelvcreate –snapshot –name mysnap –size 1G /dev/myvg/mylv
Restore from snapshotlvconvert –merge /dev/myvg/mysnap
Move physical volume between volume groupspvmove /dev/sdb /dev/sdc then vgreduce myvg /dev/sdb
Monitor LVM statusvgs, pvs, lvs
Configure LVM thin provisioninglvcreate –type thin-pool -L 10G –name thin_pool myvg
Set up Stratis storage pooldnf install stratisd stratis-cli, systemctl enable –now stratisd, stratis pool create mypool /dev/sdb
Create Stratis filesystemstratis filesystem create mypool myfs
Extend Stratis filesystemstratis filesystem mypool/myfs then stratis pool add-data mypool /dev/sdc
Monitor Stratis storagestratis pool list, stratis filesystem list
Configure LVM cachinglvcreate –type cache -L 1G -n lvcache myvg /dev/slowlv /dev/fastpv
Backup LVM configurationvgcfgbackup myvg
Troubleshoot LVM issuesCheck: dmesg, /var/log/messages, LVM metadata with vgcfgrestore
Migrate data between storage systemsdd if=/dev/myvg/mylv of=/backup/lv_backup.img

15. Basic Kernal Management

CommandArguments / OptionsUse Case / DescriptionImportant Notes
uname-rShows the kernel release version.
uname-aShows all system information.
lsmod(none)Lists all currently loaded kernel modules.
modinfo<module_name>Shows detailed information about a kernel module.
modprobe<module_name>Loads a kernel module and its dependencies.
modprobe-r <module_name>Unloads a kernel module and its dependencies.
insmod/path/to/module.koLow-level command to insert a module (does not handle dependencies).
rmmod<module_name>Low-level command to remove a module (does not handle dependencies).
dmesg(none)Displays the kernel ring buffer (boot and kernel messages).
dmesg-TShows dmesg output with human-readable timestamps.
lspci-kLists PCI devices and shows the kernel driver in use for each.
udevadmmonitorMonitors the udev daemon for device events in real-time.

Used Scenarios with Q/A:

QuestionsAnswers
List loaded kernel moduleslsmod
Load kernel modulemodprobe module_name
Unload kernel modulemodprobe -r module_name
Check kernel module parametersmodinfo module_name
Set kernel module parametersCreate /etc/modprobe.d/mymodule.conf: options module_name param=value
List available kernel modulesfind /lib/modules/$(uname -r) -name “*.ko”
Check kernel versionuname -r
Check kernel boot parameterscat /proc/cmdline
Modify kernel parameters at runtimeecho “value” > /proc/sys/kernel/parameter or sysctl -w kernel.parameter=value
Blacklist kernel moduleecho “blacklist module_name” > /etc/modprobe.d/blacklist.conf
Update kerneldnf install kernel-* then reboot
Boot from different kernel versionSelect from GRUB menu or set default with grub2-set-default
Check hardware informationlspci, lsusb, lscpu
Monitor kernel messagesdmesg or journalctl –dmesg
Troubleshoot kernel issuesCheck: dmesg | grep -i error, remove problematic modules, use previous kernel
Configure kernel module dependenciesmodinfo module_name | grep depends
Create custom kernel modulednf install kernel-devel, write module code, compile with make
Check kernel ring bufferdmesg -w (follow)
Analyze system interruptscat /proc/interrupts
Monitor kernel performancevmstat 1, mpstat 1, pidstat 1

16. Managing the Boot Process

CommandArgumentsUse Case / DescriptionImportant Notes
systemctl –type=target–allList all targets (active/inactive)
systemctl isolaterescue.targetSwitch to rescue target immediately
systemctl get-defaultShow current default target
systemctl set-defaultmulti-user.targetSet default boot target
grub2-mkconfig-o /boot/grub2/grub.cfgRegenerate GRUB config (BIOS)
grub2-mkconfig-o /boot/efi/EFI/redhat/grub.cfgRegenerate GRUB config (UEFI)
grub2-install/dev/sdaReinstall GRUB bootloader
systemctl catmulti-user.targetView target unit file contents
grep Isolate*.targetFind targets that allow isolation
dnf group listList available package groups
dnf group install“server with gui”Install GUI packages

Used Scenarios with Q/A:

QuestionAnswer
Modify GRUB2 configurationvim /etc/default/grub add to GRUB_CMDLINE_LINUX, then grub2-mkconfig -o /boot/grub2/grub.cfg
Set default kernel boot entrygrub2-set-default 0 (0 for first entry)
Add kernel boot parametersvim /etc/default/grub add to GRUB_CMDLINE_LINUX=”rhgb quiet new_param”
Reinstall GRUB2 bootloadergrub2-install /dev/sda
Rebuild initramfsdracut -f or mkinitrd -f
Boot into rescue modeReboot, in GRUB edit kernel line, add systemd.unit=rescue.target
Boot into emergency modeReboot, in GRUB edit kernel line, add systemd.unit=emergency.target
Set default boot targetsystemctl set-default multi-user.target
Change systemd target at runtimesystemctl isolate multi-user.target
Troubleshoot boot failuresBoot from installation media, chroot /mnt/sysroot, reinstall GRUB, fix fstab
Recover from bootloader issuesBoot from live CD, mount root, chroot, grub2-install /dev/sda
Password protect GRUBgrub2-setpassword
Analyze boot performancesystemd-analyze, systemd-analyze blame, systemd-analyze critical-chain
Configure serial console for bootAdd console=ttyS0,115200 to kernel parameters
Backup boot configurationcp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.backup
Restore boot configurationRestore from backup or recreate from /etc/default/grub
Work with UEFI boot managerUse efibootmgr to manage UEFI entries
Set up dual boot configurationInstall both OS, configure GRUB to detect both
Monitor boot process messagesRemove rhgb quiet from kernel parameters, watch boot messages
Fix filesystem issues at bootBoot from rescue media, run fsck on affected partitions

17. Essential Troubleshooting Commands

CommandArgumentsUse Case / DescriptionImportant Notes
systemctlrescueBoots into rescue mode
systemctlemergencyBoots into emergency mode
journalctl-bShows logs from the current boot
journalctl -b -1Shows logs from the previous boot
systemctl list-unitsShow loaded units in rescue/emergency mode
systemctl show-environmentShow current shell environment variables
chroot/mnt/sysimageChange root to mounted system in rescue mode
dracut –forceRecreate initramfs
mount -o remount,rw/Remount root filesystem as read-write
passwdChange password (e.g., root password reset)
touch /.autorelabelTrigger SELinux relabel on next boot
exec /usr/lib/systemd/systemdReplace current shell with Systemd (after password reset)
fsck/dev/sdb1Check and repair filesystem
journalctl -xbShow boot logs with details
systemctl rebootReboot system

Used Scenarios with Q/A:

QuestionsAnswers
Reset forgotten root passwordReboot, edit kernel line adding rd.break, then:

chroot /sysroot
passwd root
touch /.autorelabel
exit twice
Repair corrupted filesystemumount /dev/sda1 (if mounted), then fsck /dev/sda1
Recover from kernel panicCheck logs, identify faulty driver/hardware, boot previous kernel
Fix network connectivity issuessystemctl restart NetworkManager, check cables, ip link show, nmcli con show
Restore broken package databaserpm –rebuilddb
Recover deleted filesUse testdisk, photorec, or restore from backup
Fix bootloader issuesBoot from installation media, chroot /mnt/sysroot, grub2-install /dev/sda, grub2-mkconfig
Troubleshoot service failuressystemctl status servicename, journalctl -u servicename, check dependencies
Diagnose performance issuestop, vmstat 1, iostat 1, identify resource bottlenecks
Fix permission problemsls -la, getfacl file, check user/group with id username
Recover from full filesystemdf -h, identify large files with du -sh /* 2>/dev/null | sort -hr, clean up
Troubleshoot hardware issuesdmesg | grep -i error, lspci, smartctl -a /dev/sda
Fix broken dependenciesdnf check, rpm -Va, reinstall broken packages
Recover from failed updatesBoot previous kernel, use dnf history undo
Diagnose memory issuesfree -h, cat /proc/meminfo, identify memory leaks
Fix corrupted configuration filesRestore from backup or recreate from documentation
Troubleshoot login issuesCheck PAM configuration, user shell, home directory permissions
Recover from accidental file deletionRestore from backup or use file recovery tools
Fix broken symbolic linksfind / -type l -! -exec test -e {} \; -print
Diagnose and fix security issuesgrep -r “password” /etc/ 2>/dev/null, check file permissions, audit logs

18. Automation with Bash Shell Scripting

CommandArgumentsUse Case / DescriptionImportant Notes
#!/bin/bash(shebang)Specify script interpreter
exit 0Exit script with success status
$1, $2, …Positional parameters (script arguments)
$#Number of arguments
$@All arguments
readVARIABLERead user input into variable
test -f fileCheck if file exists
[ -f file ]Alternative test syntax
$(command)Command substitution
if … then … fiConditional execution
for i in $@; do … doneLoop through arguments
for (( i=0; i<10; i++ )); do … doneArithmetic for loop
while condition; do … doneWhile loop
until condition; do … doneUntil loop
case $var in … esacCase statement
bash -xscript.shDebug script execution

Used Scenarios with Q/A:

QuestionsAnswers
Create script that displays system information!/bin/bash
echo “=== System Information ===”
echo “Hostname: $(hostname)”
echo “Kernel: $(uname -r)”
echo “Uptime: $(uptime -p)”
echo “Memory: $(free -h | grep Mem | awk ‘{print $3 “/” $2}’)”
echo “Disk: $(df -h / | awk ‘NR==2 {print $3 “/” $2 ” (” $5 “)”}’)”
Write script that backs up specific directories!/bin/bash
BACKUP_DIR=”/backup”
DATE=$(date +%Y%m%d)
tar -czf “$BACKUP_DIR/backup_$DATE.tar.gz” /home /etc
echo “Backup completed: $BACKUP_DIR/backup_$DATE.tar.gz”!/bin/bash
BACKUP_DIR=”/backup”
DATE=$(date +%Y%m%d)
tar -czf “$BACKUP_DIR/backup_$DATE.tar.gz” /home /etc
echo “Backup completed: $BACKUP_DIR/backup_$DATE.tar.gz”
Create script that monitors disk space and sends alerts!/bin/bash
THRESHOLD=80
USAGE=$(df / | awk ‘NR==2 {print $5}’ | sed ‘s/%//’)
if [ $USAGE -gt $THRESHOLD ]; then
echo “Warning: Root filesystem is ${USAGE}% full” | mail -s “Disk Alert” admin@example.com
fi
Write script that processes log files!/bin/bash
LOG_FILE=”/var/log/application.log”
ERRORS=$(grep -c “ERROR” “$LOG_FILE”)
if [ $ERRORS -gt 0 ]; then
echo “Found $ERRORS errors in $LOG_FILE”
grep “ERROR” “$LOG_FILE” | tail -10 > /tmp/recent_errors.txt
fi
Create script with command-line arguments!/bin/bash
echo “Script name: $0”
echo “First argument: $1”
echo “Second argument: $2”
echo “All arguments: $@”
echo “Number of arguments: $#”
Write script with conditional statements!/bin/bash
if [ -f “/etc/passwd” ]; then
echo “File exists”
else
echo “File does not exist”
fi
if [ $UID -eq 0 ]; then
echo “Running as root”
else
echo “Not running as root”
fi
Create script with loops!/bin/bash
For loop
for user in $(cut -d: -f1 /etc/passwd | head -5); do
echo “User: $user”
done
While loop
count=1
while [ $count -le 5 ]; do
echo “Count: $count”
((count++))
done
Write script that creates user accounts from file!/bin/bash
USER_FILE=”users.txt”
while IFS=: read -r username password; do
useradd -m “$username”
echo “$username:$password” | chpasswd
echo “Created user: $username”
done < “$USER_FILE”
Create script that monitors services!/bin/bash
SERVICES=(“httpd” “mariadb” “sshd”)
for service in “${SERVICES[@]}”; do
if systemctl is-active –quiet “$service”; then
echo “$service is running”
else
echo “$service is NOT running”
systemctl start “$service”
fi
done
Write script with functions!/bin/bash
log_message() {
echo “$(date): $1” >> /var/log/myscript.log
}
backup_files() {
tar -czf “$1” “$2”
}
log_message “Starting backup”
backup_files “/backup/home.tar.gz” “/home”
log_message “Backup completed”
Create script that handles errors!/bin/bash
set -e # Exit on any error
cleanup() {
echo “Cleaning up…”
rm -f /tmp/tempfile
}
trap cleanup EXIT
# Main script with error handling
if [ ! -d “$1” ]; then
echo “Error: Directory $1 does not exist” >&2
exit 1
fi
Write script that interacts with users!/bin/bash
read -p “Enter username: ” username
read -s -p “Enter password: ” password
echo
read -p “Enter shell [bash]: ” shell
shell=${shell:-bash}
useradd -m -s “/bin/$shell” “$username”
echo “$username:$password” | chpasswd
echo “User $username created”
Create script for system maintenance!/bin/bash
Cleanup temporary files
find /tmp -type f -mtime +7 -delete
Rotate logs
find /var/log -name “*.log” -mtime +30 -delete
Update package cache
dnf makecache
Write script that configures network!/bin/bash
INTERFACE=”eth0″
IP=”192.168.1.100″
NETMASK=”255.255.255.0″
GATEWAY=”192.168.1.1″
nmcli con add type ethernet con-name static-$INTERFACE ifname $INTERFACE \
ip4 $IP/$NETMASK gw4 $GATEWAY
nmcli con up static-$INTERFACE
Create script that installs software!/bin/bash
PACKAGES=(“httpd” “mariadb-server” “php”)
for pkg in “${PACKAGES[@]}”; do
if ! rpm -q “$pkg” &>/dev/null; then
dnf install -y “$pkg”
systemctl enable “$pkg”
fi
done
Write script for log rotation!/bin/bash
LOG_DIR=”/var/log/myapp”
find “$LOG_DIR” -name “.log” -mtime +7 -exec gzip {} \; find “$LOG_DIR” -name “.gz” -mtime +30 -delete
echo “Log rotation completed: $(date)” >> “$LOG_DIR/rotation.log”
Create script that generates reports!/bin/bash
echo “=== System Report ===” > /tmp/system_report.txt
echo “Date: $(date)” >> /tmp/system_report.txt
echo “Uptime: $(uptime)” >> /tmp/system_report.txt
echo “Memory: $(free -h)” >> /tmp/system_report.txt
echo “Disk: $(df -h)” >> /tmp/system_report.txt
echo “Top processes:” >> /tmp/system_report.txt
ps aux –sort=-%cpu | head -10 >> /tmp/system_report.txt
Write script with array processing!/bin/bash
FILES=(“/etc/passwd” “/etc/group” “/etc/hosts”)
for file in “${FILES[@]}”; do
echo “=== $file ===”
if [ -f “$file” ]; then
cat “$file”
else
echo “File not found”
fi
echo
done
Create script that uses regular expressions!/bin/bash
validate_ip() {
if [[ $1 =~ ^[0-9]+.[0-9]+.[0-9]+.[0-9]+$ ]]; then
return 0
else
return 1
fi
}
read -p “Enter IP address: ” ip
if validate_ip “$ip”; then
echo “Valid IP: $ip”
else
echo “Invalid IP: $ip”
fi
Write script for automated troubleshooting!/bin/bash
LOG_FILE=”/var/log/troubleshoot.log”
check_service() {
if ! systemctl is-active –quiet “$1”; then
echo “Service $1 is not running. Starting…” >> “$LOG_FILE”
systemctl start “$1”
fi
}
check_disk() {
USAGE=$(df / | awk ‘NR==2 {print $5}’ | sed ‘s/%//’)
if [ $USAGE -gt 90 ]; then
echo “Disk usage critical: ${USAGE}%” >> “$LOG_FILE”
fi
}
echo “Troubleshooting started: $(date)” > “$LOG_FILE”
check_service “sshd”
check_service “httpd”
check_disk
echo “Troubleshooting completed: $(date)” >> “$LOG_FILE”

19. Configuring SSH

CommandArgumentsUse Case / DescriptionImportant Notes
ssh-p 2022 user@hostConnect via non-default port
ssh-i ~/.ssh/key.pem user@hostConnect with specific private key
ssh-L 8080:localhost:80 user@hostLocal port forwarding
ssh-R 8080:localhost:80 user@hostRemote port forwarding
ssh-keygen-t rsa -b 4096Generate RSA key pair
ssh-copy-id-i ~/.ssh/key.pub user@hostCopy public key to host
ssh-agent/bin/bashStart SSH agent for current shell
ssh-addAdd private key passphrase to agent
semanage port-a -t ssh_port_t -p tcp 2022Add SELinux policy for custom SSH port
firewall-cmd–add-port=2022/tcpOpen custom SSH port in firewall

Used Scenarios with Q/A:

QuestionsAnswers
Configure SSH to use different portEdit /etc/ssh/sshd_config: change #Port 22 to Port 2222, then systemctl restart sshd, semanage port -a -t ssh_port_t -p tcp 2222, firewall-cmd –add-port=2222/tcp –permanent, firewall-cmd –reload
Disable root login over SSHEdit /etc/ssh/sshd_config: change PermitRootLogin yes to PermitRootLogin no
Configure key-based authenticationssh-keygen -t rsa -b 4096 -N “” -f ~/.ssh/id_rsa, ssh-copy-id -i ~/.ssh/id_rsa.pub user@host
Restrict SSH access to specific usersEdit /etc/ssh/sshd_config: add AllowUsers user1 user2 or AllowGroups sshusers
Configure SSH session timeoutEdit /etc/ssh/sshd_config: add ClientAliveInterval 300 and ClientAliveCountMax 2
Set up SSH tunnelingssh -L 8080:localhost:80 user@remote (local forward) or ssh -R 8080:localhost:80 user@remote (remote forward)
Configure SSH X11 forwardingEdit /etc/ssh/sshd_config: set X11Forwarding yes and on client use ssh -X user@host
Harden SSH configurationEdit /etc/ssh/sshd_config:

Protocol 2
PermitEmptyPasswords no
PasswordAuthentication no
PubkeyAuthentication yes
ChallengeResponseAuthentication no
UsePAM yes
PrintMotd no
Set up SSH jump hostssh -J jumpuser@jumpserver targetuser@target
Configure SSH bastion hostConfigure bastion in ~/.ssh/config:

Host bastion
Hostname bastion.example.com
User myuser
IdentityFile ~/.ssh/bastion_key

Host internal*
ProxyJump bastion
User internaluser
IdentityFile ~/.ssh/internal_key

Host internal1
Hostname 10.0.1.10

Host internal2
Hostname 10.0.1.11
Monitor SSH connectionsss -tlnp | grep :22, journalctl -u sshd -f
Troubleshoot SSH connection issuesCheck: ssh -v user@host, verify keys, permissions (~/.ssh/ should be 700, keys 600), firewall, SELinux
Configure SSH client optionsCreate ~/.ssh/config:

Host myserver
Hostname server.example.com
User myuser
Port 2222
IdentityFile ~/.ssh/mykey
ServerAliveInterval 60
Set up SSH for automated scriptsUse SSH keys in scripts: ssh -i /path/to/key user@host command
Configure SSH for port forwardingssh -L 3306:localhost:3306 user@dbserver (forward MySQL port)
Implement two-factor authentication for SSHUse Google Authenticator: dnf install google-authenticator, google-authenticator, edit /etc/pam.d/sshd and /etc/ssh/sshd_config
Configure SSH to use specific ciphersEdit /etc/ssh/sshd_config: Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
Set up SSH connection multiplexingEdit ~/.ssh/config:

Host *
ControlMaster auto
ControlPath ~/.ssh/%r@%h:%p
ControlPersist 600
Configure SSH to use different authentication methodsEdit /etc/ssh/sshd_config: AuthenticationMethods publickey,password publickey
Backup and restore SSH keystar -czf ssh-backup.tar.gz ~/.ssh/ /etc/ssh/

20. Managing Apache HTTP Services

CommandArgumentsUse Case / DescriptionImportant Notes
dnf installhttpdInstall Apache web server
systemctl enable –nowhttpdStart and enable Apache
systemctl statushttpdCheck Apache status
curlhttp://localhostTest web server from command line
httpd -tTest Apache configuration
apachectlstartStart Apache (legacy)
apachectlstopStop Apache (legacy)
apachectlrestartRestart Apache (legacy)
apachectlgracefulGraceful restart (legacy)
setenforce0Temporarily disable SELinux (for testing)

Used Scenarios with Q/A:

QuestionsAnswers
Install Apache web serverdnf install httpd
Start and enable Apache servicesystemctl start httpd && systemctl enable httpd
Configure virtual hostsCreate /etc/httpd/conf.d/vhost.conf:

<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/html/example
ErrorLog /var/log/httpd/example_error.log
CustomLog /var/log/httpd/example_access.log combined
</VirtualHost *:80>
Set up SSL/TLS for websitednf install mod_ssl, create SSL cert:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/pki/tls/private/apache.key -out /etc/pki/tls/certs/apache.crt,

configure in VirtualHost:

<VirtualHost *:443>
SSLEngine on
SSLCertificateFile /etc/pki/tls/certs/apache.crt SSLCertificateKeyFile /etc/pki/tls/private/apache.key </VirtualHost>
Configure directory access controlsIn VirtualHost or directory block:

<Directory “/var/www/html/secure”>
Require all denied
Require ip 192.168.1.0/24
</Directory>
Set up password protection for directoryhtpasswd -c /etc/httpd/.htpasswd username, then in VirtualHost:

<Directory “/var/www/html/secure”>
AuthType Basic
AuthName “Restricted Area”
AuthUserFile /etc/httpd/.htpasswd
Require valid-user
</Directory>
Configure custom error pagesErrorDocument 404 /errors/404.html and create the error page
Set up logging for virtual hostsIn VirtualHost: CustomLog /var/log/httpd/vhost_access.log combined
Configure PHP supportdnf install php php-mysqlnd
Set up CGI scriptsIn main config: ScriptAlias /cgi-bin/ “/var/www/cgi-bin/”
Configure virtual host aliasesServerAlias example.com *.example.com
Set up reverse proxyProxyPass “/app” “http://backend:8080/”, ProxyPassReverse “/app” “http://backend:8080/”
Configure load balancingBalancerMember http://backend1:8080 BalancerMember http://backend2:8080 ProxyPass “/app” “balancer://mycluster/”
Implement URL rewritingRewriteEngine On, RewriteRule ^oldpage$ newpage [R=301,L]
Set up web application firewalldnf install mod_security, configure in /etc/httpd/conf.d/mod_security.conf
Monitor web server performanceapachectl status, server-status page, ps aux | grep httpd
Troubleshoot web server issuesCheck: systemctl status httpd, journalctl -u httpd, apachectl configtest
Configure Apache modulesdnf install mod_php (for PHP), enable modules with a2enmod module_name
Set up virtual host for different portsListen 8080 in VirtualHost
Backup web server configurationtar -czf httpd-backup.tar.gz /etc/httpd/ /var/www/html/

21. Managing SELinux

CommandArgumentsUse Case / DescriptionImportant Notes
sestatus-vShows SELinux statusUse -v for detailed information
setenforce0Sets SELinux to permissive modeTemporary change only
setenforce1Sets SELinux to enforcing modeTemporary change only
getenforce(none)Gets the current SELinux modeShows enforcing/permissive/disabled
chcon-t httpd_sys_content_t /pathChanges SELinux context of file/directoryAvoid using – changes lost on relabel
semanagefcontext -a -t httpd_sys_content_t “/dir(/.*)?”Adds file context to policyRecommended method for context changes
restorecon-R -v /pathRestores default SELinux context recursivelyUse after semanage fcontext
semanageboolean -lLists SELinux booleansShows current and permanent settings
setsebool-P boolean_name on/offSets SELinux boolean persistently-P makes changes permanent
getsebool-aLists all SELinux booleansUse grep to filter results
sealert-l UUIDAnalyzes SELinux log messagesInstall setroubleshoot-server package
sepolicygenerateGenerates SELinux policies for applicationsAdvanced troubleshooting
ls-Z fileShows SELinux context of files 
ps -ZShows SELinux context of processes 

Used Scenarios with Q/A:

QuestionsAnswers
Check SELinux statussestatus
Set SELinux to enforcing modesetenforce 1
Set SELinux to permissive modesetenforce 0
View SELinux context of filesls -Z /etc/passwd
Change SELinux context of fileschcon -t httpd_sys_content_t /var/www/html/index.html
Restore default SELinux contextrestorecon -R /var/www/html/
Configure SELinux booleanssetsebool -P httpd_can_network_connect on
Troubleshoot SELinux denialssealert -a /var/log/audit/audit.log or ausearch -m avc -ts recent
Analyze SELinux audit logsausearch -m avc -ts today
Create custom SELinux policyaudit2allow -a to see suggested rules, audit2allow -a -M mypolicy to create module
Configure SELinux for web serversetsebool -P httpd_can_network_connect on, chcon -t httpd_sys_content_t /web/content
Configure SELinux for databasesetsebool -P mysql_connect_http on, chcon -t mysqld_db_t /var/lib/mysql/
Configure SELinux for network servicessemanage port -a -t http_port_t -p tcp 8080
Set SELinux context for custom applicationschcon -t bin_t /opt/myapp/bin/, semanage fcontext -a -t bin_t “/opt/myapp/bin(/.*)?”
Monitor SELinux eventstail -f /var/log/audit/audit.log | grep avc
Backup SELinux configurationtar -czf selinux-backup.tar.gz /etc/selinux/ /var/lib/selinux/
Troubleshoot SELinux issuesCheck: sealert -a /var/log/audit/audit.log, verify contexts, check booleans
Configure SELinux userssemanage user -l, semanage login -a -s user_u username
Set up SELinux policy modulesaudit2allow -M mypolicy, semodule -i mypolicy.pp
Implement SELinux in mixed environmentSet permissive mode during migration: setenforce 0, monitor logs, create policies

22. Configuring Firewall

CommandArgumentsUse Case / DescriptionImportant Notes
firewall-cmd–list-allLists all firewall rules for default zone
firewall-cmd–list-all –zone=zone_nameLists rules for specific zone
firewall-cmd–get-servicesLists all available services
firewall-cmd–add-service=service_nameAdds a service to firewallRuntime only
firewall-cmd–add-service=service_name –permanentAdds service permanentlyRequires –reload
firewall-cmd–remove-service=service_nameRemoves a service from firewall
firewall-cmd–add-port=port/protocolAdds a port to firewall
firewall-cmd–remove-port=port/protocolRemoves a port from firewall
firewall-cmd–runtime-to-permanentMakes runtime rules permanentAlternative to –permanent
firewall-cmd–reloadReloads firewall rulesActivates permanent changes
firewall-cmd–get-default-zoneShows current default zone
firewall-cmd–set-default-zone=zone_nameChanges default zone
firewall-cmd–get-zonesLists all available zones
firewall-cmd–list-all-zonesShows configuration for all zones

Used Scenarios with Q/A:

QuestionsAnswers
Check firewall statusfirewall-cmd –state
List all firewall rulesfirewall-cmd –list-all or firewall-cmd –list-all-zones
Open port for specific servicefirewall-cmd –add-port=80/tcp or firewall-cmd –add-service=http
Block specific IP addressfirewall-cmd –add-rich-rule=’rule family=”ipv4″ source address=”192.168.1.100″ reject’
Configure firewall zonesfirewall-cmd –get-zones, firewall-cmd –get-default-zone
Set default firewall zonefirewall-cmd –set-default-zone=public
Create custom firewall servicefirewall-cmd –new-service=myservice, firewall-cmd –service=myservice –add-port=8080/tcp
Configure rich rulesfirewall-cmd –add-rich-rule=’rule family=”ipv4″ source address=”192.168.1.0/24″ service name=”ssh” accept’
Set up port forwardingfirewall-cmd –add-forward-port=port=80:proto=tcp:toport=8080
Configure masqueradingfirewall-cmd –add-masquerade
Implement DMZ zonefirewall-cmd –new-zone=dmz, firewall-cmd –zone=dmz –add-interface=eth1
Monitor firewall activityfirewall-cmd –list-rich-rules, journalctl -u firewalld -f
Backup firewall configurationfirewall-cmd –runtime-to-permanent
Restore firewall configurationfirewall-cmd –reload
Troubleshoot firewall issuesCheck: systemctl status firewalld, firewall-cmd –state, verify services/ports
Configure time-based rulesfirewall-cmd –add-rich-rule=’rule family=”ipv4″ source address=”192.168.1.0/24″ port port=”22″ protocol=”tcp” accept’ with time constraints
Set up logging for firewall rulesfirewall-cmd –set-log-denied=all
Implement source NATfirewall-cmd –add-rich-rule=’rule family=”ipv4″ source address=”192.168.1.0/24″ masquerade’
Configure destination NATfirewall-cmd –add-forward-port=port=80:proto=tcp:toport=8080:toaddr=192.168.1.100
Set up firewall for specific applicationsCreate service definition for custom application ports

23. Accessing Network Storage

CommandArgumentsUse Case / DescriptionImportant Notes
mount-t nfs server:/share /mntMounts an NFS share
mountserver.example.com:/ /mntNFSv4 pseudo root mountMounts all shares
umount/mntUnmounts an NFS share
showmount-e serverShows exports on NFS serverMay not work through firewalls
systemctlstart nfs-serverStarts NFS server service
systemctlenable nfs-serverEnables NFS server service
systemctlstart autofsStarts automount service
systemctlenable autofsEnables automount service
firewall-cmd–add-service nfs –permanentOpens firewall for NFSAlso add rpc-bind and mountd

Used Scenarios with Q/A:

QuestionsAnswers
Mount NFS share manuallymount -t nfs server:/export /mnt/nfs
Configure persistent NFS mountsecho “server:/export /mnt/nfs nfs defaults 0 0” >> /etc/fstab
Set up automount for NFS sharesInstall autofs: dnf install autofs, configure /etc/auto.master and /etc/auto.nfs
Configure NFS exportsOn server: vim /etc/exports add: /export 192.168.1.0/24(rw,sync,no_root_squash), then exportfs -a
Secure NFS exports/export 192.168.1.0/24(rw,sync,no_root_squash,all_squash)
Mount SMB/CIFS sharemount -t cifs //server/share /mnt/smb -o username=user,password=pass
Configure automount for SMB sharesIn /etc/auto.master: /mnt/smb /etc/auto.smb –timeout=60
Set up iSCSI initiatordnf install iscsi-initiator-utils, iscsiadm -m discovery -t st -p target_ip, iscsiadm -m node -T iqn -p target_ip -l
Configure iSCSI persistent connectionsiscsiadm -m node -T iqn -p target_ip -o update -n node.startup -v automatic
Mount FTP sharecurlftpfs ftp://user:pass@server /mnt/ftp
Troubleshoot network storage issuesCheck: showmount -e server, rpcinfo -p server, network connectivity, firewall
Monitor network storage performanceiostat -x 1, nfsiostat
Configure storage authenticationFor iSCSI: configure CHAP in /etc/iscsi/iscsid.conf
Set up multipath storagednf install device-mapper-multipath, configure /etc/multipath.conf
Configure storage encryptioncryptsetup luksFormat /dev/sdb1 for encrypted storage
Backup network storage configurationtar -czf storage-config-backup.tar.gz /etc/fstab /etc/exports /etc/auto.*
Restore network storage accessRestore from backup or recreate configurations
Set up high availability storageConfigure DRBD or cluster-aware filesystems
Configure storage quotas on network sharesedquota -u username for user quotas on NFS
Monitor network storage usagedf -h, du -sh /mnt/nfs/*

24. Configuring Time Services

CommandArgumentsUse Case / DescriptionImportant Notes
timedatectl(none)Shows current time settingsRecommended command
timedatectlset-time “YYYY-MM-DD HH:MM:SS”Sets system time and date
timedatectlset-timezone TimezoneSets system timezone
timedatectllist-timezonesLists available timezones
timedatectlset-ntp true/falseEnables/disables NTP synchronization
date(none)Shows current date and time
date–date ‘@epoch_time’Converts epoch time to human readable
hwclock–systohcSyncs system time to hardware clock
hwclock–hctosysSyncs hardware time to system clock
chronycsourcesShows NTP sourcesFor chrony service
chronyctrackingShows NTP tracking information
tzselect(none)Interactive timezone selection

Used Scenarios with Q/A:

QuestionsAnswers
Check current system time and datedate and timedatectl
Set system timezonetimedatectl set-timezone America/New_York
Configure NTP time synchronizationdnf install chrony, systemctl enable –now chronyd
Set up chrony as NTP clientEdit /etc/chrony.conf:

server 0.rhel.pool.ntp.org iburst
server 1.rhel.pool.ntp.org iburst
server 2.rhel.pool.ntp.org iburst
server 3.rhel.pool.ntp.org iburst
Configure chrony with multiple time serversAdd multiple servers in /etc/chrony.conf as shown above
Set up local time serverEdit /etc/chrony.conf: add allow 192.168.1.0/24 and use local stratum 10
Troubleshoot time synchronizationchronyc sources -v, chronyc tracking, chronyc makestep
Monitor time service statussystemctl status chronyd, chronyc activity
Configure time service loggingEdit /etc/chrony.conf: set logdir /var/log/chrony
Set up time service for virtual machinesAdd clock=pit to kernel parameters for better time in VMs
Configure hardware clock synchronizationhwclock –systohc to sync hardware clock
Backup time service configurationtar -czf chrony-backup.tar.gz /etc/chrony.conf /var/lib/chrony/
Restore time service configurationRestore from backup or reconfigure
Troubleshoot time drift issueschronyc tracking check offset, chronyc makestep to force sync
Configure time service securityUse NTP authentication with keys in /etc/chrony.conf
Set up time service monitoringchronyc sourcestats, set up monitoring with Nagios/Zabbix
Configure time service for different timezonestimedatectl list-timezones, set per-user if needed
Implement redundant time serversConfigure multiple independent time sources
Monitor time service performancechronyc tracking check stability and offset
Troubleshoot certificate time validationCheck certificate validity dates with openssl x509 -in cert.pem -text | grep -A 2 -B 2 Validity

25. Managing Containers

CommandArgumentsUse Case / DescriptionImportant Notes
podmanrun -d –name name imageRuns container in background
podmanrun -it image /bin/shRuns container with interactive shell
podmanpsLists running containers
podmanps -aLists all containers
podmanstop containerStops a container
podmanstart containerStarts a container
podmanrestart containerRestarts a container
podmanrm containerRemoves a container
podmanimagesLists container images
podmanrmi imageRemoves container image
podmanpull imagePulls image from registry
podmanexec -it container /bin/shExecutes command in running container
podmaninspect image/containerShows detailed container/image info
podmansearch termSearches for container images
podmanlogin registryLogs into container registry
podmaninfoShows container environment info
podmanbuild -t name .Builds image from Containerfile
podmangenerate systemd –name container –filesGenerates systemd service file
skopeoinspect docker://imageInspects remote images without pulling
buildahbud -t image .Builds image from ContainerfileAlternative to podman build

Used Scenarios with Q/A:

QuestionsAnswers
Install container runtime (Podman)dnf install podman
Pull container image from registrypodman pull docker.io/nginx:latest
List available container imagespodman images
Run container in foregroundpodman run nginx:latest
Run container in backgroundpodman run -d –name mynginx nginx:latest
Execute commands in running containerpodman exec -it mynginx /bin/bash
Stop and remove containerspodman stop mynginx && podman rm mynginx
Create container from ContainerfileCreate Containerfile:

FROM docker.io/centos:8
RUN dnf install -y httpd
COPY index.html /var/www/html/
EXPOSE 80
CMD [“httpd”, “-DFOREGROUND”]

Then: podman build -t myapp .
Configure container networkingpodman run –network=host nginx or podman run -p 8080:80 nginx
Set up container storagepodman run -v /host/data:/container/data nginx
Manage container logspodman logs mynginx
Configure container resource limitspodman run –memory=512m –cpus=1.5 nginx
Set up container health checksCreate healthcheck in Containerfile:

HEALTHCHECK –interval=30s –timeout=3s \
CMD curl -f http://localhost/ || exit 1
Create container podpodman pod create –name mypod, podman run –pod mypod nginx
Configure container registriespodman login docker.io, configure registries in /etc/containers/registries.conf
Backup container datapodman commit mynginx mynginx-backup or podman export mynginx > backup.tar
Monitor container performancepodman stats mynginx, podman top mynginx
Troubleshoot container issuesCheck: podman logs mynginx, podman inspect mynginx, verify resources
Set up container as systemd serviceCreate /etc/systemd/system/container-myservice.service:

[Unit]
Description=My Container Service
[Service]
Restart=always
ExecStart=/usr/bin/podman run –name myservice myimage:latest
ExecStop=/usr/bin/podman stop myservice
[Install]
WantedBy=multi-user.target
Implement container security best practicesUse SELinux labels: podman run –security-opt label=type:container_t myapp, run as non-root, use trusted images

Author photo
Publication date:
Hi! I’m Shanuka, a skilled Network Engineer working for an IT-based company in Sri Lanka. I specialize in designing, implementing, and securing complex networks, with a keen interest in emerging technologies such as cloud computing, automation, and AI-driven system optimization.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.