0% found this document useful (0 votes)
30 views17 pages

Sysadmin Cheatsheet

Uploaded by

Uno Axie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views17 pages

Sysadmin Cheatsheet

Uploaded by

Uno Axie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

The Learn Linux TV Terminal Cheat Sheet

Essential Terminal Commands


It all starts with the basics! There's a great deal of Linux commands, so it can be difficult to keep track of them
all. Here's a list of useful commands, broken down by category.

File Management
Viewing Files and Directories

Command Effect

ls List files in the current directory

ls -l Long listing format (permissions, owner, size)

ls -a Show hidden files, those starting with "."

ls -lh Human-readable sizes

tree View directory tree (may need to install)

Navigation

Command Effect

cd /path/to/dir Change to a directory

cd .. Go up one directory.

cd ~ Go to the home directory

pwd Print current directory

Creating Files and Directories

Command Effect

touch file.txt Create a new empty file

mkdir new_folder Create a new directory

mkdir -p parent/child Create nested directories

Copying Files and Directories

Command Effect

cp file1.txt file2.txt Copy file

cp -r dir1/ dir2/ Copy directory recursively

cp -i file1.txt backup.txt Prompt before overwrite


Moving & Renaming

Command Effect

mv file.txt /new/location/ Move file to new location

mv oldname.txt newname.txt Rename file

mv -i file.txt /new/location/ Prompt before overwrite

Deleting Files and Directories

Command Effect

rm file.txt Delete file

rm -i file.txt Confirm before deleting

rm -r folder/ Recursively delete directory

rm -rf folder/ Force delete without prompt

Finding Files

Command Effect

find . -name "*.log" Find all .log files

find /path/to/search -type f -size +1M Find files over 1MB in /var/log

find /path/to/search -type f -mmin -10 Find files modified less than 10 minutes ago

find /path/to/search -type f -mtime -1 Find files modified less than 1 day ago

find /path/to/search -type d Find directories instead of files


File Permissions and Ownership

Command Effect

chmod +r file.txt Allow all users to read the file

chmod -r file.txt Prevent any user from reading the file

chmod +w file.txt Allow all users to make changes to the file

chmod -w file.txt Prevent any user from making changes to the file

chmod +x script.sh Allow all users to execute the file

chmod -x script.sh Prevent any users from executing the file

chmod u+r file.txt Allow the owner to read the file

chmod u-r file.txt Prevent the owner from reading the file

chmod u+w file.txt Allow the owner to make changes to the file

chmod u-w file.txt Prevent the owner from making changes to the file

chmod u+x script.sh Allow the owner to execute the file

chmod u-x script.sh Prevent the owner from executing the file

chmod g+r file.txt Allow the group to read the file

chmod g-r file.txt Prevent the group from reading the file

chmod g+w file.txt Allow the group to make changes to the file

chmod g-w file.txt Prevent the group from making changes to the file

chmod g+x script.sh Allow the group to execute the file

chmod g-x script.sh Prevent the group from executing the file

chmod o+r file.txt Allow others to read the file

chmod o-r file.txt Prevent others from reading the file

chmod o+w file.txt Allow others to make changes to the file

chmod o-w file.txt Prevent others from making changes to the file

chmod o+x script.sh Allow others to execute the file

chmod o-x script.sh Prevent others from executing the file

chmod 755 file.txt Set specific permissions (see table, below)

chown user:group file.txt Change ownership

chown -R user:group /path/to/dir Change ownership recursively (for directories)


File Permission Table

Permission Effect

777 Allow all users to read, write, and execute

755 Full permissions for owner; read and execute for group and others

700 Full permissions for owner; no permissions for group or others

666 Read and write for owner, group, and others

644 Read and write for owner; read-only for group and others

600 Read and write for owner; no permissions for group and others

555 Read and execute for owner, group, and others

440 Read-only for owner and group; no permissions for others

400 Read-only for owner; no permissions for group and others

