Linux Commands Guide for Red Hat, RHEL, Rocky and AlmaLinux

Linux 30 min readUpdated Oct 30, 2026
4 views0 comments

This guide collects the commands that system administrators really use on the Red Hat family of Linux: Red Hat Enterprise Linux (RHEL), Rocky Linux, AlmaLinux, CentOS Stream, Oracle Linux and Fedora. Each section explains what a command is for, shows the most useful options and gives examples you can copy. It is written so a beginner can follow it from top to bottom, and so an experienced admin can jump to the section they need and use it as a reference.

Everything here works on RHEL 8, 9 and 10 and their clones unless a note says otherwise. Commands that change the system need root rights, so they start with sudo. If you are logged in as root, simply leave sudo out. Want the short version? Use the printable Linux cheat sheet for RHEL, Rocky and AlmaLinux.

Practise safely. Run the examples in a virtual machine, not on a production server. Rocky Linux and AlmaLinux are free. Red Hat also gives individuals a no-cost RHEL Developer subscription, which is a good way to learn on the real thing.

Contents

1. Know your system and find help

The first thing to do on any server is to find out what it is. These commands answer that in seconds.

cat /etc/redhat-release          # for example: AlmaLinux release 9.4
cat /etc/os-release              # name, version and ID of the distribution
hostnamectl                      # hostname, OS, kernel, virtualisation
uname -r                         # running kernel version
uptime                           # how long it has been up, plus load average
whoami                           # the user you are logged in as
id                               # your user ID, group ID and all groups
date; timedatectl                # current time, time zone, clock sync status
Command What it tells you
lscpu CPU model, cores and threads
free -h Memory and swap in human-readable units
lsblk Disks and partitions as a tree
df -hT Mounted filesystems, their type and free space
lspci, lsusb PCI and USB devices (from the pciutils and usbutils packages)
sudo dmidecode -t system Server make and model, serial number
subscription-manager status Whether a RHEL system is registered and entitled (RHEL only)

Getting help without a search engine

man ls                    # the manual page (press q to quit, / to search)
ls --help | less          # a short summary of options
man -k "network manager"  # search all manual pages by keyword (same as apropos)
whatis chmod              # one-line description
type cd ; which dig       # is it a shell built-in, an alias or a file?
history | tail -20        # your last 20 commands
!!                        # repeat the previous command
sudo !!                   # repeat it with sudo (a lifesaver)
Ctrl+R                    # search your command history as you type

If a command is missing, ask dnf which package provides it, for example sudo dnf provides dig. Manual pages for many commands live in packages such as man-pages; install it if man says “No manual entry”.

2. Files and directories

Linux has one directory tree that starts at /. Your home folder is /home/yourname, which you can also write as ~. Configuration lives in /etc, logs in /var/log, and programs in /usr.

Command Use
pwd Show the directory you are in
cd /var/log, cd .., cd -, cd Go to a directory, up one level, back to the previous one, home
ls -lah List files with details, hidden files and readable sizes
ls -lt, ls -ltr Newest first, oldest first
ls -Z Also show the SELinux label of each file
mkdir -p /srv/site/images Create a folder and any missing parents
touch notes.txt Create an empty file or update its timestamp
cp -a source/ backup/ Copy and keep permissions, owners, links and times
mv old.txt new.txt Rename or move
rm file.txt, rm -ri folder/ Delete a file, or a folder after asking for each item
ln -s /opt/app/current /srv/app Create a symbolic link
stat file Size, owner, permissions, all timestamps, SELinux context
file photo.jpg Detect what kind of file it really is
tree -L 2 Show a folder tree two levels deep (install the tree package)

There is no recycle bin. rm deletes for good. Never run rm -rf with a variable you have not checked, and double-check the path before you press Enter.

Finding files

find /etc -name "*.conf"                      # by name
find /var/log -type f -mtime +30              # files not modified for 30+ days
find / -xdev -type f -size +500M 2>/dev/null  # files over 500 MB on the root filesystem
find /home -user bob                          # files owned by bob
find . -name "*.tmp" -delete                  # find and delete
find /var -type f -size +100M -exec ls -lh {} \;   # run a command on each result

The option -xdev keeps find on one filesystem, and 2>/dev/null hides “permission denied” noise. For instant lookups by name, install the locate package (mlocate or plocate, depending on the version), run sudo updatedb once, then use locate nginx.conf. We cover disk space problems in more detail in How to Find What Is Using Disk Space on Linux.

Sizes and compression

