
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:
2. Essential File Management Commands
4. Essential System Management Commands
8. Commands used to Manage Softwares
11. Scheduling Tasks
13. Managing Storage
17. Essential Troubleshooting Commands
18. Automation with Bash Shell Scripting
19. Configuring SSH
20. Managing Apache HTTP Services
21. Managing SELinux
1. Basic Commands
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
type | pwd | Finds out whether a command is a Bash internal command or executable file | |
which | ls | Finds out where the shell will get a command from | |
time | ls | Executes command and shows time information | |
/usr/bin/time | ls | Runs the external time command (different from internal) | |
echo | $PATH | Shows contents of PATH variable | |
ls | > /dev/null | Redirects STDOUT to null device | |
ls ilwehgi | 2> /dev/null | Redirects STDERR to null device | |
ls ilwehgi /etc | 2> /dev/null > output | Sends errors to /dev/null and output to file | |
echo hello | > output | Overwrites file contents | |
ls | >> output | Appends output to file | |
ls -R / | | less | Shows recursive directory listing in pager | |
ls | > /dev/tty1 | Redirects output to device file (requires root) | |
history | (none) | Shows command history | |
\!number | (e.g., \!31) | Executes command with specific number from history | |
history | -d number | Deletes specific command from history | |
history | -c | Clears current history | |
history | -w | Writes current history to history file | |
vim | ~/testfile | Opens file in vim editor | |
env | (none) | Shows current environment variables | |
echo | $LANG | Reads value of LANG variable | |
LANG=es_ES.UTF-8 | (variable assignment) | Temporarily sets language to Spanish | |
man | man | Opens man page of man command | |
man | apropos | Opens man page of apropos | |
sudo | mandb | Updates mandb database as root | makewhatis command used in previous RHEL versions |
pinfo | ‘(coreutils) ls invocation’ | Shows info page for ls command |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Create a file named “practice.txt” and redirect the output of ls -l to it | ls -l > practice.txt |
Append the current date to “practice.txt” without overwriting existing content | date >> practice.txt |
Use a pipe to count how many lines are in /etc/passwd | cat /etc/passwd | wc -l |
Create a shell variable named COLOR with value “blue” and display it | COLOR=”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 file | In 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 history | history -c && history -w |
Use man to find which option for ls shows file sizes in human-readable format | man 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 permanent | alias ll=’ls -l’ and add to ~/.bashrc |
Redirect both standard output and standard error of a command to /dev/null | command > /dev/null 2>&1 |
Use tab completion to quickly type a long filename | Type partial filename and press Tab |
Display the first 5 lines of /etc/passwd | head -5 /etc/passwd |
Display the last 3 lines of /etc/passwd | tail -3 /etc/passwd |
Follow (monitor) new entries in /var/log/messages in real-time | tail -f /var/log/messages |
Find which command would be executed when you type “ls” | which ls or type ls |
2. Essential File Management Commands
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
mount | (none) | Shows all mounted devices | |
df | -hT | Shows disk space with human-readable format and filesystem type | |
cd | (none) | Changes to home directory | |
touch | file1 | Creates empty file | |
cd | / | Changes to root directory | |
cd | /tmp | Changes to /tmp directory | |
mkdir | files | Creates directory (relative path) | |
mkdir | /home/$USER/files | Creates directory (absolute path) | |
rmdir | files | Removes empty directory | |
pwd | (none) | Shows current directory | |
ls | -l | Long listing with file properties | |
ls | -a | Shows all files including hidden | |
ls | -lrt | Shows files sorted by modification time (newest last) | |
ls | -d | Shows directory names, not contents | |
ls | -R | Recursively shows directory contents | |
touch | .hidden | Creates hidden file | |
cp | /etc/hosts /tmp | Copies file to directory | |
cp | -R /etc /tmp | Recursively copies directory | |
cp | -a ~ /tmp | Archives copy preserving all attributes | |
cp | -a /somedir/.\* /tmp | Copies 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 | |
mv | myfile /tmp | Moves file to directory | |
mkdir somefiles; mv somefiles /tmp | (compound command) | Creates then moves directory | |
mv | myfile mynewfile | Renames file | |
rm | -rf newfiles | Recursively and forcefully removes directory | |
ln | /etc/hosts . | Creates hard link to file | |
ln | -s /etc/hosts . | Creates symbolic link to file | |
ln | -s /home /tmp | Creates symbolic link to directory | |
\ls | -l | Shows ls output without alias (shows link properties) | |
tar | cvf etc.tar /etc | Creates tar archive | |
file | etc.tar | Analyzes file type | |
gzip | etc.tar | Compresses file | |
tar | tvf etc.tar.gz | Shows contents of compressed tar archive | |
tar | xvf etc.tar.gz etc/hosts | Extracts specific file from archive | |
gunzip | etc.tar.gz | Decompresses file | |
tar | xvf etc.tar -C /tmp etc/passwd | Extracts file to specific directory | |
tar | cjvf homes.tar /home | Creates bzip2 compressed archive | |
rm | -f \*gz \*tar | Removes all gz and tar files |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
/home/student/test/dir1/dir2 | mkdir -p /home/student/test/dir1/dir2 |
/etc/hosts to your home directory preserving all attributes | cp -a /etc/hosts ~/ |
/tmp | mv ~/hosts /tmp/ |
/etc/passwd in your home directory | ln /etc/passwd ~/passwd_link |
/etc in your home directory | ln -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 long | find /etc -maxdepth 1 -name ‘???’ |
a tar archive of your home directory compressed with gzip | tar -czf home_backup.tar.gz ~/ |
the tar archive to /tmp | tar -xzf home_backup.tar.gz -C /tmp |
the contents of the tar archive without extracting it | tar -tzf home_backup.tar.gz |
the test directory and all its contents | rm -rf /home/student/test |
all files in /var/log that were modified in the last 2 days | find /var/log -mtime -2 |
all .conf files from /etc to /tmp | cp /etc/*.conf /tmp/ |
disk usage of your home directory in human-readable format | du -h ~/ |
the filesystem type used for your root partition | df -T / |
a file with spaces in the name and practice manipulating it | touch ‘file with spaces.txt’ and mv ‘file with spaces.txt’ /tmp/ |
relative pathnames to navigate the directory structure | cd ../somedir or cd ../../otherdir |
absolute pathnames to perform operations from any location | cp /etc/hosts /tmp/ (from any location) |
available disk space on all mounted filesystems | df -h |
the inode number of a file | ls -i filename |
3. Text Management Commands
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
less | /etc/passwd | Opens file in pager for easy reading | |
ps aux | | less | Sends command output to pager | |
cat | /etc/passwd | Dumps file contents to screen | |
tac | (mentioned) | Shows file contents in reverse order | |
head | -n 5 /etc/passwd | Shows first 5 lines of file | |
tail | -n 2 /etc/passwd | Shows last 2 lines of file | |
tail | -5 /etc/passwd | Shows last 5 lines (alternative syntax) | |
tail | -f /var/log/messages | Follows (monitors) file in real time | |
head | -n 11 /etc/passwd | tail -n 1 | Shows only line 11 of file | |
cut | -d : -f 1 /etc/passwd | Filters first field using colon delimiter | |
sort | /etc/passwd | Sorts file contents | |
cut -f 1 -d : /etc/passwd | | sort | Sorts first column of file | |
cut -f 3 -d : /etc/passwd | | sort -n | Sorts third field numerically | |
du -h | | sort -rn | Sorts disk usage with biggest files first | |
sort | -k3 -t : /etc/passwd | Sorts third column using colon delimiter | |
ps aux | | sort -k 4 -n | Sorts processes by memory usage | |
ps aux | | wc | Counts lines, words, characters in output | |
grep | anna /etc/passwd | Searches for text in file | |
grep | ^anna /etc/passwd | Searches for lines starting with text | |
grep | ash$ /etc/passwd | Searches for lines ending with text | |
grep | ‘^anna’ /etc/passwd | Uses escaping for regular expressions | |
grep | -E ‘b.\+t’ regex.txt | Uses extended regular expressions | |
grep | ‘ \#’ /etc/services | Searches for commented lines | |
grep | -v ‘^\#’ /etc/services | Shows lines NOT starting with # | |
grep | -v ‘^\#’ /etc/services -B 5 | Shows matching lines plus 5 before | |
grep | -v -e ‘^\#’ -e ‘^$’ /etc/services | Excludes comments and blank lines | |
awk | -F : ‘{ print $4 }’ /etc/passwd | Prints fourth field | |
awk | -F : ‘/user/ { print $4 }’ /etc/passwd | Searches for text and prints field | |
sed | -n 5p /etc/passwd | Prints fifth line of file | |
sed | -i s/old-text/new-text/g ~/myfile | Replaces text in file | |
sed | -i -e ‘2d’ ~/myfile | Deletes second line from file | |
sed | -i -e ‘2d;20,25d’ ~/myfile | Deletes lines 2 and 20-25 |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
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/services | grep ‘^ftp’ /etc/services |
Use cut to display only the usernames from /etc/passwd | cut -d: -f1 /etc/passwd |
Use sort to sort /etc/passwd by the third field numerically | sort -t: -k3 -n /etc/passwd |
Count how many user accounts can login with a shell in /etc/passwd | grep -c ‘/bin/bash\|/bin/sh’ /etc/passwd |
Use awk to print the first and last fields of /etc/passwd | awk -F: ‘{print $1, $NF}’ /etc/passwd |
Use sed to replace “root” with “admin” in a test file | sed -i ‘s/root/admin/g’ testfile |
Display lines 10-20 of /etc/passwd using head and tail | head -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 file | grep -E ‘([0-9]{1,3}\.){3}[0-9]{1,3}’ file |
Sort the output of ps aux by memory usage | ps aux –sort=-%mem |
Filter ps aux to show only processes owned by root | ps aux | grep ‘^root’ |
Use wc to count words in /etc/hosts | wc -w /etc/hosts |
Compare two files and show differences | diff file1 file2 |
Use less to search for text in a large file | less /var/log/messages then /searchterm |
Extract specific columns from command output using cut | ps aux | cut -c 1-80 (adjust columns as needed) |
Use awk to calculate the total memory used by all processes | ps aux | awk ‘{sum += $4} END {print sum}’ |
Use sed to delete empty lines from a file | sed -i ‘/^$/d’ file |
Create a file with multiple columns and practice sorting by different columns | Create 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 match | grep -A2 -B2 searchterm file |
4. Essential System Management Commands
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
sudo | -i | Opens root shell (for authorized users) | |
su | – | Opens root shell (requires root password) | |
w | (none) | Shows logged in users and their terminals | |
chvt | 4 | Switches to virtual terminal 4 | |
systemctl | reboot | Reboots system properly | |
systemctl | halt | Halts system | |
systemctl | poweroff | Powers off system | |
echo b | > /proc/sysrq-trigger | Emergency reset (use only as last resort) | |
systemctl | status sshd | Checks if SSH service is running | |
ip a | | grep ‘inet ‘ | Shows IP addresses | |
ssh | root@192.168.4.220 | Connects to remote server as root | |
ssh | -Y linda@server2 | Connects with X11 forwarding for GUI apps | |
ssh | -v | Verbose mode for debugging connections | |
ssh | -p port user@host | SSH connection on non-default port | |
scp | /etc/hosts server2:/tmp | Securely copies file to remote server | |
scp | root@server2:/etc/passwd ~ | Copies file from remote server | |
scp | -r server2:/etc/ /tmp | Recursively copies directory | |
scp | -P port file user@host:/path | SCP on non-default port (uppercase P) | |
sftp | student@server2 | Opens secure FTP session | |
rsync | -r | Synchronizes recursively | |
rsync | -l | Copies symbolic links as links | |
rsync | -p | Preserves permissions | |
rsync | -n | Dry run (no actual sync) | |
rsync | -a | Archive mode (preserves all) | |
rsync | -A | Archive mode plus ACLs | |
rsync | -X | Synchronizes SELinux context | |
ssh-keygen | (none) | Generates SSH key pair | |
ssh-copy-id | server2 | Copies public key to remote server | |
sed | -i -e ’25d’ ~/.ssh/known_hosts | Removes line 25 from known_hosts file | |
tail | -f /var/log/secure | Monitors security logs in real-time |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Generate SSH key pair without passphrase | ssh-keygen -t rsa -b 2048 -N “” -f ~/.ssh/id_rsa |
Copy your public key to another server | ssh-copy-id -i ~/.ssh/id_rsa.pub user@remote-server |
Connect to another server using SSH without password | ssh -i ~/.ssh/id_rsa user@remote-server |
Use scp to copy a file to a remote server | scp file.txt user@remote-server:/path/ |
Use scp to copy a directory recursively to a remote server | scp -r directory/ user@remote-server:/path/ |
Use sftp to transfer files interactively | sftp user@remote-server then use commands: put localfile, get remotefile, ls, exit |
Configure SSH to use a different port | Edit /etc/ssh/sshd_config: change #Port 22 to Port 2222, then systemctl restart sshd |
Restrict SSH root login in SSH configuration | Edit /etc/ssh/sshd_config: change PermitRootLogin yes to PermitRootLogin no |
Use rsync to synchronize directories between two servers | rsync -av /local/dir/ user@remote-server:/remote/dir/ |
Set up SSH X11 forwarding for graphical applications | ssh -X user@remote-server then run graphical commands |
Switch between virtual terminals using keyboard shortcuts | Use Ctrl+Alt+F2 through Ctrl+Alt+F6 for terminals, Ctrl+Alt+F1 for GUI |
Reboot the system properly using systemctl | systemctl reboot or reboot |
Shut down the system properly using systemctl | systemctl poweroff or poweroff |
Monitor who is logged into the system and what they’re doing | w 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 forwarding | ssh -L 8080:localhost:80 user@remote-server |
Use w to see current system users and their activities | Edit ~/.ssh/config:Host myserver |
Configure SSH client options in ~/.ssh/config | ssh -v user@remote-server |
Troubleshoot SSH connection issues | Check: systemctl status sshd, ss -tlnp | grep :22, firewall-cmd –list-all |
5. User and Group Management
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
useradd | username | Creates a new user account | |
useradd | -m -c “User Comment” username | Creates user with home directory and comment | |
useradd | -s /bin/bash username | Creates user with specified shell | |
useradd | -m -u UID -G groups username | Creates user with home dir, UID, and groups | |
usermod | -aG groupname username | Adds user to supplementary group | |
usermod | -L username | Locks a user account | |
usermod | -U username | Unlocks a user account | |
userdel | -r username | Deletes user and their home directory | |
groupadd | groupname | Creates a new group | |
groupmod | -n newname oldname | Renames a group | |
groupdel | groupname | Deletes a group | |
passwd | username | Sets or changes user password | |
passwd | -l username | Locks user’s password | |
passwd | -u username | Unlocks user’s password | |
passwd | -n min -w warn -x max username | Sets password aging policies | |
chage | -l username | Lists password aging information | |
chage | -M 90 username | Sets maximum password age to 90 days | |
chage | -E YYYY-MM-DD username | Sets account expiration date | |
id | username | Displays user and group information | |
su | – username | Switches to another user’s environment | |
sudo | command | Executes 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 | |
groups | username | Shows user’s group memberships | |
newgrp | groupname | Changes effective primary group temporarily | |
groupmems | -g sales -l | Lists members of a specific group |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Create a new user account with home directory | useradd -m -c “Test User” testuser |
Create a new group called “developers” | groupadd developers |
Add a user to the “developers” group | usermod -aG developers testuser |
Set password aging policies for a user account | chage -M 90 -m 7 -W 14 testuser |
Create a user without a home directory | useradd -M -s /sbin/nologin systemuser |
Delete a user account and their home directory | userdel -r testuser |
Modify a user’s login shell | usermod -s /bin/csh username |
Change a user’s primary group | usermod -g developers username |
Lock and unlock a user account | passwd -l username and passwd -u username |
Configure sudo access for a user to run all commands | visudo add: username ALL=(ALL) ALL |
Configure sudo to allow a user to run specific commands only | visudo add: username ALL=(ALL) NOPASSWD: /bin/systemctl |
Set up passwordless sudo for specific commands | visudo add: username ALL=(ALL) NOPASSWD: /usr/bin/dnf |
Check which groups a user belongs to | id username or groups username |
Set default user creation parameters | useradd -D to view, edit /etc/default/useradd |
Modify user account expiration date | chage -E 2024-12-31 username |
Create a system account (no login, no home directory) | useradd -r -s /sbin/nologin systemaccount |
Change user’s UID | usermod -u 1500 username |
Change group’s GID | groupmod -g 1500 groupname |
Force user to change password on next login | chage -d 0 username |
Backup and restore user home directories | tar -czf user_backup.tar.gz /home/username and tar -xzf user_backup.tar.gz -C / |
6. Permissions Management
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
chmod | 755 file | Sets rwx for owner, rx for group and others | |
chmod | u+x file | Adds execute permission for owner | |
chmod | g-w file | Removes write permission for group | |
chmod | o=r file | Sets others’ permissions to read only | |
chmod | -R 755 directory | Recursively sets permissions on directory | |
chmod | g+w,o-r file | Multiple permission changes in one command | |
chmod | -R a+X dir | Recursively adds execute for directories only | |
chmod | u+s file | Sets SUID bit (run as owner) | |
chmod | g+s dir | Sets SGID bit on directory (inherit group) | |
chmod | +t dir | Sets sticky bit (only owner can delete) | |
chown | user:group file | Changes owner and group of file | |
chown | -R user:group directory | Recursively changes owner and group | |
chown | user file | Changes file owner only | |
chown | :group file | Changes file group only | |
chgrp | group file | Changes group of file | |
umask | 022 | Sets default file creation mask | |
umask | (none) | Shows current umask setting | |
setfacl | -m u:user:rw file | Adds ACL for user on file | |
setfacl | -m g:group:r file | Adds ACL for group on file | |
setfacl | -x u:user file | Removes ACL for user from file | |
getfacl | file | Displays ACL of file | |
chattr | +i file | Makes file immutable | |
chattr | -i file | Removes immutable attribute | |
lsattr | file | Lists file attributes | |
find | / -user linda | Finds all files owned by specific user | |
find | / -group users | Finds all files owned by specific group |
Used Scenarios with Q/A:
Question | Answer |
---|---|
Set read, write, execute permissions for owner on a file using symbolic notation | chmod 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 user | chown newuser filename |
Change file group ownership | chgrp newgroup filename |
Set the setuid bit on an executable file | chmod u+s filename |
Set the setgid bit on a directory | chmod g+s directory |
Set the sticky bit on a directory | chmod +t directory |
Set default file creation permissions using umask | umask 022 (files: 644, directories: 755) |
Set ACL to give specific user read access to a file | setfacl -m u:username:r filename |
Set ACL to give specific group write access to a directory | setfacl -m g:groupname:w directory |
Remove specific ACL entries from a file | setfacl -x u:username filename |
Set default ACL on a directory | setfacl -d -m g:groupname:rw directory |
Check current permissions and ownership of files | ls -la filename |
Troubleshoot permission denied errors | Check: ls -la, getfacl filename, verify user/group membership with id username |
Recursively change permissions on a directory and its contents | chmod -R 755 directory/ |
Find all setuid files on the system | find / -perm -4000 2>/dev/null |
Find all world-writable files | find / -perm -o=w 2>/dev/null |
Configure permissions to allow group collaboration on files | chmod g+rw shared_file and chgrp developers shared_file |
Reset permissions to default values | chmod 644 file and chmod 755 directory (common defaults) |
Verify and fix SELinux context on files | restorecon -R /path/ for SELinux context |
7. Configure Networking
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
ip | addr show | Shows IP addresses and network interfaces | |
ip | addr add 192.168.1.100/24 dev eth0 | Adds IP address to interface | Every change you do using ip is not persistent therefore, use nmtui or nmcli |
ip | route show | Shows routing table | |
ip | route add default via 192.168.1.1 | Adds default route | |
ip | link show | Shows network link status | |
ip | -s link show | Shows link statistics | |
nmcli | con show | Shows NetworkManager connections | |
nmcli | con show ens33 | Shows all properties of the ens33 connection | |
nmcli | con add con-name “MyConn” type ethernet ifname eth0 | Adds new connection | Example 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 |
nmcli | con mod “MyConn” ipv4.addresses 192.168.1.100/24 | Modifies connection’s IP address | Example 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 |
nmcli | con up “MyConn” | Activates a connection | |
nmcli | dev status | Shows network device status | |
nmcli | dev show devicename | Shows settings for specific device | |
nmcli | general permissions | Shows current network configuration permissions | |
nmcli | connection reload en33 | Reload 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 | -tuln | Shows listening TCP and UDP ports | |
ss | -lt | Shows listening TCP ports | |
netstat | (none) | Shows active connections | Replaced by ss command, and this command is mostly obsolete |
ping | -c 4 192.168.1.1 | Sends 4 ICMP echo requests to host | |
ping | 8.8.8.8 | Tests network connectivity | |
hostnamectl | set-hostname server1.example.com | Sets system hostname | Configuration file location: /etc/hostname |
hostnamectl | status | Shows hostname and system information | |
getent | hosts servername | Verifies hostname resolution | |
cat | /etc/NetworkManager/system-connections/ ens160.nmconnection | Views NetworkManager Connection File | In previous RHEL versions thy was under: /etc/sysconfig/network-scripts |
systemctl | status NetworkManager | Shows NetworkManager service status | |
man | 5 nm-settings | Shows man pages of how to do configuration using nmcli | |
man | nmcli-examples | Shows examples of nmcli | You do not need to remember the arguemtns to configure network settings – use this man pages |
Configuration File Path | Use Case | Important Notes |
/etc/NetworkManager/system-connections/ | NetworkManager Connection File – contains IP information | |
/etc/sysconfig/network-scripts | Contains IP information – Used in old RHEL versions | NetworkManager uses the following directory: /etc/NetworkManager/system-connections/ |
/etc/hostname | Contains hostname information | |
/etc/hosts | Contains DNS information | |
/etc/nsswitch.conf | Controls how and in what order system databases (like hosts, passwd, group) are looked up | Do not edit this file manually |
/etc/resolv.conf | DNS server configuration file |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Configure static IP address using nmcli | nmcli con add type ethernet con-name static-eth ifname eth0 ip4 192.168.1.100/24 gw4 192.168.1.1 |
Configure DHCP using nmcli | nmcli con add type ethernet con-name dhcp-eth ifname eth0 |
Set system hostname | hostnamectl set-hostname server1.example.com |
Configure DNS servers | nmcli con mod static-eth ipv4.dns ‘8.8.8.8,8.8.4.4’ |
Add static host entries to /etc/hosts | echo ‘192.168.1.50 server50’ >> /etc/hosts |
Troubleshoot network connectivity using ping | ping -c 4 8.8.8.8 then traceroute 8.8.8.8 |
Check network interface configuration | ip addr show or nmcli con show |
View routing table | ip route show or route -n |
Test port connectivity using telnet or nc | nc -zv hostname port or telnet hostname port |
Configure network bonding/teaming | nmcli 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 service | systemctl restart NetworkManager |
Configure network interface to start at boot | nmcli con mod con-name connection.autoconnect yes |
Change MTU size on network interface | nmcli con mod con-name 802-3-ethernet.mtu 1500 |
Configure multiple IP addresses on one interface | nmcli con mod con-name +ipv4.addresses ‘192.168.1.101/24’ |
Set up network routes | ip route add 10.0.0.0/8 via 192.168.1.1 |
Monitor network traffic and connections | ss -tuln or netstat -tuln |
Configure firewall rules for specific services | firewall-cmd –add-service=http –permanent && firewall-cmd –reload |
Troubleshoot DNS resolution issues | Check: 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 configuration | cp -r /etc/NetworkManager/ ~/network-backup/ |
8. Commands used to Manage Softwares
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
dnf | install package | Installs a package | |
dnf | remove package | Removes a package | |
dnf | update | Updates all packages | |
dnf | update package | Updates specific package | |
dnf | search keyword | Searches for package by keyword | |
dnf | search all keyword | Deep search in package descriptions | |
dnf | provides */file | Finds package containing specific file | |
dnf | info package | Shows detailed package information | |
dnf | list installed | Lists installed packages | |
dnf | list available | Lists available packages | |
dnf | list package | Shows installed and available versions | |
dnf | repolist | Shows configured repositories | |
dnf | group list | Lists package groups | |
dnf | groupinstall “Group Name” | Installs package group | |
dnf | group info “Group Name” | Shows package group contents | |
dnf | history | Shows transaction history | |
dnf | history undo ID | Undoes specific transaction | |
dnf | clean all | Clears cached repository data | |
dnf | config-manager –add-repo=URL | Adds new repository | |
dnf | module list | Lists available modules | |
dnf | module info modulename | Shows module information | |
dnf | module install name:stream/profile | Installs module with specific stream/profile | |
rpm | -qi package | Queries information about installed package | |
rpm | -ql package | Lists files in package | |
rpm | -qf /path/to/file | Queries which package owns file | |
rpm | -qc package | Shows package configuration files | |
rpm | -qd package | Shows package documentation | |
rpm | -q –scripts package | Shows scripts in package | |
rpm | -qp –scripts package.rpm | Shows scripts in package file (not installed) | |
rpm | -qR package | Shows package dependencies | |
rpm | -V package | Verifies package integrity | |
rpm | -Va | Verifies all installed packages | |
rpm | -qa | Lists all installed packages | |
subscription-manager | register | Registers system with Red Hat | |
subscription-manager | list –available | Lists available subscriptions | |
subscription-manager | attach –auto | Attaches available subscription | |
subscription-manager | unregister | Unregisters system |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Install a software package using dnf | dnf install httpd |
Remove a software package using dnf | dnf remove httpd |
Update all system packages using dnf | dnf update |
Search for available packages | dnf search python3 |
Show information about an installed package | dnf info httpd |
List all installed packages | dnf list installed or rpm -qa |
Clean dnf cache | dnf clean all |
Install a package group | dnf groupinstall “Development Tools” |
Configure additional software repository | Create /etc/yum.repos.d/myrepo.repo: [myrepo] name=My Repository baseurl=file:///path/to/repo enabled=1 gpgcheck=0 |
Install local RPM package | dnf install /path/to/package.rpm |
Verify integrity of installed packages | rpm -V package-name |
Check what package provides a specific file | dnf provides /usr/bin/python3 |
List files installed by a package | rpm -ql package-name |
Check for available updates | dnf check-update |
Downgrade a package to previous version | dnf downgrade package-name |
Manage dnf history and undo transactions | dnf history then dnf history undo 3 |
Configure dnf to exclude certain packages from updates | echo “exclude=kernel*” >> /etc/dnf/dnf.conf |
Set up automatic updates | dnf install dnf-automatic and configure /etc/dnf/automatic.conf |
Work with module streams | dnf module list then dnf module enable nodejs:16 |
Troubleshoot package dependency issues | dnf deplist package-name to see dependencies |
9. Managing Processes
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
ps | aux | Shows all processes with detailed info | |
ps | -ef | Shows all processes in full format | |
ps | fax | Shows process hierarchy tree | |
top | (none) | Interactive process viewer | |
htop | (none) | Enhanced interactive process viewer | |
kill | PID | Sends TERM signal to process (graceful) | |
kill | -9 PID | Sends SIGKILL to process (force stop) | |
killall | processname | Kills processes by name | |
pkill | processname | Kills processes by name pattern | |
nice | -n 10 command | Starts command with nice value of 10 | |
renice | -n 5 -p PID | Changes nice value of running process | |
renice | value PID | Changes nice value (alternative syntax) | |
jobs | (none) | Lists background jobs in current shell | |
bg | %1 | Resumes background job | |
fg | %1 | Brings background job to foreground | |
tuned-adm | profile profile | Sets system performance profile | |
tuned-adm | list | Lists available tuned profiles | |
tuned-adm | active | Shows currently active tuned profile |
Key Combinations
Key Combo | Use Case / Description |
---|---|
Ctrl+Z | Suspends current foreground job |
Ctrl+C | Terminates current job |
Ctrl+D | Sends EOF (End Of File) signal |
& (at end of command) | Starts command in background |
Alt+F1-F6 | Switches between virtual terminals |
Ctrl+Alt+F1-F6 | Switches from GUI to text terminals |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
List all processes running on the system | ps aux or ps -ef |
Find processes using most CPU | ps aux –sort=-%cpu | head -10 |
Find processes using most memory | ps aux –sort=-%mem | head -10 |
Kill a process by PID | kill 1234 |
Kill a process by name | pkill process-name or killall process-name |
Change process priority using nice | nice -n 10 /path/to/command |
Change priority of running process using renice | renice -n 10 -p 1234 |
Run process in background | long-running-command & |
Move process between foreground and background | fg %1 (bring to foreground), bg %1 (send to background) |
List background jobs | jobs |
Use kill to send different signals to processes | kill -1 1234 (HUP), kill -9 1234 (KILL), kill -15 1234 (TERM) |
Monitor processes in real-time | top or htop |
Find parent-child process relationships | ps -ef –forest or pstree |
Identify zombie processes | ps aux | grep defunct or ps aux | awk ‘$8==”Z” {print $2}’ |
Set process CPU affinity | taskset -p 1234 (view), taskset -cp 0,1 1234 (set to CPUs 0,1) |
Monitor system resource usage | vmstat 1, iostat 1, mpstat 1 |
Configure process limits for users | ulimit -a (view), edit /etc/security/limits.conf |
Use pstree to view process hierarchy | pstree -p |
Find which process is using a specific port | ss -tulnp | grep :80 or lsof -i :80 |
Manage services as processes | systemctl status servicename |
10. Working with Systemd
Command | Arguments / Options | Use Case / Description | Important Notes |
---|---|---|---|
systemctl | start <unit> | Starts a service/unit. | |
systemctl | stop <unit> | Stops a service/unit. | |
systemctl | restart <unit> | Restarts a service/unit. | |
systemctl | reload <unit> | Reloads a service’s configuration. | |
systemctl | enable <unit> | Enables a unit to start automatically at boot. | |
systemctl | disable <unit> | Disables a unit from starting automatically at boot. | |
systemctl | status <unit> | Shows the current status of a unit. | |
systemctl | status -l <unit> | Shows detailed status information. | |
systemctl | list-units -t service | Lists all active service units. | |
systemctl | list-units -t service –all | Lists all service units, including inactive ones. | |
systemctl | –failed -t service | Shows all services that have failed. | |
systemctl | -t help | Shows all available Systemd unit types. | |
systemctl | list-dependencies <unit> | Shows the dependencies of a specific unit. | |
systemctl | list-dependencies –reverse <unit> | Shows which units depend on a specific unit. | |
systemctl | show <unit> | Shows all available configuration options for a unit. | |
systemctl | edit <unit> | Creates an override file for a unit in /etc/systemd/system. | |
systemctl | cat <unit> | Displays the current, combined configuration of a unit. | |
systemctl | mask <unit> | Completely disables a unit, preventing manual and automatic start. | |
systemctl | unmask <unit> | Reverses the effect of mask. | |
systemctl | daemon-reload | Reloads Systemd manager configuration after changing unit files. | |
journalctl | -u <unit> | Shows logs for a specific Systemd unit. | |
journalctl | -f | Follows (tails) the journal. | |
systemd-analyze | (none) | Shows boot performance statistics. |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Start a system service | systemctl start httpd |
Stop a system service | systemctl stop httpd |
Restart a system service | systemctl restart httpd |
Check status of a service | systemctl status httpd |
Enable service to start at boot | systemctl enable httpd |
Disable service from starting at boot | systemctl disable httpd |
Mask a service to prevent starting | systemctl mask httpd |
Unmask a service | systemctl unmask httpd |
View system boot time and performance | systemd-analyze (boot time), systemd-analyze blame (service times) |
Change default system target (runlevel) | systemctl set-default multi-user.target |
List all running services | systemctl list-units –type=service –state=running |
List all failed services | systemctl –failed |
View service dependencies | systemctl list-dependencies httpd |
Analyze why a service failed to start | journalctl -u httpd and systemctl status httpd -l |
Create a custom systemd service | Create /etc/systemd/system/myservice.service: [Unit] Description=My Custom Service [Service] ExecStart=/path/to/command [Install] WantedBy=multi-user.target |
Configure service resource limits | Add to service file: LimitNOFILE=65536 |
View service logs using journalctl | journalctl -u servicename -f |
Set service to restart on failure | Add to service file: Restart=on-failure |
Work with systemd timers | Create /etc/systemd/system/mytimer.timer and .service files |
Troubleshoot systemd service issues | journalctl -u servicename –since “1 hour ago” |
11. Scheduling Tasks
Command | Arguments / Options | Use Case / Description | Important Notes |
---|---|---|---|
crontab | -e | Edits the current user’s crontab file. | |
crontab | -l | Lists the current user’s crontab entries. | |
crontab | -r | Deletes the current user’s crontab. | |
crontab | -u <username> -e | Edits the crontab for a specific user (requires root). | |
at | HH:MM | Schedules 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. | |
systemctl | status atd | Checks the status of the at daemon. | |
systemctl | enable crond | Enables the cron daemon to start at boot. | |
systemctl | start crond | Starts the cron daemon. | |
batch | (none) | Schedules a job to run when system load is low. |
Used Scenarios with Q/A:
Task | Command |
---|---|
Create a user cron job that runs daily | crontab -e add: 0 2 * * * /home/user/backup.sh |
Create a system cron job | sudo vim /etc/crontab add: 0 2 * * * root /root/backup.sh |
Schedule a one-time task using at | echo “tar -czf /backup/backup.tar.gz /home” | at 02:00 tomorrow |
List pending at jobs | atq |
Remove a scheduled at job | atrm 1 |
Configure cron to run every 5 minutes | */5 * * * * /path/to/script.sh |
Configure cron to run on specific days of week | 0 2 * * 1 /path/to/script.sh |
Redirect cron job output to a file | 0 2 * * * /path/to/script.sh > /var/log/script.log 2>&1 |
Set up cron job that runs during specific hours only | 0 9-17 * * * /path/to/script.sh |
Configure email notification for cron jobs | Add MAILTO=user@example.com at top of crontab |
Restrict cron access for users | echo “username” >> /etc/cron.deny |
Backup cron configuration | crontab -l > cron-backup.txt |
Troubleshoot why cron job didn’t run | Check: grep CRON /var/log/cron, verify script permissions, PATH |
Set up anacron for missed jobs | dnf install anacron, configure /etc/anacrontab |
Create cron job that runs on first day of month | 0 0 1 * * /path/to/script.sh |
Schedule system maintenance tasks | 0 2 * * * /usr/bin/updatedb (update locate database) |
Monitor cron job execution | tail -f /var/log/cron |
Configure environment for cron jobs | Add to crontab: SHELL=/bin/bash, PATH=/usr/bin:/bin |
Use systemd timers as cron alternative | Create systemd timer as shown in Chapter 11 |
Set up log rotation for cron output | Configure in /etc/logrotate.d/ for the log file |
12. Configuring Logging
Command | Arguments / Options | Use Case / Description | Important Notes |
---|---|---|---|
journalctl | -f | Follows (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 | -b | Shows logs from the current boot only. | |
journalctl | -x | Adds explanation messages to the log output. | |
journalctl | -o verbose | Shows log entries with all available fields. | |
journalctl | _SYSTEMD_UNIT=<unit> | Filters logs using specific fields (e.g., by unit). | |
tail | -f /var/log/file | Monitors 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. | |
Command | Arguments / Options | Use Case / Description | |
journalctl | -f | Follows (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 | -b | Shows logs from the current boot only. | |
journalctl | -x | Adds explanation messages to the log output. | |
journalctl | -o verbose | Shows log entries with all available fields. | |
journalctl | _SYSTEMD_UNIT=<unit> | Filters logs using specific fields (e.g., by unit). | |
tail | -f /var/log/file | Monitors 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 | -v | Shows the version of rsyslog. | |
logrotate | -f /etc/logrotate.conf | Forces log rotation to happen immediately. |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Configure rsyslog to log to a specific file | vim /etc/rsyslog.conf add: *.info /var/log/all.log |
Set up log rotation for custom application logs | Create /etc/logrotate.d/myapp: /var/log/myapp.log { daily rotate 7 compress missingok } |
Use journalctl to view system logs | journalctl |
Filter journal logs by time period | journalctl –since “2024-01-01” –until “2024-01-02” |
Filter journal logs by service/unit | journalctl -u httpd |
Configure persistent journal storage | mkdir -p /var/log/journal && systemctl restart systemd-journald |
Clear journal logs | journalctl –vacuum-time=1d |
Set log retention policy | Edit /etc/systemd/journald.conf: SystemMaxUse=1G |
Forward logs to remote server | vim /etc/rsyslog.conf add: *.* @@remote-server:514 |
Search for specific error messages in logs | journalctl -p err or grep -i error /var/log/messages |
Monitor logs in real-time | journalctl -f |
Configure log level for specific services | Edit service file or use journalctl -p debug |
Create custom log files | vim /etc/rsyslog.conf add: local0.* /var/log/myapp.log |
Analyze log file permissions and ownership | ls -la /var/log/ and getfacl /var/log/messages |
Troubleshoot logging issues | Check: systemctl status rsyslog, disk space, permissions |
Use logger to add custom entries to logs | logger -p local0.info “Test message” |
Configure log rate limiting | Edit /etc/rsyslog.conf: $SystemLogRateLimitInterval 0 (disable) |
Archive old log files | find /var/log -name “*.gz” -o -name “*.1” |
Set up log monitoring alerts | grep -i “error\|fail” /var/log/messages | mail -s “Errors” admin@example.com |
Correlate logs from different services | journalctl -u httpd -u mariadb –since “1 hour ago” |
13. Managing Storage
Command | Arguments / Options | Use Case / Description | Important Notes |
---|---|---|---|
fdisk | /dev/sdX | Partitions a disk using the MBR partition table scheme. | |
gdisk | /dev/sdX | Partitions a disk using the GPT partition table scheme. | |
parted | /dev/sdX | A versatile partitioning tool. | |
parted | /dev/sdX mklabel gpt | Creates 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/sdX1 | Creates an XFS filesystem on a partition. | |
mkfs.xfs | /dev/sdX1 | Creates an XFS filesystem (the RHEL 9 default). | |
mkfs | -t ext4 /dev/sdX1 | Creates an ext4 filesystem. | |
mkfs.ext4 | /dev/sdX1 | Creates an ext4 filesystem. | |
mount | /dev/sdX1 /mnt | Temporarily mounts a filesystem. | |
mount | -a | Mounts all filesystems defined in /etc/fstab. | |
umount | /mnt or /dev/sdX1 | Unmounts a filesystem. | |
df | -h | Shows disk space usage of mounted filesystems in human-readable format. | |
du | -sh /path | Shows disk usage of a specific directory. | |
tune2fs | -l /dev/sdX1 | Shows properties and information of an ext2/3/4 filesystem. | |
xfs_admin | -L <label> /dev/sdX1 | Sets a label on an XFS filesystem. | |
mkswap | /dev/sdX1 | Formats a partition as swap space. | |
swapon | /dev/sdX1 | Activates a swap partition. | |
swapoff | /dev/sdX1 | Deactivates a swap partition. | |
findmnt | –verify | Verifies the correctness of /etc/fstab before rebooting. |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Create a new disk partition using fdisk | fdisk /dev/sdb → n → p → 1 → Enter → Enter → w |
Create a new disk partition using parted | parted /dev/sdb mklabel gpt mkpart primary 0% 100% |
Create XFS filesystem on a partition | mkfs.xfs /dev/sdb1 |
Create ext4 filesystem on a partition | mkfs.ext4 /dev/sdb1 |
Mount filesystem manually | mount /dev/sdb1 /mnt |
Configure persistent mounts in /etc/fstab | echo “/dev/sdb1 /mnt xfs defaults 0 0” >> /etc/fstab |
Use filesystem UUID in fstab | blkid /dev/sdb1 then use: UUID=xxx /mnt xfs defaults 0 0 |
Use filesystem label in fstab | xfs_admin -L mylabel /dev/sdb1 then: LABEL=mylabel /mnt xfs defaults 0 0 |
Add swap space using a partition | mkswap /dev/sdc1 && swapon /dev/sdc1 add to fstab: /dev/sdc1 swap swap defaults 0 0 |
Add swap space using a file | dd if=/dev/zero of=/swapfile bs=1M count=1024 && mkswap /swapfile && swapon /swapfile add to fstab: /swapfile swap swap defaults 0 0 |
Check filesystem integrity | xfs_repair /dev/sdb1 or fsck.ext4 /dev/sdb1 |
Repair damaged filesystem | xfs_repair -L /dev/sdb1 (force repair, may lose data) |
Monitor disk space usage | df -h and du -sh /path |
Extend existing filesystem (for non-LVM) | For XFS: xfs_growfs /mountpoint, for ext4: resize2fs /dev/partition |
Create encrypted filesystem | cryptsetup luksFormat /dev/sdb1 then cryptsetup luksOpen /dev/sdb1 encrypted_vol |
Backup and restore filesystem | xfsdump -l 0 -f backup.xfsdump /dev/sdb1 and xfsrestore -f backup.xfsdump /mnt |
Check disk health with SMART | smartctl -a /dev/sda |
Mount network filesystems | mount -t nfs server:/export /mnt |
Set filesystem mount options | mount -o noatime,nodiratime /dev/sdb1 /mnt |
Troubleshoot mount issues | Check: dmesg | grep sdb, mount, /etc/fstab syntax |
14. Managing Advanced Storage
Command | Arguments / Options | Use Case / Description | Important Notes |
---|---|---|---|
pvcreate | /dev/sdX1 | Initializes 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. | |
vgcreate | vg_name /dev/sdX1 | Creates a Volume Group (VG) named vg_name with an initial PV. | |
vgextend | vg_name /dev/sdY1 | Adds a new PV to an existing VG. | |
vgreduce | vg_name /dev/sdY1 | Removes 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_name | Creates a Logical Volume (LV) of 10GB. | |
lvcreate | -l 50%FREE -n lv_name vg_name | Creates an LV using 50% of the free space in the VG. | |
lvextend | -L +5G /dev/vg_name/lv_name | Extends an LV by 5GB. | |
lvextend / lvresize | -r -L +5G /dev/vg_name/lv_name | Extends 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/point | Grows an XFS filesystem to the size of its underlying LV. | |
resize2fs | /dev/vg_name/lv_name | Resizes an ext4 filesystem to the size of its underlying LV. | |
pvmove | /dev/sdY1 /dev/sdX1 | Moves data from one PV to another within the same VG. | |
stratis | pool create pool_name /dev/sdX | Creates a Stratis pool on a block device. | |
stratis | fs create pool_name fs_name | Creates a filesystem in a Stratis pool. | |
stratis | fs list | Lists all Stratis filesystems. | |
stratis | filesystem snapshot pool_name origin_fs snapshot_fs | Creates a snapshot of a Stratis filesystem. |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Create physical volume | pvcreate /dev/sdb |
Create volume group | vgcreate myvg /dev/sdb |
Create logical volume | lvcreate -n mylv -L 10G myvg |
Extend logical volume | lvextend -L +5G /dev/myvg/mylv then xfs_growfs /dev/myvg/mylv |
Reduce logical volume | lvreduce -L -2G /dev/myvg/mylv (unmount and resize filesystem first) |
Extend volume group | vgextend myvg /dev/sdc |
Reduce volume group | vgreduce myvg /dev/sdc (move data first with pvmove) |
Create snapshot of logical volume | lvcreate –snapshot –name mysnap –size 1G /dev/myvg/mylv |
Restore from snapshot | lvconvert –merge /dev/myvg/mysnap |
Move physical volume between volume groups | pvmove /dev/sdb /dev/sdc then vgreduce myvg /dev/sdb |
Monitor LVM status | vgs, pvs, lvs |
Configure LVM thin provisioning | lvcreate –type thin-pool -L 10G –name thin_pool myvg |
Set up Stratis storage pool | dnf install stratisd stratis-cli, systemctl enable –now stratisd, stratis pool create mypool /dev/sdb |
Create Stratis filesystem | stratis filesystem create mypool myfs |
Extend Stratis filesystem | stratis filesystem mypool/myfs then stratis pool add-data mypool /dev/sdc |
Monitor Stratis storage | stratis pool list, stratis filesystem list |
Configure LVM caching | lvcreate –type cache -L 1G -n lvcache myvg /dev/slowlv /dev/fastpv |
Backup LVM configuration | vgcfgbackup myvg |
Troubleshoot LVM issues | Check: dmesg, /var/log/messages, LVM metadata with vgcfgrestore |
Migrate data between storage systems | dd if=/dev/myvg/mylv of=/backup/lv_backup.img |
15. Basic Kernal Management
Command | Arguments / Options | Use Case / Description | Important Notes |
---|---|---|---|
uname | -r | Shows the kernel release version. | |
uname | -a | Shows 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.ko | Low-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 | -T | Shows dmesg output with human-readable timestamps. | |
lspci | -k | Lists PCI devices and shows the kernel driver in use for each. | |
udevadm | monitor | Monitors the udev daemon for device events in real-time. |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
List loaded kernel modules | lsmod |
Load kernel module | modprobe module_name |
Unload kernel module | modprobe -r module_name |
Check kernel module parameters | modinfo module_name |
Set kernel module parameters | Create /etc/modprobe.d/mymodule.conf: options module_name param=value |
List available kernel modules | find /lib/modules/$(uname -r) -name “*.ko” |
Check kernel version | uname -r |
Check kernel boot parameters | cat /proc/cmdline |
Modify kernel parameters at runtime | echo “value” > /proc/sys/kernel/parameter or sysctl -w kernel.parameter=value |
Blacklist kernel module | echo “blacklist module_name” > /etc/modprobe.d/blacklist.conf |
Update kernel | dnf install kernel-* then reboot |
Boot from different kernel version | Select from GRUB menu or set default with grub2-set-default |
Check hardware information | lspci, lsusb, lscpu |
Monitor kernel messages | dmesg or journalctl –dmesg |
Troubleshoot kernel issues | Check: dmesg | grep -i error, remove problematic modules, use previous kernel |
Configure kernel module dependencies | modinfo module_name | grep depends |
Create custom kernel module | dnf install kernel-devel, write module code, compile with make |
Check kernel ring buffer | dmesg -w (follow) |
Analyze system interrupts | cat /proc/interrupts |
Monitor kernel performance | vmstat 1, mpstat 1, pidstat 1 |
16. Managing the Boot Process
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
systemctl –type=target | –all | List all targets (active/inactive) | |
systemctl isolate | rescue.target | Switch to rescue target immediately | |
systemctl get-default | Show current default target | ||
systemctl set-default | multi-user.target | Set default boot target | |
grub2-mkconfig | -o /boot/grub2/grub.cfg | Regenerate GRUB config (BIOS) | |
grub2-mkconfig | -o /boot/efi/EFI/redhat/grub.cfg | Regenerate GRUB config (UEFI) | |
grub2-install | /dev/sda | Reinstall GRUB bootloader | |
systemctl cat | multi-user.target | View target unit file contents | |
grep Isolate | *.target | Find targets that allow isolation | |
dnf group list | List available package groups | ||
dnf group install | “server with gui” | Install GUI packages |
Used Scenarios with Q/A:
Question | Answer |
---|---|
Modify GRUB2 configuration | vim /etc/default/grub add to GRUB_CMDLINE_LINUX, then grub2-mkconfig -o /boot/grub2/grub.cfg |
Set default kernel boot entry | grub2-set-default 0 (0 for first entry) |
Add kernel boot parameters | vim /etc/default/grub add to GRUB_CMDLINE_LINUX=”rhgb quiet new_param” |
Reinstall GRUB2 bootloader | grub2-install /dev/sda |
Rebuild initramfs | dracut -f or mkinitrd -f |
Boot into rescue mode | Reboot, in GRUB edit kernel line, add systemd.unit=rescue.target |
Boot into emergency mode | Reboot, in GRUB edit kernel line, add systemd.unit=emergency.target |
Set default boot target | systemctl set-default multi-user.target |
Change systemd target at runtime | systemctl isolate multi-user.target |
Troubleshoot boot failures | Boot from installation media, chroot /mnt/sysroot, reinstall GRUB, fix fstab |
Recover from bootloader issues | Boot from live CD, mount root, chroot, grub2-install /dev/sda |
Password protect GRUB | grub2-setpassword |
Analyze boot performance | systemd-analyze, systemd-analyze blame, systemd-analyze critical-chain |
Configure serial console for boot | Add console=ttyS0,115200 to kernel parameters |
Backup boot configuration | cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.backup |
Restore boot configuration | Restore from backup or recreate from /etc/default/grub |
Work with UEFI boot manager | Use efibootmgr to manage UEFI entries |
Set up dual boot configuration | Install both OS, configure GRUB to detect both |
Monitor boot process messages | Remove rhgb quiet from kernel parameters, watch boot messages |
Fix filesystem issues at boot | Boot from rescue media, run fsck on affected partitions |
17. Essential Troubleshooting Commands
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
systemctl | rescue | Boots into rescue mode | |
systemctl | emergency | Boots into emergency mode | |
journalctl | -b | Shows logs from the current boot | |
journalctl | -b -1 | Shows logs from the previous boot | |
systemctl list-units | Show loaded units in rescue/emergency mode | ||
systemctl show-environment | Show current shell environment variables | ||
chroot | /mnt/sysimage | Change root to mounted system in rescue mode | |
dracut –force | Recreate initramfs | ||
mount -o remount,rw | / | Remount root filesystem as read-write | |
passwd | Change password (e.g., root password reset) | ||
touch /.autorelabel | Trigger SELinux relabel on next boot | ||
exec /usr/lib/systemd/systemd | Replace current shell with Systemd (after password reset) | ||
fsck | /dev/sdb1 | Check and repair filesystem | |
journalctl -xb | Show boot logs with details | ||
systemctl reboot | Reboot system |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Reset forgotten root password | Reboot, edit kernel line adding rd.break, then: chroot /sysroot passwd root touch /.autorelabel exit twice |
Repair corrupted filesystem | umount /dev/sda1 (if mounted), then fsck /dev/sda1 |
Recover from kernel panic | Check logs, identify faulty driver/hardware, boot previous kernel |
Fix network connectivity issues | systemctl restart NetworkManager, check cables, ip link show, nmcli con show |
Restore broken package database | rpm –rebuilddb |
Recover deleted files | Use testdisk, photorec, or restore from backup |
Fix bootloader issues | Boot from installation media, chroot /mnt/sysroot, grub2-install /dev/sda, grub2-mkconfig |
Troubleshoot service failures | systemctl status servicename, journalctl -u servicename, check dependencies |
Diagnose performance issues | top, vmstat 1, iostat 1, identify resource bottlenecks |
Fix permission problems | ls -la, getfacl file, check user/group with id username |
Recover from full filesystem | df -h, identify large files with du -sh /* 2>/dev/null | sort -hr, clean up |
Troubleshoot hardware issues | dmesg | grep -i error, lspci, smartctl -a /dev/sda |
Fix broken dependencies | dnf check, rpm -Va, reinstall broken packages |
Recover from failed updates | Boot previous kernel, use dnf history undo |
Diagnose memory issues | free -h, cat /proc/meminfo, identify memory leaks |
Fix corrupted configuration files | Restore from backup or recreate from documentation |
Troubleshoot login issues | Check PAM configuration, user shell, home directory permissions |
Recover from accidental file deletion | Restore from backup or use file recovery tools |
Fix broken symbolic links | find / -type l -! -exec test -e {} \; -print |
Diagnose and fix security issues | grep -r “password” /etc/ 2>/dev/null, check file permissions, audit logs |
18. Automation with Bash Shell Scripting
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
#!/bin/bash | (shebang) | Specify script interpreter | |
exit 0 | Exit script with success status | ||
$1, $2, … | Positional parameters (script arguments) | ||
$# | Number of arguments | ||
$@ | All arguments | ||
read | VARIABLE | Read user input into variable | |
test | -f file | Check if file exists | |
[ -f file ] | Alternative test syntax | ||
$(command) | Command substitution | ||
if … then … fi | Conditional execution | ||
for i in $@; do … done | Loop through arguments | ||
for (( i=0; i<10; i++ )); do … done | Arithmetic for loop | ||
while condition; do … done | While loop | ||
until condition; do … done | Until loop | ||
case $var in … esac | Case statement | ||
bash -x | script.sh | Debug script execution |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
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
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
ssh | -p 2022 user@host | Connect via non-default port | |
ssh | -i ~/.ssh/key.pem user@host | Connect with specific private key | |
ssh | -L 8080:localhost:80 user@host | Local port forwarding | |
ssh | -R 8080:localhost:80 user@host | Remote port forwarding | |
ssh-keygen | -t rsa -b 4096 | Generate RSA key pair | |
ssh-copy-id | -i ~/.ssh/key.pub user@host | Copy public key to host | |
ssh-agent | /bin/bash | Start SSH agent for current shell | |
ssh-add | Add private key passphrase to agent | ||
semanage port | -a -t ssh_port_t -p tcp 2022 | Add SELinux policy for custom SSH port | |
firewall-cmd | –add-port=2022/tcp | Open custom SSH port in firewall |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Configure SSH to use different port | Edit /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 SSH | Edit /etc/ssh/sshd_config: change PermitRootLogin yes to PermitRootLogin no |
Configure key-based authentication | ssh-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 users | Edit /etc/ssh/sshd_config: add AllowUsers user1 user2 or AllowGroups sshusers |
Configure SSH session timeout | Edit /etc/ssh/sshd_config: add ClientAliveInterval 300 and ClientAliveCountMax 2 |
Set up SSH tunneling | ssh -L 8080:localhost:80 user@remote (local forward) or ssh -R 8080:localhost:80 user@remote (remote forward) |
Configure SSH X11 forwarding | Edit /etc/ssh/sshd_config: set X11Forwarding yes and on client use ssh -X user@host |
Harden SSH configuration | Edit /etc/ssh/sshd_config: Protocol 2 PermitEmptyPasswords no PasswordAuthentication no PubkeyAuthentication yes ChallengeResponseAuthentication no UsePAM yes PrintMotd no |
Set up SSH jump host | ssh -J jumpuser@jumpserver targetuser@target |
Configure SSH bastion host | Configure 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 connections | ss -tlnp | grep :22, journalctl -u sshd -f |
Troubleshoot SSH connection issues | Check: ssh -v user@host, verify keys, permissions (~/.ssh/ should be 700, keys 600), firewall, SELinux |
Configure SSH client options | Create ~/.ssh/config: Host myserver Hostname server.example.com User myuser Port 2222 IdentityFile ~/.ssh/mykey ServerAliveInterval 60 |
Set up SSH for automated scripts | Use SSH keys in scripts: ssh -i /path/to/key user@host command |
Configure SSH for port forwarding | ssh -L 3306:localhost:3306 user@dbserver (forward MySQL port) |
Implement two-factor authentication for SSH | Use Google Authenticator: dnf install google-authenticator, google-authenticator, edit /etc/pam.d/sshd and /etc/ssh/sshd_config |
Configure SSH to use specific ciphers | Edit /etc/ssh/sshd_config: Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com |
Set up SSH connection multiplexing | Edit ~/.ssh/config: Host * ControlMaster auto ControlPath ~/.ssh/%r@%h:%p ControlPersist 600 |
Configure SSH to use different authentication methods | Edit /etc/ssh/sshd_config: AuthenticationMethods publickey,password publickey |
Backup and restore SSH keys | tar -czf ssh-backup.tar.gz ~/.ssh/ /etc/ssh/ |
20. Managing Apache HTTP Services
Command | Arguments | Use Case / Description | Important Notes |
---|---|---|---|
dnf install | httpd | Install Apache web server | |
systemctl enable –now | httpd | Start and enable Apache | |
systemctl status | httpd | Check Apache status | |
curl | http://localhost | Test web server from command line | |
httpd | -t | Test Apache configuration | |
apachectl | start | Start Apache (legacy) | |
apachectl | stop | Stop Apache (legacy) | |
apachectl | restart | Restart Apache (legacy) | |
apachectl | graceful | Graceful restart (legacy) | |
setenforce | 0 | Temporarily disable SELinux (for testing) |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Install Apache web server | dnf install httpd |
Start and enable Apache service | systemctl start httpd && systemctl enable httpd |
Configure virtual hosts | Create /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 website | dnf 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 controls | In 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 directory | htpasswd -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 pages | ErrorDocument 404 /errors/404.html and create the error page |
Set up logging for virtual hosts | In VirtualHost: CustomLog /var/log/httpd/vhost_access.log combined |
Configure PHP support | dnf install php php-mysqlnd |
Set up CGI scripts | In main config: ScriptAlias /cgi-bin/ “/var/www/cgi-bin/” |
Configure virtual host aliases | ServerAlias example.com *.example.com |
Set up reverse proxy | ProxyPass “/app” “http://backend:8080/”, ProxyPassReverse “/app” “http://backend:8080/” |
Configure load balancing | BalancerMember http://backend1:8080 BalancerMember http://backend2:8080 ProxyPass “/app” “balancer://mycluster/” |
Implement URL rewriting | RewriteEngine On, RewriteRule ^oldpage$ newpage [R=301,L] |
Set up web application firewall | dnf install mod_security, configure in /etc/httpd/conf.d/mod_security.conf |
Monitor web server performance | apachectl status, server-status page, ps aux | grep httpd |
Troubleshoot web server issues | Check: systemctl status httpd, journalctl -u httpd, apachectl configtest |
Configure Apache modules | dnf install mod_php (for PHP), enable modules with a2enmod module_name |
Set up virtual host for different ports | Listen 8080 in VirtualHost |
Backup web server configuration | tar -czf httpd-backup.tar.gz /etc/httpd/ /var/www/html/ |
21. Managing SELinux
Command | Arguments | Use Case / Description | Important Notes |
sestatus | -v | Shows SELinux status | Use -v for detailed information |
setenforce | 0 | Sets SELinux to permissive mode | Temporary change only |
setenforce | 1 | Sets SELinux to enforcing mode | Temporary change only |
getenforce | (none) | Gets the current SELinux mode | Shows enforcing/permissive/disabled |
chcon | -t httpd_sys_content_t /path | Changes SELinux context of file/directory | Avoid using – changes lost on relabel |
semanage | fcontext -a -t httpd_sys_content_t “/dir(/.*)?” | Adds file context to policy | Recommended method for context changes |
restorecon | -R -v /path | Restores default SELinux context recursively | Use after semanage fcontext |
semanage | boolean -l | Lists SELinux booleans | Shows current and permanent settings |
setsebool | -P boolean_name on/off | Sets SELinux boolean persistently | -P makes changes permanent |
getsebool | -a | Lists all SELinux booleans | Use grep to filter results |
sealert | -l UUID | Analyzes SELinux log messages | Install setroubleshoot-server package |
sepolicy | generate | Generates SELinux policies for applications | Advanced troubleshooting |
ls | -Z file | Shows SELinux context of files | |
ps | -Z | Shows SELinux context of processes |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Check SELinux status | sestatus |
Set SELinux to enforcing mode | setenforce 1 |
Set SELinux to permissive mode | setenforce 0 |
View SELinux context of files | ls -Z /etc/passwd |
Change SELinux context of files | chcon -t httpd_sys_content_t /var/www/html/index.html |
Restore default SELinux context | restorecon -R /var/www/html/ |
Configure SELinux booleans | setsebool -P httpd_can_network_connect on |
Troubleshoot SELinux denials | sealert -a /var/log/audit/audit.log or ausearch -m avc -ts recent |
Analyze SELinux audit logs | ausearch -m avc -ts today |
Create custom SELinux policy | audit2allow -a to see suggested rules, audit2allow -a -M mypolicy to create module |
Configure SELinux for web server | setsebool -P httpd_can_network_connect on, chcon -t httpd_sys_content_t /web/content |
Configure SELinux for database | setsebool -P mysql_connect_http on, chcon -t mysqld_db_t /var/lib/mysql/ |
Configure SELinux for network services | semanage port -a -t http_port_t -p tcp 8080 |
Set SELinux context for custom applications | chcon -t bin_t /opt/myapp/bin/, semanage fcontext -a -t bin_t “/opt/myapp/bin(/.*)?” |
Monitor SELinux events | tail -f /var/log/audit/audit.log | grep avc |
Backup SELinux configuration | tar -czf selinux-backup.tar.gz /etc/selinux/ /var/lib/selinux/ |
Troubleshoot SELinux issues | Check: sealert -a /var/log/audit/audit.log, verify contexts, check booleans |
Configure SELinux users | semanage user -l, semanage login -a -s user_u username |
Set up SELinux policy modules | audit2allow -M mypolicy, semodule -i mypolicy.pp |
Implement SELinux in mixed environment | Set permissive mode during migration: setenforce 0, monitor logs, create policies |
22. Configuring Firewall
Command | Arguments | Use Case / Description | Important Notes |
firewall-cmd | –list-all | Lists all firewall rules for default zone | |
firewall-cmd | –list-all –zone=zone_name | Lists rules for specific zone | |
firewall-cmd | –get-services | Lists all available services | |
firewall-cmd | –add-service=service_name | Adds a service to firewall | Runtime only |
firewall-cmd | –add-service=service_name –permanent | Adds service permanently | Requires –reload |
firewall-cmd | –remove-service=service_name | Removes a service from firewall | |
firewall-cmd | –add-port=port/protocol | Adds a port to firewall | |
firewall-cmd | –remove-port=port/protocol | Removes a port from firewall | |
firewall-cmd | –runtime-to-permanent | Makes runtime rules permanent | Alternative to –permanent |
firewall-cmd | –reload | Reloads firewall rules | Activates permanent changes |
firewall-cmd | –get-default-zone | Shows current default zone | |
firewall-cmd | –set-default-zone=zone_name | Changes default zone | |
firewall-cmd | –get-zones | Lists all available zones | |
firewall-cmd | –list-all-zones | Shows configuration for all zones |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Check firewall status | firewall-cmd –state |
List all firewall rules | firewall-cmd –list-all or firewall-cmd –list-all-zones |
Open port for specific service | firewall-cmd –add-port=80/tcp or firewall-cmd –add-service=http |
Block specific IP address | firewall-cmd –add-rich-rule=’rule family=”ipv4″ source address=”192.168.1.100″ reject’ |
Configure firewall zones | firewall-cmd –get-zones, firewall-cmd –get-default-zone |
Set default firewall zone | firewall-cmd –set-default-zone=public |
Create custom firewall service | firewall-cmd –new-service=myservice, firewall-cmd –service=myservice –add-port=8080/tcp |
Configure rich rules | firewall-cmd –add-rich-rule=’rule family=”ipv4″ source address=”192.168.1.0/24″ service name=”ssh” accept’ |
Set up port forwarding | firewall-cmd –add-forward-port=port=80:proto=tcp:toport=8080 |
Configure masquerading | firewall-cmd –add-masquerade |
Implement DMZ zone | firewall-cmd –new-zone=dmz, firewall-cmd –zone=dmz –add-interface=eth1 |
Monitor firewall activity | firewall-cmd –list-rich-rules, journalctl -u firewalld -f |
Backup firewall configuration | firewall-cmd –runtime-to-permanent |
Restore firewall configuration | firewall-cmd –reload |
Troubleshoot firewall issues | Check: systemctl status firewalld, firewall-cmd –state, verify services/ports |
Configure time-based rules | firewall-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 rules | firewall-cmd –set-log-denied=all |
Implement source NAT | firewall-cmd –add-rich-rule=’rule family=”ipv4″ source address=”192.168.1.0/24″ masquerade’ |
Configure destination NAT | firewall-cmd –add-forward-port=port=80:proto=tcp:toport=8080:toaddr=192.168.1.100 |
Set up firewall for specific applications | Create service definition for custom application ports |
23. Accessing Network Storage
Command | Arguments | Use Case / Description | Important Notes |
mount | -t nfs server:/share /mnt | Mounts an NFS share | |
mount | server.example.com:/ /mnt | NFSv4 pseudo root mount | Mounts all shares |
umount | /mnt | Unmounts an NFS share | |
showmount | -e server | Shows exports on NFS server | May not work through firewalls |
systemctl | start nfs-server | Starts NFS server service | |
systemctl | enable nfs-server | Enables NFS server service | |
systemctl | start autofs | Starts automount service | |
systemctl | enable autofs | Enables automount service | |
firewall-cmd | –add-service nfs –permanent | Opens firewall for NFS | Also add rpc-bind and mountd |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Mount NFS share manually | mount -t nfs server:/export /mnt/nfs |
Configure persistent NFS mounts | echo “server:/export /mnt/nfs nfs defaults 0 0” >> /etc/fstab |
Set up automount for NFS shares | Install autofs: dnf install autofs, configure /etc/auto.master and /etc/auto.nfs |
Configure NFS exports | On 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 share | mount -t cifs //server/share /mnt/smb -o username=user,password=pass |
Configure automount for SMB shares | In /etc/auto.master: /mnt/smb /etc/auto.smb –timeout=60 |
Set up iSCSI initiator | dnf install iscsi-initiator-utils, iscsiadm -m discovery -t st -p target_ip, iscsiadm -m node -T iqn -p target_ip -l |
Configure iSCSI persistent connections | iscsiadm -m node -T iqn -p target_ip -o update -n node.startup -v automatic |
Mount FTP share | curlftpfs ftp://user:pass@server /mnt/ftp |
Troubleshoot network storage issues | Check: showmount -e server, rpcinfo -p server, network connectivity, firewall |
Monitor network storage performance | iostat -x 1, nfsiostat |
Configure storage authentication | For iSCSI: configure CHAP in /etc/iscsi/iscsid.conf |
Set up multipath storage | dnf install device-mapper-multipath, configure /etc/multipath.conf |
Configure storage encryption | cryptsetup luksFormat /dev/sdb1 for encrypted storage |
Backup network storage configuration | tar -czf storage-config-backup.tar.gz /etc/fstab /etc/exports /etc/auto.* |
Restore network storage access | Restore from backup or recreate configurations |
Set up high availability storage | Configure DRBD or cluster-aware filesystems |
Configure storage quotas on network shares | edquota -u username for user quotas on NFS |
Monitor network storage usage | df -h, du -sh /mnt/nfs/* |
24. Configuring Time Services
Command | Arguments | Use Case / Description | Important Notes |
timedatectl | (none) | Shows current time settings | Recommended command |
timedatectl | set-time “YYYY-MM-DD HH:MM:SS” | Sets system time and date | |
timedatectl | set-timezone Timezone | Sets system timezone | |
timedatectl | list-timezones | Lists available timezones | |
timedatectl | set-ntp true/false | Enables/disables NTP synchronization | |
date | (none) | Shows current date and time | |
date | –date ‘@epoch_time’ | Converts epoch time to human readable | |
hwclock | –systohc | Syncs system time to hardware clock | |
hwclock | –hctosys | Syncs hardware time to system clock | |
chronyc | sources | Shows NTP sources | For chrony service |
chronyc | tracking | Shows NTP tracking information | |
tzselect | (none) | Interactive timezone selection |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Check current system time and date | date and timedatectl |
Set system timezone | timedatectl set-timezone America/New_York |
Configure NTP time synchronization | dnf install chrony, systemctl enable –now chronyd |
Set up chrony as NTP client | Edit /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 servers | Add multiple servers in /etc/chrony.conf as shown above |
Set up local time server | Edit /etc/chrony.conf: add allow 192.168.1.0/24 and use local stratum 10 |
Troubleshoot time synchronization | chronyc sources -v, chronyc tracking, chronyc makestep |
Monitor time service status | systemctl status chronyd, chronyc activity |
Configure time service logging | Edit /etc/chrony.conf: set logdir /var/log/chrony |
Set up time service for virtual machines | Add clock=pit to kernel parameters for better time in VMs |
Configure hardware clock synchronization | hwclock –systohc to sync hardware clock |
Backup time service configuration | tar -czf chrony-backup.tar.gz /etc/chrony.conf /var/lib/chrony/ |
Restore time service configuration | Restore from backup or reconfigure |
Troubleshoot time drift issues | chronyc tracking check offset, chronyc makestep to force sync |
Configure time service security | Use NTP authentication with keys in /etc/chrony.conf |
Set up time service monitoring | chronyc sourcestats, set up monitoring with Nagios/Zabbix |
Configure time service for different timezones | timedatectl list-timezones, set per-user if needed |
Implement redundant time servers | Configure multiple independent time sources |
Monitor time service performance | chronyc tracking check stability and offset |
Troubleshoot certificate time validation | Check certificate validity dates with openssl x509 -in cert.pem -text | grep -A 2 -B 2 Validity |
25. Managing Containers
Command | Arguments | Use Case / Description | Important Notes |
podman | run -d –name name image | Runs container in background | |
podman | run -it image /bin/sh | Runs container with interactive shell | |
podman | ps | Lists running containers | |
podman | ps -a | Lists all containers | |
podman | stop container | Stops a container | |
podman | start container | Starts a container | |
podman | restart container | Restarts a container | |
podman | rm container | Removes a container | |
podman | images | Lists container images | |
podman | rmi image | Removes container image | |
podman | pull image | Pulls image from registry | |
podman | exec -it container /bin/sh | Executes command in running container | |
podman | inspect image/container | Shows detailed container/image info | |
podman | search term | Searches for container images | |
podman | login registry | Logs into container registry | |
podman | info | Shows container environment info | |
podman | build -t name . | Builds image from Containerfile | |
podman | generate systemd –name container –files | Generates systemd service file | |
skopeo | inspect docker://image | Inspects remote images without pulling | |
buildah | bud -t image . | Builds image from Containerfile | Alternative to podman build |
Used Scenarios with Q/A:
Questions | Answers |
---|---|
Install container runtime (Podman) | dnf install podman |
Pull container image from registry | podman pull docker.io/nginx:latest |
List available container images | podman images |
Run container in foreground | podman run nginx:latest |
Run container in background | podman run -d –name mynginx nginx:latest |
Execute commands in running container | podman exec -it mynginx /bin/bash |
Stop and remove containers | podman stop mynginx && podman rm mynginx |
Create container from Containerfile | Create 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 networking | podman run –network=host nginx or podman run -p 8080:80 nginx |
Set up container storage | podman run -v /host/data:/container/data nginx |
Manage container logs | podman logs mynginx |
Configure container resource limits | podman run –memory=512m –cpus=1.5 nginx |
Set up container health checks | Create healthcheck in Containerfile: HEALTHCHECK –interval=30s –timeout=3s \ CMD curl -f http://localhost/ || exit 1 |
Create container pod | podman pod create –name mypod, podman run –pod mypod nginx |
Configure container registries | podman login docker.io, configure registries in /etc/containers/registries.conf |
Backup container data | podman commit mynginx mynginx-backup or podman export mynginx > backup.tar |
Monitor container performance | podman stats mynginx, podman top mynginx |
Troubleshoot container issues | Check: podman logs mynginx, podman inspect mynginx, verify resources |
Set up container as systemd service | Create /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 practices | Use SELinux labels: podman run –security-opt label=type:container_t myapp, run as non-root, use trusted images |
Leave a Reply