711 Full permissions for owner; execute-only for group and others

Archiving & Compression

Command Effect

tar -cvf archive.tar folder/ Create archive with the contents of folder/

tar -xvf archive.tar Extract archive

tar -czvf archive.tar.gz folder/ Create compressed archive

tar -xzvf archive.tar.gz Extract compressed archive

Manipulating Text

Command Effect

sed 's/foo/bar/' file.txt Replace first occurrence of "foo" with "bar" per line

sed 's/foo/bar/g' file.txt Replace all occurrences of "foo" with "bar" per line

sed -i 's/foo/bar/g' file.txt Same as above, but edits the file in place

sed -n '3p' file.txt Print only the 3rd line of the file

sed -n '5,10p' file.txt Print lines 5 through 10

sed '/^#/d' file.txt Delete all lines starting with # (comments)

sed '/^$/d' file.txt Delete all blank lines

sed '1d' file.txt Delete the first line of the file

sed 's/[0-9]//g' file.txt Remove all digits from the file

sed 's/.*/[&]/' file.txt Wrap each line in square brackets


Package Management
apt

Command Effect

sudo apt update Update the package list from repositories

sudo apt upgrade Upgrade all installed packages to the latest version

sudo apt dist-upgrade Upgrade packages

sudo apt install package-name Install a specific package

sudo apt install package1 package2 Install multiple packages at once

sudo apt remove package-name Uninstall a package (keeping config files)

sudo apt purge package-name Uninstall a package and its config files

sudo apt autoremove Remove unused dependencies

sudo apt search keyword Search for packages matching a keyword

apt show package-name Display details about a package

sudo apt list --upgradable Show packages that can be upgraded

sudo apt clean Clear downloaded .deb package files from cache

sudo apt edit-sources Edit the APT sources list using the default editor

dnf

Command Effect

sudo dnf check-update Check for available package updates

sudo dnf update Update all packages to the latest available versions

sudo dnf upgrade Alias for update (preferred in newer versions)

sudo dnf install package-name Install a specific package

sudo dnf install pkg1 pkg2 Install multiple packages at once

sudo dnf remove package-name Uninstall a package

sudo dnf autoremove Remove unused dependencies

dnf search keyword Search for packages by keyword

dnf info package-name Show detailed info about a package

sudo dnf list --installed List all installed packages

sudo dnf list --available List all available packages

sudo dnf clean all Clear package cache and metadata

sudo dnf group list Show available software groups

sudo dnf group install "Group Name" Install a software group


zypper

Command Effect

sudo zypper refresh Refresh all enabled repositories

sudo zypper update Update all installed packages

sudo zypper up Alias for update

sudo zypper patch Apply official patches (recommended for SUSE systems)

sudo zypper install package-name Install a specific package

sudo zypper install pkg1 pkg2 Install multiple packages

sudo zypper remove package-name Uninstall a package

sudo zypper se keyword Search for packages matching a keyword

zypper info package-name Show detailed information about a package

sudo zypper list-updates List available updates

sudo zypper ps List processes using deleted libraries (post-update check)

sudo zypper clean --all Clear metadata and cache

zypper lr List all configured repositories

sudo zypper ar URL repo-alias Add a new repository

sudo zypper rr repo-alias Remove a repository

sudo zypper dup Perform a distribution upgrade (e.g., Tumbleweed snapshots)

System Management
Viewing System Information

Command Effect

hostname View system host name

hostnamectl View system information

uname -r View kernel version

uname -m View architecture


Resource Monitoring

Command Effect

df Show available disk space

df -h Show available disk space (human readable form)

du View disk usage for current working directory

du -h View disk usage for current working directory (human readable form)

du -sh folder/ View disk usage of a particular directory (with human readable output)

free Check the amount of free system memory

free -m Check the amount of free system memory (human readable form)

top Open the " top " process manager

htop Open the " htop " process manager (prettier, but may not be installed by default)

Copying/Transferring Files

Using scp :

Command Effect