du -sh /var/*  | sort -h        # size of each item in /var, smallest to largest
df -hT                          # free space per filesystem
tar -czvf backup.tar.gz /etc    # create a compressed archive
tar -tzf backup.tar.gz          # list its content without extracting
tar -xzvf backup.tar.gz -C /tmp # extract into /tmp
gzip file.log ; gunzip file.log.gz
zip -r site.zip site/ ; unzip site.zip

Remember the tar letters: c create, x extract, t list, z gzip, v verbose, f file name (always last before the name).

3. Reading, searching and editing text

Almost everything on Linux is a text file: configuration, logs, scripts. These tools let you read and process them fast.

Command Use
cat file Print a whole file
less file Page through a file. /word searches, G goes to the end, q quits
head -n 20 file, tail -n 50 file First or last lines
tail -f /var/log/messages Follow a log live (Ctrl+C to stop)
wc -l file Count lines (-w words, -c bytes)
sort, sort -u, sort -n Sort lines, remove duplicates, sort numerically
uniq -c Count repeated lines (the input must be sorted)
cut -d: -f1,7 /etc/passwd Pick columns by delimiter
diff -u old.conf new.conf Show what changed between two files

grep: search inside files

grep "error" /var/log/messages             # lines containing "error"
grep -i "failed password" /var/log/secure  # ignore case
grep -rn "PermitRootLogin" /etc/ssh/       # search a folder recursively, show line numbers
grep -v "^#" /etc/ssh/sshd_config          # lines that do NOT start with #
grep -E "error|warning|critical" file      # several words at once
grep -c "404" access.log                   # only count the matches
grep -B2 -A2 "segfault" /var/log/messages  # 2 lines before and after each match

sed and awk: edit and report

sed -i.bak 's/^SELINUX=.*/SELINUX=permissive/' /etc/selinux/config   # replace, keep a .bak backup
sed -n '10,20p' file                       # print lines 10 to 20
sed '/^$/d' file                           # delete empty lines
awk -F: '{print $1, $3}' /etc/passwd       # user name and user ID
awk '$9 == 404 {print $7}' access.log      # the URL column of every 404
awk '{s+=$1} END {print s}' numbers.txt    # add up a column

Always keep a backup before using sed -i: the .bak suffix above does it for you.

Editors

nano file is the easy one: the shortcuts are shown at the bottom (Ctrl+O save, Ctrl+X exit). vi or vim is on every server, so learn the basics: press i to type, Esc to stop typing, then :wq to save and quit, :q! to quit without saving, /word to search, dd to delete a line, u to undo.

4. Pipes, redirection and shell tricks

The real power of the shell comes from joining small commands together.

command1 | command2         # send the output of command1 into command2
command > file             # write output to a file (overwrites it)
command >> file            # append output to a file
command 2> errors.txt      # send only error messages to a file
command > all.txt 2>&1    # send output and errors to the same file
command && other          # run "other" only if command succeeded
command || other            # run "other" only if command failed
command1 ; command2         # run both, one after the other
echo "hello" | tee file     # print AND write to a file (use sudo tee to write to root-owned files)

Practical examples:

# The 10 IP addresses that hit your web server most
awk '{print $1}' /var/log/httpd/access_log | sort | uniq -c | sort -rn | head -10

# Which users have a real login shell?
grep -v -E "nologin|false" /etc/passwd | cut -d: -f1

# Delete the 10 oldest files in a folder
ls -tr | head -10 | xargs rm -v

# Edit a root-owned file with redirection (plain "sudo echo > file" does not work)
echo "net.ipv4.ip_forward = 1" | sudo tee /etc/sysctl.d/99-forward.conf

Keyboard shortcuts that save time: Tab completes names, Ctrl+A and Ctrl+E jump to the start or end of the line, Ctrl+W deletes a word, Ctrl+L clears the screen, Ctrl+C stops a running command, and Ctrl+Z pauses it.

5. Permissions and sudo

Every file has an owner, a group and three sets of permissions: for the owner, the group and everyone else. Run ls -l and you see something like -rwxr-xr-- 1 bob staff 120 Jan 5 notes.sh. The first letter is the type (- file, d directory, l link), then three triples of read (r), write (w) and execute (x).

Number Letters Meaning Typical use
7 rwx read, write, execute Scripts and folders for the owner
6 rw- read and write Normal files
5 r-x read and execute Folders others may enter
4 r-- read only Public files
0 --- nothing Keep others out
chmod 644 file.txt            # owner read+write, everyone else read
chmod 755 script.sh           # owner everything, others read+execute
chmod 600 ~/.ssh/id_ed25519   # private key: only the owner (SSH insists on this)
chmod u+x script.sh           # add execute for the owner
chmod -R g+w /srv/shared      # add group write recursively
chown bob:developers file     # change owner and group
chown -R apache:apache /var/www/html
umask                         # default permissions mask for new files (usually 0022)

Never “fix” a permission problem with chmod -R 777. It lets every user and every hacked program change your files. Find out which user needs access and give exactly that.

