
Useful Linux Commands
Created: 2018-09-11 04:23:11 | Last modified: 2025-12-08 19:37:26Access: Read | Views: 581 | Rating: N/A | Tags: linux
Here is a list of useful Linux commands
Core Operating System
# View that status of a service
systemctl status SERVICE
# Follow/tail a service a service logs (add --output cat to view color outpud)
journalctl --follow _SYSTEMD_UNIT=SERVICE.service
Grub
To manually boot an operating system from grub
- You can use ls to get the available partitions e.g. (hd0,msdos1).
- msdos1 can be abbreviated to just 1 e.g. (hd0,1)
- You can view the available kernels by using something like ls (hd0,1)/ and into other directories e.g. ls (hd0,1)/grub2/
set prefix=(hd0,1)/grub2
set root=(hd0,1)
insmod normal
normal
insmod linux
linux /vmlinuz-4.18.0-348.el8.x86_64 root=/dev/mapper/almalinux-root ro
initrd /initramfs-4.18.0-348.el8.x86_64.img
boot
We had an issue with Alma Linux booting after it upgraded grub. We managed to get into the operating system by using the commands above. But to fix it permidenantly
# Edit the grub file
vi /etc/default/grub
# Change this line to false
### set: GRUB_ENABLE_BLSCFG=false
# Save vi file (:wq) - Then enter the follow commands to rebuild grub
grub2-mkconfig -o /boot/grub2/grub.cfg
grub2-install /dev/xvda
File System
Delete a list of files that are older than X days
find /path/to/files* -mtime + -delete
#Example - Delete everything in the current directory older than 365 days find . -mtime +365 -delete #Example - You can omit the -delete flag to just find the files and not delete them find . -mtime +365 -delete
Getting the size of directories in Linux
# Get the size of all directories under root
du -sh /*
# Get the size of all directories under root but exclude /backup
du -sh --exclude=/backup /*
# Get the size of all files in current directory and output delimited by a comma
du -hs * | awk -F'\t' '{print $1 "," $2;}'
# Do a du of all files and sort by size and show modified date
du -h --time * | sort -h
Using smartctl to view details and status of a hard drive
# View information about a drive
smartctl -i /dev/sdb
# Run a short test | Other available tests short|long|conveyance|select
sudo smartctl -t short /dev/sdc
# View SMART (S.M.A.R.T) status of a drive / test results
smartctl -a /dev/sdb
FSCK - Fix Filesystem
# Run full scan and fix bad blocks
fsck -pvcf
Shred - Destroy a drive
# Locate the drive to be destroyed
lsblk
# Destroy the drive with 3 writes (example drive from lsblk nvme0n1)
sudo shred -vfz -n 3 /dev/nvme0n1
SSH
Enable SSH for a root user
#Edit the file
vim /etc/[ssh]/sshd_config
#Change this line to yes
PermitRootLogin yes
#Restart sshd
systemctl restart sshd
Users and Groups
# List groups for user
groups USER
#Add a user to group
usermod -a -G GROPU USER
# Remove a user from a group
gpasswd -d USER GROUP
# Make this group the primary group of the user
usermod -g GROUP USER
# Delete a user
# add -r option to delete home directory too
# add -f option to force the deletion of the user
userdel USER
# Add a user with root permissions
Set hostname
On versions of RHEL greater than 9, use the following command to set the hostname
# Get hostname details
hostnamectl
# Set the hostname
hostnamectl set-hostname NEWHOSTNAME
Copy
# Recursive copy with permissions cp -Rp source destination
Terminal
When you start seeing weird characters after grepping a binary file

You can rest the terminal user the following command;
clear
echo -e "\033c"
Time zone
To set the time zone on a Centos 8 server
# Get time details timedatectl # List available time zones timedatectl list-timezones # Set a time zone timedatectl set-timezone TIMEZONE # Example time zone set timedatectl set-timezone Pacific/Auckland # Verify time zone has been set timedatectl
Resetting the date and top NTP servers
sudo service ntpd stop sudo ntpdate sudo service ntpd start
Certificate/SSL Check
To check the validity of a certificate and/or SSL connection, you can run the following command. In this example, the IP address is 111.111.111.111 and the SSL port to check is 443. You can use different ports e.g. 5061 for VOIP with SSL.
openssl s_client -connect 111.111.111.111:443
Yum
Examples of using YUM
#Get the history of yum installs yum history yum history list all
#View installed packages
yum list installed | grep package_name #Get the details of a particular event (use ID) yum history info yum history info 22 #Downgrade a package yum downgrade package_name #Downgrade to a particular date/update run yum history undo 22 #Remove a package yum remove yum remove http #Exclude a package during upgrade (where PackageName is the package to exclude) yum upgrade --exclude PackageName yum update --exclude PackageName
Bash History - You can search through your CLI history using the following, this eliminates the need to manually type out the command every time.
CTRL+R #Reverse Search for yum example. CTRL+R and then type part of the command (reverse-i-search)`yum': yum update CTRL+R #When in search, pressing CTRL+R again searches back further (reverse-i-search)`yum': yum -y install program
Show a list of CLI command history. You can apply the following so that the date/time is shown when running the command;
# Show History history # Add date/time to history format HISTTIMEFORMAT="%d/%m/%y %T " history
ports
Get a list of listening ports in Linux
#See all listening ports (note: "yum install net-tools" maybe required) lsof -i -P -n | grep LISTEN
netstat -tulpn | grep LISTEN
#Get details of a particular listening port netstat -ltnp | grep -w ':22'
Printers
# Send a print job to printer [PrinterName] with file [File]
lpr -P [PrinterName] [File]
iptables
# List of ports in iptables with numeric port numbers iptables --list --numeric # Block an IP address using iptables (where 111.111.111.111 is the IP address you wish to block) iptables -I INPUT 1 -s 111.111.111.111 -j DROP # Allow for only a port from a specific address iptables -I INPUT -p tcp -s 111.111.111.111 --dport 22 -j ACCEPT # Redirect ports inside iptables e.g. redirect port 80 to port 8080 iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080 # Example of allowing https from everywhere iptables -I INPUT -p tcp -s 0.0.0.0 --dport 443 -j ACCEPT # Insert a rule (https) before a specific line number (in this example 3) iptables -I INPUT 3 -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT # Save iptables service iptables save
Remove a rule
# List the iptables rules with line number iptables -L --line-numbers # Delete the line number iptables -D INPUT 3 # Save IP Tables service iptables save
Example of blocking all IPs apart from 111.111.111.111
# Flush IPTables - Deletes all rules (use carefully)
iptables -F
# Default policy to drop all incoming traffic
iptables -P INPUT DROP
# Allow incoming traffic from 103.248.200.4
iptables -A INPUT -s 111.111.111.111 -j ACCEPT
# Allow loopback traffic (important for local processes)
iptables -A INPUT -i lo -j ACCEPT
# Allow established and related connections (to avoid breaking active connections)
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
Saving in Ubuntu
# Install the iptables-persistent package (if not already done) - Select yes when being asked to save the rules
apt install iptables-persistent
# Save IPTables at any time
netfilter-persistent save
firewall-cmd
Add and list firewall ports in Centos 7 with (firewall-cmd or firewallcmd)
Add --permanent to make it permanant
# List all firewall-cmd --list-all firewall-cmd --list-ports # Add a port firewall-cmd --zone=public --add-service=http firewall-cmd --zone=public --add-port=80/tcp --permanent # Remove a port firewall-cmd --zone=public --remove-port=80/tcp --permanent # Add a new zone, eg. newZone firewall-cmd --permanent --new-zone=newZone # Reload the firewall to make the changes take effect firewall-cmd --reload # List all zones and ports/services firewall-cmd --list-all-zones
Example of allowing only a specific IP address to a port. This needs to be done with a zone, example is adding SSH as a service and removing it from the public zone
# List if any sources are available for the zone firewall-cmd --permanent --zone=trusted --list-sources # Create the zone 'trusted' with the source IP address of 192.168.0.55 firewall-cmd --permanent --zone=trusted --add-source=192.168.0.55/32 # Add an SSH service to the allowed list firewall-cmd --permanent --zone=trusted --add-service=ssh # Remove SSH from the public zone firewall-cmd --permanent --zone=public --remove-service=ssh # Reload the firewall to apply your changes firewall-cmd --reload # Check and confirm everything has been added as expected firewall-cmd --zone=trusted --list-all
Example of adding an IP source and port policy. From 111.111.111.111 and UDP port 161
# Add the rule
firewall-cmd --permanent --zone=public --add-rich-rule='
rule family="ipv4"
source address="111.111.111.111/32"
port protocol="udp" port="161" accept'
# Save the config and list all of the rules
firewall-cmd --reload
firewall-cmd --list-all
# You can use --remove-rich-rule to remove any rules
tcpdump
Dump TCP/UDP traffic information
# Standard Example tcpdump # TCPDump without address translation tcpdump -n # TCPDump without address and port translation tcpdump -nn # TCPDump excluding port 22 tcpdump not port 22 # TCPDump for wireshark (as a capture, tcpdump.pcap is the captured file) tcpdump -s 0 -i eth0 -w tcpdump.pcap
PostFix
# Delete all messages in postfix queue
postsuper -d ALL
# Delete a single message in the postfix queue, where [message id] is the message id
postsuper -d [message id]
ping
Ping with a specific size and a do not fragment option. Assuming an MTU setting of 1500, subtract 28 to get the packet size to use, so for a 1500 MTU you would use 1472
ping -s 2000 -M do 192.168.0.1
Ping from a specific source interface (where eth2 is the interface in this example)
ping -I eth2 10.16.1.20
Speed test
You can run a speed test through the CLI using the following commands;
curl -s https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py | python -
Text
# Tail a file, prints out text as it is added to the text file tail -f filename # Grep for SEARCH in a file and show line number grep -n search fileName # Grep for SEARCH and show 5 lines before (-B) and 5 lines after (-A) grep -B 5 -A 5 search fileName
Misc
Get the UUID of a network interface (used for adding to /etc/sysconfig/network-scripts/ifcfg-ethx.cfg
uuidgen ifcfg-eth0
Disable write cache on a harddrive
# View if cache is enabled hdparm -W /dev/sda # Disable the write cache on the hard drive hdparm -W0 /dev/sda
View a list of the last logged in users
last THEUSERNAME
Clear the ARP cache in Linux - This is useful for stale ARP entries
ip neigh flush all
Mount a volume and make to persistent/permanent
# Mount a drive mount /dev/sdb1 /mnt/a_new_folder
# Make it persistent vim /etc/fstab #Add the following line /dev/sdb1 /archive xfs defaults 0 0
# Example for a dirve /dev/xvdb1 to a mount point /archive

Check Linux last shutdown and reboot times
# Check the last reboot (when the system was booted) last -x reboot # Check the last shutdown (when the system was shutdown) last -x shutdown
Linux Mail with an attachment (note -a or -A not working on some systems)
mail [email protected] -a theAttachment.pdf
Get a list of messages and responses from the maillog for a specific email address.
This will search for a list of emails, get the email id from the 6th spaced column, echo the message information for that message id, insert some ##### between each line and output it to messageList.log
for i in `grep -i "[email protected]" /var/log/maillog | awk '{print $6}'`; do grep -i $i /var/log/maillog; echo '#########################'; done > messageList.log
Zip a file using Linux (Recursive)
zip -r zipfile.zip file_or_folder
Sort Linux processes by memory using the PS command
ps -o pid,user,%mem,command ax | sort -b -k3 -r

Kill processes (or single) inside Linux
# Kill a single process where 2325 is the process kill 2325 # Kill all processes killall -9 httpd #Centos 6 pkill -9 http #Centos 7
Clear Logs - When a log file gets to large or doesn't automatically rotate you can clear/truncate the log using the following command
# Truncate
truncate -s 0 logfile
# Clear with null
cat /dev/null > logfile.log
DNS Logging (Bind)
You can enable and disable query logging using the following command. The results are displayed in /var/log/messages
rndc querylog # View the results tail -f /var/log/messages
Do an SNMP walk
snmpwalk -v2C -c public 111.111.111.111 system
Install of Webmin on Centos. Just copy and paste the following into the terminal and Webmin will install.
(echo "[Webmin] name=Webmin Distribution Neutral baseurl=http://download.webmin.com/download/yum enabled=1 gpgcheck=1 gpgkey=http://www.webmin.com/jcameron-key.asc" >/etc/yum.repos.d/webmin.repo; yum -y install webmin)