scp file.txt user@remote:/home/user/ Copy a file from local to remote

scp user@remote:/home/user/file.txt . Copy a file from remote to local

scp -r folder/ user@remote:/home/user/ Copy a directory recursively

scp -P 2222 file.txt user@remote:/home/user/ Use a specific port (e.g., 2222)

scp -i ~/.ssh/id_rsa file.txt user@remote:/home/user/ Use an identity file (OpenSSH Key)

Using rsync :

Command Effect

rsync -avh --dry-run /source/ /destination/ Dry run (preview what will happen)

Sync a local directory to another local


rsync -avh /source/ /destination/
location

rsync -avh /local/dir/ user@remote:/remote/dir/ Sync a local directory to a remote server

rsync -avh user@remote:/remote/dir/ /local/dir/ Sync from remote server to local machine

rsync -avh --delete /source/ /destination/ Include deletion (mirror sync)

rsync -avh --progress largefile.iso


Show progress for large files
user@remote:/backup/

rsync -avh -e "ssh -p 2222" /source/


Use a specific SSH port
user@remote:/dest/

rsync -avh --exclude "*.log" /source/ /destination/ Exclude certain files or directories
Managing Processes

Command Effect

ps Show processes for the current shell session

ps -e Show all processes

ps -ef Show all processes in full-format listing

ps aux Show detailed info for all processes (BSD-style)

ps -u username Show processes for a specific user

ps -p 1234 Show info about process with PID 1234

ps -ef | grep nginx Find all processes related to "nginx"

ps --sort=-%mem | head Show top memory-consuming processes

ps --sort=-%cpu | head Show top CPU-consuming processes

kill PID Send default SIGTERM to the process with given PID

kill -9 PID Forcefully kill a process using SIGKILL

kill -15 PID Gracefully stop a process (SIGTERM, same as default)

kill -HUP PID Restart a process by sending SIGHUP

kill -l List all available signals

pkill processname Kill a process by its name

pkill -9 processname Forcefully kill all processes with that name

killall processname Kill all processes matching the exact name

xkill Graphically click on a window to kill it (X11 systems)


Managing Services

Note: Replace service with the name of the service you're working with.

Command Effect

systemctl status service Show status of the service

systemctl start service Start the service

systemctl stop service Stop the service

systemctl restart service Restart the service

Reload the service without stopping it (not supported on all


systemctl reload service
services)

systemctl enable service Enable the service to start on boot

systemctl disable service Disable the service from starting on boot

systemctl is-active service Check if the service is currently active

systemctl is-enabled service Check if the service is enabled to start at boot

systemctl list-units --
List all active services
type=service

systemctl list-unit-files List all unit files and their enablement state

Reload systemd manager configuration (after modifying unit


systemctl daemon-reload
files)

Formatting filesystems

Command Effect

mkfs.ext4 /dev/sdX1 Format partition as ext4

mkfs.xfs /dev/sdX1 Format partition as XFS

mkfs.vfat /dev/sdX1 Format partition as FAT32

mkfs.ntfs /dev/sdX1 Format partition as NTFS (requires ntfs-3g )

mkfs.btrfs /dev/sdX1 Format partition as Btrfs

mkfs -t ext4 /dev/sdX1 Specify filesystem type using -t

mkfs.ext4 -L "DATA" /dev/sdX1 Format ext4 with a volume label

mkfs.ext4 -m 0 /dev/sdX1 Set reserved block percentage to 0% (default is 5%)

mkfs -t ext4 -c /dev/sdX1 Check for bad blocks before formatting


Mounting filesystems

Command Effect

mount Show all currently mounted filesystems

mount /dev/sdX1 /mnt Mount a device to the /mnt directory

mount -t ext4 /dev/sdX1 /mnt Mount a partition as ext4 explicitly

mount -o ro /dev/sdX1 /mnt Mount the partition as read-only

mount -o loop image.iso /mnt Mount an ISO file as a loop device