Special permissions and ACLs

  • setuid (chmod u+s): the program runs as its owner. Example: passwd.
  • setgid on a folder (chmod g+s): new files inherit the folder’s group, handy for shared folders.
  • sticky bit (chmod +t): in a shared folder such as /tmp, users can delete only their own files.
chmod 2775 /srv/shared                   # setgid + rwxrwxr-x
setfacl -m u:alice:rwx /srv/project      # give one extra user access, without changing the group
getfacl /srv/project                     # show ACLs
setfacl -x u:alice /srv/project          # remove that entry
chattr +i /etc/important.conf            # make a file immutable (even root cannot change it)
lsattr /etc/important.conf

sudo

On the Red Hat family, members of the group wheel can use sudo.

sudo command                 # run one command as root
sudo -i                      # open a root shell (use rarely)
sudo -u postgres psql        # run as another user
sudo -l                      # what am I allowed to run?
sudo visudo                  # edit /etc/sudoers safely (it checks the syntax)
sudo visudo -f /etc/sudoers.d/deploy   # give a specific user or group specific rights

Never edit /etc/sudoers with a normal editor: one typo can lock you out of sudo. visudo refuses to save a broken file.

6. Users and groups

sudo useradd -m -s /bin/bash -G wheel alice   # create user with a home folder, a shell and admin rights
sudo passwd alice                              # set the password
sudo usermod -aG docker,developers alice       # ADD to groups (the -a matters!)
sudo usermod -L alice                          # lock the account;  -U unlocks it
sudo usermod -s /sbin/nologin svc_backup       # no interactive login for a service account
sudo userdel -r alice                          # delete the user and the home folder
sudo groupadd developers
sudo gpasswd -d alice developers               # remove from a group
id alice ; groups alice                        # check
getent passwd alice                            # look up in all sources (local, LDAP, SSSD)

A very common mistake is usermod -G group user without -a: it replaces all of the user’s groups, which can remove them from wheel. Always use -aG.

Password rules and login history

sudo chage -l alice          # password age and expiry
sudo chage -M 90 alice       # force a change every 90 days
sudo chage -d 0 alice        # force a change at next login
who ; w                      # who is logged in now, and what they run
last -n 20                   # recent logins
sudo lastb | head            # failed login attempts
lastlog | head               # last login of every account

7. Packages with dnf and rpm

dnf is the package manager of RHEL 8 and later. The old name yum still works because it is only an alias for dnf. It downloads packages, solves dependencies and removes them cleanly. rpm is the lower-level tool that works on single package files and on the database of what is installed.

Command Use
sudo dnf check-update List the updates that are available
sudo dnf upgrade Install all updates (update is the same)
sudo dnf upgrade --security Install only security updates
sudo dnf install nginx Install a package (add -y to skip the question)
sudo dnf remove nginx Remove a package
sudo dnf autoremove Remove dependencies nobody needs any more
dnf search "web server" Search names and descriptions
dnf info nginx Version, size, repository and description
dnf provides */bin/dig Which package contains a file or command
dnf repoquery -l nginx List the files a package would install
dnf list installed | grep kernel What is installed
dnf repolist Enabled repositories (--all shows disabled ones too)
sudo dnf clean all Clear the cache when metadata looks stale
sudo dnf group install "Development Tools" Install a group of packages

History: undo a change

dnf history                   # every dnf transaction with an ID
dnf history info 12           # what transaction 12 did
sudo dnf history undo 12      # reverse it

AppStream modules and extra repositories

RHEL 8 and 9 ship some software as modules, so you can pick a version stream. RHEL 10 reduces the use of modules, so check dnf module list on your system.

dnf module list nodejs                 # which versions exist
sudo dnf module enable nodejs:20       # choose a stream
sudo dnf module install nodejs:20      # enable and install in one step
sudo dnf module reset nodejs           # forget the choice

Many tools you may expect are in EPEL (Extra Packages for Enterprise Linux), run by the Fedora project. Some development libraries live in the CRB repository (called CodeReady Builder on RHEL).

# Rocky Linux and AlmaLinux
sudo dnf install epel-release
sudo dnf config-manager --set-enabled crb

# RHEL (registered system)
sudo subscription-manager repos --enable codeready-builder-for-rhel-9-$(arch)-rpms
sudo dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm

The config-manager command comes from dnf-plugins-core. Only add repositories you trust: a package from a repository runs as root when it installs.

Keep a package at one version, and automatic updates

sudo dnf install 'dnf-command(versionlock)'
sudo dnf versionlock add kernel-5.14.0-427.el9     # pin
sudo dnf versionlock list ; sudo dnf versionlock clear

sudo dnf install dnf-automatic
sudo systemctl enable --now dnf-automatic-install.timer   # download and install updates automatically
sudo dnf needs-restarting -r      # tells you if a reboot is needed (from dnf-utils)

Automatic installs are great for security patches on small servers. On critical systems, prefer scheduled maintenance windows with dnf upgrade --security and a reboot check.

rpm: query what is installed

rpm -qa | grep -i kernel          # all installed packages matching a word
rpm -qi openssh-server            # details of an installed package
rpm -ql openssh-server            # files installed by the package
rpm -qf /etc/ssh/sshd_config      # which package owns this file
rpm -V openssh-server             # verify files against the package (shows changed files)
rpm -qp --requires pkg.rpm        # what a downloaded .rpm needs
rpm -K pkg.rpm                    # check its signature
sudo rpm --import RPM-GPG-KEY     # trust a repository signing key

Prefer dnf install ./package.rpm over rpm -ivh for local files: dnf resolves the dependencies for you.

subscription-manager (Red Hat Enterprise Linux only)

sudo subscription-manager register --username YOUR_ID    # you will be asked for the password
sudo subscription-manager attach --auto                    # attach a subscription (if needed)
subscription-manager status
subscription-manager repos --list-enabled
sudo subscription-manager unregister

Rocky Linux and AlmaLinux do not need subscriptions.

8. Services, logs and timers with systemd

A service is a program that runs in the background, such as a web server or a database. systemd starts, stops and watches all services on RHEL.

Command Use
systemctl status sshd Is it running? The last log lines too
sudo systemctl start|stop|restart sshd Start, stop or restart now
sudo systemctl reload nginx Re-read the configuration without dropping connections
sudo systemctl enable --now nginx Start at boot and start now
sudo systemctl disable --now nginx Do not start at boot and stop now
systemctl is-active nginx, is-enabled nginx Short answers, good for scripts
systemctl --failed Everything that has failed. Run this first after a reboot
systemctl list-units --type=service All loaded services
sudo systemctl mask service Make it impossible to start, even by another service
systemctl cat nginx Show the unit file that is really used

Change a service without editing the original file

sudo systemctl edit nginx          # opens an override file
# example content:
# [Service]
# Restart=on-failure
# LimitNOFILE=65535
sudo systemctl daemon-reload       # needed after changing any unit file
sudo systemctl restart nginx

Overrides live in /etc/systemd/system/nginx.service.d/ and survive package updates. Never edit files in /usr/lib/systemd/system/: an update will overwrite them.

journalctl: read the logs

journalctl -u sshd                        # logs of one service
journalctl -u nginx -f                    # follow it live
journalctl -b                             # this boot only;  -b -1 = the previous boot
journalctl --since "1 hour ago"
journalctl --since "2026-10-29 08:00" --until "2026-10-29 09:00"
journalctl -p err -b                      # errors and worse, this boot
journalctl -k                             # kernel messages (like dmesg)
journalctl --disk-usage
sudo journalctl --vacuum-time=14d         # delete entries older than 14 days

If the directory /var/log/journal does not exist, the journal is kept only in memory and is lost at reboot. Create it with sudo mkdir -p /var/log/journal and restart systemd-journald to keep logs across reboots. Classic text logs also exist: /var/log/messages (general), /var/log/secure (logins and sudo), /var/log/dnf.log and /var/log/audit/audit.log.

Targets and boot speed

systemctl get-default                      # graphical.target or multi-user.target
sudo systemctl set-default multi-user.target   # servers rarely need a graphical login
systemd-analyze                            # total boot time
systemd-analyze blame | head               # slowest units at boot

A simple timer instead of cron

Two small files run a script every night at 02:30. First the service, /etc/systemd/system/cleanup.service:

[Unit]
Description=Nightly cleanup

[Service]
Type=oneshot
ExecStart=/usr/local/bin/cleanup.sh

Then the timer, /etc/systemd/system/cleanup.timer:

[Unit]
Description=Run cleanup every night