mount -o uid=1000,gid=1000 /dev/sdX1 /mnt Mount with specific user and group ownership

mount -a Mount all filesystems from /etc/fstab

umount /mnt Unmount a mounted filesystem

umount /dev/sdX1 Unmount by device

umount -l /mnt Lazy unmount (force unmount, use sparingly)

mount -t nfs server:/share /mnt/nfs Mount an NFS share

mount -t cifs //server/share /mnt/smb -o Mount a Samba (Windows) share with


user=username authentication

IP Addressing and Routing

Command Effect

ip a Show all IP addresses (alias for ip addr )

ip addr show Show IP address details for all interfaces

ip addr show eth0 Show IP details for a specific interface

ip link show Show all network interfaces

ip link set eth0 up Enable the interface eth0

ip link set eth0 down Disable the interface eth0

ip route Display current routing table

ip route add default via 192.168.1.1 Set the default gateway

ip route add 10.0.0.0/24 via 192.168.1.1 Add a route to a specific network

ip -s link Show interface statistics

ip neigh Show ARP table (neighbor cache)

ip link set eth0 mtu 1400 Change the MTU of the interface
Inspecting open ports

Note: It's a good idea to check this regularly, to ensure nothing is open that shouldn't be.

Command Effect

ss Show summary of socket connections

ss -t Show only TCP connections

ss -u Show only UDP connections

ss -l Show listening sockets only

ss -tuln Show all listening TCP/UDP ports in numeric form

ss -s Display summary statistics

ss -p Show process using each socket

ss -tnp Show TCP sockets with process info

ss -a Show all sockets (listening and non-listening)

ss -o state established '( dport = :ssh )' Show established SSH connections

ss -H Suppress header line in output

DNS Querying

Note: Although nslookup is said to be deprecated, that's no longer true.


Both nslookup and dig are usful tools.

Using dig :

Command Effect

dig example.com Perform a basic DNS lookup for A record

dig example.com A Explicitly query for the A (IPv4 address) record

dig example.com AAAA Query for the IPv6 address (AAAA record)

dig example.com MX Query mail exchange (MX) records

dig example.com NS Query name server (NS) records

dig example.com TXT Query for TXT records (e.g., SPF, DKIM info)

dig @8.8.8.8 example.com Use a specific DNS server (e.g., Google DNS)

dig +short example.com Output only the result (useful for scripts)

dig +noall +answer example.com Show only the answer section

dig -x 8.8.8.8 Perform a reverse DNS lookup

dig +trace example.com Trace DNS path from root servers to authoritative server
Using nslookup :

Command Effect

nslookup example.com Basic A record lookup for a domain

nslookup (then type example.com ) Interactive mode query

nslookup -type=mx example.com Lookup mail exchange (MX) records

nslookup -type=ns example.com Lookup name server (NS) records

nslookup -type=txt example.com Lookup TXT records (e.g., SPF, DKIM)

nslookup -type=soa example.com Get the Start of Authority (SOA) record

nslookup -type=aaaa example.com Lookup IPv6 address (AAAA record)

nslookup -port=53 example.com Query using a specific port (default is 53)

nslookup example.com 8.8.8.8 Query a specific DNS server (Google DNS here)

nslookup -debug example.com Enable debug mode for detailed output

nslookup -type=any example.com Request all available DNS record types

nslookup -type=ptr 8.8.8.8 Reverse DNS lookup (PTR record)

nslookup (then server 8.8.8.8 ) Change the default DNS server in interactive mode

nslookup (then set timeout=10 ) Set query timeout in interactive mode

nslookup (then set retry=5 ) Set number of retries in interactive mode

Connecting to Remote Systems

Command Effect

ssh user@host Connect to a remote host as a user

ssh -p 2222 user@host Connect using a non-default port (for example, 2222)

ssh -i ~/.ssh/id_rsa user@host Connect using a specific private key

ssh user@host 'ls -la' Run a single command remotely and display output locally

Forward local port 8080 to remote port 80 (local port


ssh -L 8080:localhost:80 user@host
forwarding)

Allow remote host to access your local SSH (remote port


ssh -R 9090:localhost:22 user@host
forwarding)

ssh -N -f -L 3306:localhost:3306 Create a background tunnel without executing remote


user@host commands

Copy local SSH public key to remote host for passwordless


ssh-copy-id user@host
login

ssh -T [email protected] Test SSH authentication without opening a shell

Common Files and Their Purpose


Common /var/log Files and Their Purpose

Log File Purpose

General system log (Debian/Ubuntu); contains messages from many


/var/log/syslog
sources

General system log (RHEL/CentOS/Fedora); includes kernel and service


/var/log/messages
logs

/var/log/dmesg Kernel ring buffer; logs hardware-related messages during boot

/var/log/auth.log Authentication log (Debian/Ubuntu); tracks sudo, ssh, login attempts

/var/log/secure Authentication log (RHEL/CentOS/Fedora); similar to auth.log

/var/log/kern.log Kernel log messages

/var/log/boot.log Boot process messages

/var/log/faillog Failed login attempts

/var/log/lastlog Last login information for users

/var/log/wtmp Binary log of logins/logouts (viewable via last )

/var/log/btmp Failed login attempts (viewable via lastb )

/var/log/apt/history.log Package installation history (Debian-based systems)

/var/log/yum.log Yum package manager log (RHEL/CentOS/Fedora)

/var/log/httpd/access_log Web server access log (Apache on RHEL)

/var/log/httpd/error_log Web server error log (Apache on RHEL)

/var/log/nginx/access.log Nginx access log

/var/log/nginx/error.log Nginx error log

/var/log/Xorg.0.log X server (graphical interface) startup log

Security Hardening
General Tips
Consider the following tips as you navigate your career. While some may seem obvious, each are important!

Be sure to install updates as soon as they're released, many include important security fixes

Better yet, enable automatic updates (and consider live-patching)

Make sure you harden OpenSSH (see table in the next section)

Regularly audit open connections, and investigate any you're unfamiliar with

Use two-factor, on everything

Consider a password manager (such as Bitwarden) to avoid a situation where you can't log in to a server to
fix it

Check open ports with the ss command regularly, and stop services with systemctl that you don't use

Lock the root account

If a server isn't used at all after working hours, schedule it to shut down in the evening and start in the
morning

If you use cloud instances, regularly audit your bill to avoid unexpected surprises
Regularly test your backups! Backups that aren't tested can't be trusted

Audit backups regularly, to ensure everything that's critical is accounted for

Audit users and permissions, and remove any that aren't being used

Always use LVM while building an instance, as it gives you the ability to expand storage later

If your server uses LVM, be sure to back up each volume (otherwise the backup is not restorable)

Consider an automation system (such as Ansible) to help avoid human-error

Important! Please understand you don't have to memorize everything. Pro Linux admins memorize only
the commands they use often, and write notes for infrequent commands.

Common OpenSSH Hardening Settings

Recommended Setting Description

PermitRootLogin no Disables root login via SSH to prevent brute-force attacks on root

PasswordAuthentication
Disables password-based login; enforces key-based authentication
no

Protocol 2 Ensures only SSH protocol version 2 is used (version 1 is insecure)

MaxAuthTries 3 Limits the number of authentication attempts per connection

Reduces the time (in seconds) before an unauthenticated session is


LoginGraceTime 30
dropped

AllowUsers user1 user2 Restrict SSH access to specified users only

AllowGroups sshusers Restrict SSH access to members of a specific group

ClientAliveInterval 300 Sends keep-alive messages every 300 seconds

ClientAliveCountMax 2 Disconnects after 2 missed keep-alive responses

X11Forwarding no Disables X11 forwarding to reduce potential attack surface

UseDNS no Speeds up login by skipping reverse DNS lookups

LogLevel VERBOSE Increases log detail for monitoring/authentication events