[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true

[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now cleanup.timer
systemctl list-timers              # next and last run of every timer
journalctl -u cleanup.service      # the output of past runs

Persistent=true runs a missed job after the server was off, which cron cannot do.

9. Processes and performance

ps aux                          # every process
ps aux --sort=-%mem | head      # top memory users
ps -ef --forest                 # parent and child relationships
ps -u apache                    # processes of one user
pgrep -a nginx                  # find processes by name
top                             # live view (q quits; M sorts by memory, P by CPU, 1 shows each core)
kill 1234                       # ask politely (SIGTERM, 15)
kill -9 1234                    # force (SIGKILL): last resort, no cleanup is done
pkill -f "python app.py"        # kill by a pattern in the command line
nice -n 10 command ; renice 5 -p 1234
command &                       # start in the background
jobs ; fg %1 ; bg %1            # manage background jobs
nohup ./long-task.sh > out.log 2>&1 &     # keep it running after you log out

For long work over SSH use a terminal multiplexer: sudo dnf install tmux, then tmux new -s work. If your connection drops, log in again and run tmux attach -t work.

Memory, disk and CPU pressure

free -h                         # focus on the "available" column, not "free"
vmstat 2 5                      # 5 samples every 2 seconds: look at r (queue), si/so (swapping), wa (I/O wait)
sudo dnf install sysstat        # adds iostat, mpstat, pidstat, sar
iostat -xz 2                    # disk utilisation and latency (%util, await)
pidstat -d 2                    # which process does the disk I/O
sar -u 1 5                      # CPU over time
uptime                          # load average: three numbers for 1, 5 and 15 minutes
sudo tuned-adm active           # current performance profile
sudo tuned-adm profile throughput-performance

Load average is the number of processes that wanted CPU or were waiting for disk. As a rule of thumb, a load higher than the number of CPU cores (nproc) for a long time means the server is overloaded.

Open files and ports

sudo lsof -i :443               # which process uses port 443
sudo lsof -u bob                # files opened by a user
sudo lsof +L1                   # deleted files that are still held open

That last command solves a classic puzzle: df says the disk is full, but du cannot find the data. A process is still holding a deleted log file open. Restart that service and the space returns.

10. Disks, filesystems and LVM

RHEL installs on LVM (Logical Volume Manager) by default, with the XFS filesystem. LVM puts a flexible layer between disks and filesystems, so you can grow a volume without a reboot.

lsblk -f                        # devices, filesystem type, UUID, mount point
sudo blkid                      # UUIDs of all devices
findmnt                         # mounts as a tree;  findmnt /var
df -hT ; df -i                  # space and inodes (running out of inodes also means "disk full")
sudo pvs ; sudo vgs ; sudo lvs  # LVM summary: physical volumes, volume groups, logical volumes

Add a new disk with LVM and XFS

Assume a new empty disk /dev/sdb. Check the device name with lsblk first: using the wrong disk destroys data.

sudo pvcreate /dev/sdb                          # mark the disk for LVM
sudo vgcreate data /dev/sdb                     # create a volume group called "data"
sudo lvcreate -n logs -L 20G data               # a 20 GB logical volume called "logs"
sudo mkfs.xfs /dev/data/logs                    # make the filesystem
sudo mkdir /logs
sudo mount /dev/data/logs /logs
sudo blkid /dev/data/logs                       # copy the UUID

To mount it at every boot, add a line to /etc/fstab (use your own UUID):

UUID=3c1e9c7e-1111-2222-3333-444455556666  /logs  xfs  defaults  0 0
sudo systemctl daemon-reload
sudo mount -a          # mounts everything in fstab: an error here means a mistake in the file
df -hT /logs

Always run mount -a after editing /etc/fstab. A wrong line can stop the server from booting normally.

Grow a volume while it is in use

sudo vgs                                  # is there free space in the volume group?
sudo lvextend -r -L +10G /dev/rhel/root   # add 10 GB and grow the filesystem in one step (-r)
sudo lvextend -r -l +100%FREE /dev/data/logs   # or use all the free space

# New disk added to an existing group:
sudo pvcreate /dev/sdc
sudo vgextend rhel /dev/sdc

# If you resized without -r:
sudo xfs_growfs /logs          # XFS grows by mount point
sudo resize2fs /dev/vg/lv      # ext4 uses the device

XFS can grow but it cannot shrink. To make an XFS volume smaller you have to back it up, recreate it and restore. If a virtual machine disk was enlarged in the hypervisor, first grow the partition (growpart /dev/sda 2 from cloud-utils-growpart), then sudo pvresize /dev/sda2, then lvextend -r.

Swap

swapon --show ; free -h
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048   # 2 GB file
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap defaults 0 0' | sudo tee -a /etc/fstab

11. Networking

On RHEL, NetworkManager controls the network. The old ifconfig and netstat commands are not installed by default; use ip and ss.

ip -br a                       # short list of interfaces and addresses
ip a show ens18                # one interface in detail
ip route                       # the routing table; look for "default via"
ip -s link show ens18          # packet, error and drop counters
hostname -I                    # all the IP addresses of this host
ss -tulpn                      # listening TCP and UDP ports with the process (t, u, l, p, n)
ss -tn state established       # active TCP connections
ping -c 4 1.1.1.1              # reachability test (4 packets)
tracepath example.com          # the path packets take
curl -I https://example.com    # headers only
curl -s -o /dev/null -w "%{http_code}\n" https://example.com   # just the status code
nc -zv server 443              # test a TCP port (from the nmap-ncat package)
sudo tcpdump -i ens18 -nn port 53    # capture traffic, here only DNS

For name resolution problems use dig and nslookup (package bind-utils). See DNS Troubleshooting with dig and nslookup for a full walk-through.

nmcli: configure the network

nmcli device status                       # devices and their state
nmcli connection show                     # saved connection profiles
nmcli connection show ens18               # all the settings of one profile

# Set a static IP address
sudo nmcli connection modify ens18 ipv4.method manual \
     ipv4.addresses 192.168.1.50/24 ipv4.gateway 192.168.1.1 ipv4.dns "1.1.1.1 8.8.8.8"
sudo nmcli connection up ens18            # apply it (you may lose SSH if the address changed!)

# Back to DHCP
sudo nmcli connection modify ens18 ipv4.method auto ipv4.addresses "" ipv4.gateway ""
sudo nmcli connection up ens18

sudo nmtui                                # a simple menu-based editor in the terminal
sudo hostnamectl set-hostname web01.example.com

If you change the IP address of a remote server, do it from the console, or schedule a revert, because the SSH session will drop. Since RHEL 9, NetworkManager stores profiles in /etc/NetworkManager/system-connections/ as key files; the old ifcfg files in /etc/sysconfig/network-scripts/ are no longer the default.

Time synchronisation

timedatectl                         # is "System clock synchronized" yes?
sudo timedatectl set-timezone Africa/Casablanca
chronyc tracking                    # how far off the clock is
chronyc sources -v                  # time servers in use

Chrony replaced ntpd. Wrong time breaks TLS certificates, Kerberos, logs and two-factor codes, so keep it synchronised.

12. The firewall: firewalld

RHEL uses firewalld, which manages the kernel firewall (nftables) through zones and services. Changes without --permanent apply immediately but vanish at reload or reboot. Changes with --permanent are saved but only active after --reload.

sudo systemctl enable --now firewalld
sudo firewall-cmd --state
sudo firewall-cmd --get-active-zones
sudo firewall-cmd --list-all                          # services, ports and rules of the default zone

sudo firewall-cmd --permanent --add-service=https     # open a named service
sudo firewall-cmd --permanent --add-port=8080/tcp     # open a port
sudo firewall-cmd --reload                            # activate the permanent changes

sudo firewall-cmd --permanent --remove-service=cockpit
sudo firewall-cmd --reload
firewall-cmd --get-services | tr ' ' '\n' | head      # known service names

Allow SSH only from one address

sudo firewall-cmd --permanent --remove-service=ssh
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="203.0.113.10" service name="ssh" accept'
sudo firewall-cmd --reload

Do this carefully. If your own address is not 203.0.113.10 you lock yourself out. Test with a second SSH session open, and keep console access in case something goes wrong.

sudo firewall-cmd --runtime-to-permanent       # save what you tested at runtime
sudo firewall-cmd --panic-on                   # block ALL traffic (emergency; --panic-off to undo)

13. SELinux

SELinux is a second layer of security: even when file permissions allow something, SELinux can still deny it if the program has no policy to do it. It is enabled by default on RHEL. When something works as root or with SELinux off but fails normally, SELinux is a prime suspect. Do not disable it: learn the six commands below instead.

getenforce                    # Enforcing, Permissive or Disabled
sestatus                      # more detail
sudo setenforce 0             # permissive until reboot: logs but does not block (for testing only)
sudo setenforce 1             # back to enforcing
ls -Z /var/www/html           # the SELinux label (context) of files
ps -eZ | grep httpd           # the context of running processes
id -Z                         # your own context

The permanent setting is in /etc/selinux/config (SELINUX=enforcing). A switch from disabled back to enforcing triggers a long relabel of all files at the next boot.

Fix 1: wrong file label (the most common problem)

Files copied or moved from another place can keep a wrong label. Reset labels to what the policy expects:

sudo restorecon -Rv /var/www/html

# A web folder in a non-standard place needs a rule, then a restore:
sudo dnf install policycoreutils-python-utils
sudo semanage fcontext -a -t httpd_sys_content_t "/srv/web(/.*)?"
sudo restorecon -Rv /srv/web

Use cp to put files in place (they get the label of the destination) rather than mv, which keeps the old label.

Fix 2: a service needs a non-standard port

sudo semanage port -l | grep http_port_t              # ports the web server may use
sudo semanage port -a -t http_port_t -p tcp 8088      # allow port 8088

Fix 3: a boolean switch

Booleans are ready-made on/off switches for common needs.

getsebool -a | grep httpd                       # all web server switches
sudo setsebool -P httpd_can_network_connect 1   # let the web server call other servers (APIs, a database)
sudo setsebool -P httpd_can_sendmail 1
sudo setsebool -P httpd_unified 1               # -P makes it permanent

Read the denials

sudo ausearch -m AVC -ts recent                 # recent denials ("AVC" = Access Vector Cache)
sudo ausearch -m AVC -ts today | audit2why      # explains in words, often with the fix
sudo dnf install setroubleshoot-server
sudo sealert -a /var/log/audit/audit.log        # human-readable analysis with suggested commands

As a last resort, you can build a small custom module for one specific denial: sudo ausearch -m AVC -ts recent | audit2allow -M mypolicy and then sudo semodule -i mypolicy.pp. Read what it allows first: this grants exactly the access that was denied, so make sure that is what you want.

14. SSH, scp and rsync

ssh user@server                      # log in
ssh -p 2222 user@server              # a different port
ssh -i ~/.ssh/mykey user@server      # a specific key
ssh user@server 'df -h'              # run one command and come back
ssh -J jump@bastion user@internal    # go through a jump host
ssh -L 8080:localhost:80 user@server # forward local port 8080 to port 80 on the server

ssh-keygen -t ed25519 -C "my laptop"    # create a key pair
ssh-copy-id user@server                 # install your public key on the server

scp file.txt user@server:/tmp/          # copy a file to a server
scp -r user@server:/var/log/app ./logs  # copy a folder from a server
rsync -avz --progress /data/ user@server:/backup/data/   # copy only what changed
rsync -avz --delete /data/ user@server:/backup/data/     # make the destination an exact mirror

With rsync a trailing slash matters: /data/ copies the content of the folder, /data copies the folder itself. Add --dry-run before using --delete to see what would be removed.

The server side is controlled by /etc/ssh/sshd_config and the files in /etc/ssh/sshd_config.d/. After a change, test it with sudo sshd -t and then sudo systemctl reload sshd. If you change the SSH port on a system with SELinux, also run semanage port -a -t ssh_port_t -p tcp 2222 and open the port in firewalld. Our guide How to Set Up SSH Key Login and Disable Password Authentication goes through the complete hardening.

15. Scheduling jobs

Cron runs commands on a schedule. Edit your own table with crontab -e. Each line has five time fields, then the command.

# minute  hour  day-of-month  month  day-of-week  command
30 2 * * *      /usr/local/bin/backup.sh              # every day at 02:30
*/15 * * * *    /usr/local/bin/check.sh               # every 15 minutes
0 9 * * 1-5     /usr/local/bin/report.sh              # weekdays at 09:00
@reboot         /usr/local/bin/start-tunnel.sh        # at boot
crontab -l                       # your jobs
sudo crontab -u bob -l           # another user's jobs
ls /etc/cron.d /etc/cron.daily   # system-wide jobs
journalctl -u crond --since today   # did it run?
echo "/usr/local/bin/one-off.sh" | at now + 10 minutes   # run once (needs the at package and atd)

Cron jobs run with a small environment, so use full paths to commands and scripts, and send output to a log: ... >> /var/log/backup.log 2>&1. For jobs that must catch up after downtime, use a systemd timer as shown in section 8.

16. Containers with Podman

Red Hat’s container tool is Podman. It works like Docker but has no background daemon, and it can run containers as a normal user (rootless). Install it with sudo dnf install podman. The commands match Docker’s, so what you know carries over (see Docker for Beginners).

podman pull docker.io/library/nginx
podman run -d --name web -p 8080:80 docker.io/library/nginx
podman ps                       # running containers;  -a shows stopped ones too
podman logs -f web
podman exec -it web /bin/sh     # a shell inside the container
podman stop web ; podman rm web
podman images ; podman rmi IMAGE
podman volume ls
sudo dnf install podman-docker  # makes the "docker" command call podman

To start a container at boot, define it as a systemd Quadlet file in /etc/containers/systemd/ (or ~/.config/containers/systemd/ for a user): a short .container file with Image= and PublishPort= lines, then systemctl daemon-reload and systemctl start the generated service. Remember to open the published port in firewalld.

17. Boot, kernel and recovery

uname -r                              # running kernel
sudo dnf upgrade kernel               # new kernels install beside the old ones
sudo grubby --default-kernel
sudo grubby --info=ALL | grep -E "^(index|kernel|title)"
sudo grubby --set-default /boot/vmlinuz-5.14.0-427.el9.x86_64
sudo reboot
lsmod | head                          # loaded kernel modules
sudo modprobe br_netfilter            # load a module now
sysctl net.ipv4.ip_forward            # read a kernel setting
sudo sysctl -w net.ipv4.ip_forward=1  # change it until reboot
# Permanent: put the line in /etc/sysctl.d/99-custom.conf and run: sudo sysctl --system

RHEL keeps the last few kernels (the installonly_limit setting in /etc/dnf/dnf.conf, default 3). If a new kernel fails to boot, choose an older one in the GRUB menu at startup.

Reset a lost root password (needs console access)

  1. Reboot, and at the GRUB menu press e to edit the first entry.
  2. Go to the line that starts with linux, press End, and add rd.break. Press Ctrl+X to boot.
  3. At the emergency prompt run:
mount -o remount,rw /sysroot
chroot /sysroot
passwd root
touch /.autorelabel      # important on SELinux systems
exit
exit

The system reboots, relabels the files (this takes a while on big disks) and you can log in with the new password. This is why physical or console access must be protected: anybody who can reach the console can do this. A GRUB password and an encrypted disk close that door.

Rescue and collecting information for support

sudo systemctl rescue                  # single-user mode (root password needed)
sudo systemctl isolate multi-user.target
sudo dnf install sos
sudo sos report                        # collects logs and configuration into one archive for Red Hat support

18. Security checks

ss -tulpn                              # what is listening? Close anything you do not use
sudo firewall-cmd --list-all           # what is allowed in?
sudo grep "Failed password" /var/log/secure | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head
sudo dnf upgrade --security            # apply security patches
sudo dnf updateinfo list security      # which advisories apply to this server
sudo rpm -Va | head                    # files changed since installation (config files will show up too)
sudo update-crypto-policies --show     # system-wide crypto level: DEFAULT, FUTURE, FIPS
sudo fips-mode-setup --check           # FIPS mode status
sudo dnf install fail2ban              # blocks addresses that keep failing to log in (from EPEL)
sudo auditctl -l                       # active audit rules

A short checklist for a new server: update everything, create a normal user with sudo, set up SSH keys and disable password logins, keep SELinux enforcing, keep firewalld on with only the needed services, enable automatic security updates and make sure the clock is synchronised. For public web servers, add HTTPS with Let’s Encrypt and Certbot.

19. Old commands and their modern replacement

Older tutorials online still show the commands from RHEL 6 and 7. Here is the translation.

Old way Use now
yum install pkg dnf install pkg (yum is only an alias)
service sshd restart systemctl restart sshd
chkconfig sshd on systemctl enable sshd
ifconfig ip a
route -n ip route
netstat -tulpn ss -tulpn
arp -a ip neigh
iptables -L firewall-cmd --list-all (or nft list ruleset)
ntpd, ntpdate chronyd, chronyc
edit /etc/sysconfig/network-scripts/ifcfg-eth0 nmcli or nmtui
/etc/init.d/script start systemctl start name
tail /var/log/messages journalctl -e (both still work)
docker podman
edit /etc/hostname and /etc/sysconfig/network hostnamectl set-hostname
cat /etc/crontab only crontab -e, /etc/cron.d and systemd timers

20. Habits that keep you out of trouble

  • Read before you run. Never paste a command from the internet into a root shell without understanding it. Be especially careful with curl ... | sudo bash.
  • Back up before you change. sudo cp -a /etc/ssh/sshd_config /etc/ssh/sshd_config.bak-$(date +%F) takes a second and saves hours.
  • Test, then reload. Most services can check their own config: sshd -t, nginx -t, httpd -t, named-checkconf, visudo -c, mount -a.
  • Keep a second SSH session open when you change SSH, the network or the firewall, so you can undo a mistake.
  • Be careful with destructive commands: rm -rf, dd (it writes straight to disks), mkfs, chmod -R, chown -R on /, and redirection with > that overwrites a file. Check the device or path twice.
  • Use the least power needed. Work as a normal user and use sudo for single commands, not a permanent root shell.
  • Do not disable SELinux or the firewall to “make it work”. Find the one rule that is missing and add it.
  • Write down what you change. A comment in the config file, or a note in a ticket, helps the next admin: often that is you in six months.

Quick answers

What is the difference between RHEL, Rocky Linux and AlmaLinux? RHEL is the commercial product from Red Hat, with a subscription and support. Rocky Linux and AlmaLinux are free, community-run rebuilds that are compatible with RHEL, so the commands, packages and file locations in this guide are the same. CentOS Stream is the upstream development stream that feeds the next RHEL minor release. Fedora is the faster-moving community distribution where new technology appears first.

Which commands should I learn first? ls, cd, cat, less, grep, find, sudo, dnf, systemctl, journalctl, ss and df/du. With these you can already install software, start services, read logs and check disk space and ports.

Where do I find the real documentation? Start with man pages on the server itself. Red Hat publishes its full product documentation free at docs.redhat.com, and it applies to the clones as well.

Did you find this helpful?Tap the heart to let us know. It takes one second and no account.

More tutorials like this

Leave a Comment

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

Bigland Network IT

Practical tutorials for people who run, build and fix things: operating systems, databases, development, networking and security.

Topics

More

Site

© 2026 Bigland Network. All rights reserved.Always test commands on a non-production system first.
Scroll to Top