Banner /etc/issue.net Displays a legal warning or login banner before authentication

Note: Be sure to restart the ssh service (Debian/Ubuntu) or the sshd service (other distributions) to apply the
changes
Working with Firewalls (UFW)
For distributions that ship UFW (uncomplicated firewall) consider the following commands for managing rules:

Command Effect

sudo ufw status Display the current firewall status and rules

sudo ufw enable Enable the firewall and start enforcing rules

sudo ufw disable Disable the firewall

sudo ufw default deny incoming Deny all incoming connections by default

sudo ufw default allow outgoing Allow all outgoing connections by default

sudo ufw allow 22 Allow incoming SSH (port 22)

sudo ufw allow 80,443/tcp Allow HTTP and HTTPS traffic

sudo ufw allow from 192.168.1.0/24 Allow all traffic from a specific subnet

sudo ufw allow from 10.0.0.5 to any port


Allow SSH access only from a specific IP
22

sudo ufw delete allow 22 Remove a rule that allows port 22

sudo ufw deny 25 Block port 25 (SMTP)

Throttle SSH attempts to prevent brute-force


sudo ufw limit ssh
attacks

sudo ufw reload Reload firewall rules

Note: You may need to install the ufw package


Working with Firewalls (firewall-cmd)
For distributions that utilize firewall-cmd , use the following commands:

Command Effect

sudo firewall-cmd --state Check if firewalld is running

sudo firewall-cmd --reload Reload firewall configuration

sudo firewall-cmd --get-active-zones Show active zones and interfaces

sudo firewall-cmd --get-services List all predefined services

sudo firewall-cmd --zone=public --list-all Show all rules in the "public" zone

Temporarily allow HTTP in the "public"


sudo firewall-cmd --zone=public --add-service=http
zone

sudo firewall-cmd --zone=public --add-port=8080/tcp Temporarily allow TCP port 8080

sudo firewall-cmd --zone=public --remove- Temporarily block SSH in the "public"


service=ssh zone

sudo firewall-cmd --permanent --add-service=https Permanently allow HTTPS

sudo firewall-cmd --permanent --remove-port=21/tcp Permanently block FTP (port 21)

Save current rules to permanent


sudo firewall-cmd --runtime-to-permanent
configuration

sudo firewall-cmd --zone=internal --change-


Assign interface eth1 to internal zone
interface=eth1

Jay's favorite aliases


Add any of the following to your ~/.bashrc file to activate an alias, which will give extended abilities.
After adding it, restart your shell to use the new command.
For example, the first alias lets you use the cpu5 command to view the top 5 CPU-using processes.

View the top 5 CPU-consuming processes:

alias cpu5='ps auxf | sort -nr -k 3 | head -5'

View the top 10 CPU-consuming processes:

alias cpu10='ps auxf | sort -nr -k 3 | head -10'

View the top 5 memory-consuming processes:

alias mem5='ps auxf | sort -nr -k 4 | head -5'

View the top 10 memory-consuming processes:

alias mem10='ps auxf | sort -nr -k 4 | head -10'

View your public IP anytime:

alias extip='curl icanhazip.com'

View a local weather report:

alias weather='curl wttr.in'

Helpful Tricks & Tweaks


Helpful Tricks & Tweaks
Here's some tips that will help you along your Linux journey.

Re-run the most recent command (but with sudo )


If you forget to use sudo , enter the following immediately after to add sudo to the most recent command:
sudo !!

View system information when you log in to a system:


Add the following to your ~/.bashrc file:
hostnamectl

Automatic ls while changing directories:


If you want to have your shell automatically run the ls command every time you change directory with cd ,
add the following to your ~/.bashrc file:

function cd() {
new_directory="$*";
if [ $# -eq 0 ]; then
new_directory=${HOME};
fi;
builtin cd "${new_directory}" && /bin/ls -lhF --time-style=long-iso --color=auto --
ignore=lost+found
}

You might also like