Skip to content

Linux-Debian (Kali) Command Cheatsheet

Overview

Linux-Debian (Kali) Fundamentals

Kali Linux is a Debian-derived distribution designed for digital forensics and penetration testing:

  • APT Package Management: Debian's Advanced Package Tool
  • Bash Environment: Customizable shell and path configuration
  • File Permissions: Unix-style permission system (read/write/execute)
  • Process Management: Tools for monitoring and controlling system processes
  • Networking: Comprehensive network analysis and manipulation tools

[SP] System & Package Management

[APT] Package Management

APT Package Management

Command Description Common Use
apt update Refresh package lists sudo apt update
apt upgrade Upgrade installed packages sudo apt upgrade
apt install Install new packages sudo apt install nmap
apt remove Remove packages sudo apt remove package
apt search Search for packages apt search "security scanner"

Basic Operations

Essential APT Commands

# Update package database
sudo apt update

# Upgrade all installed packages
sudo apt upgrade

# Full upgrade (may remove packages)
sudo apt full-upgrade

# Install specific package
sudo apt install nmap wireshark metasploit-framework

# Remove package (keep config files)
sudo apt remove package-name

# Remove package and config files
sudo apt purge package-name

# Search for packages
apt search "penetration testing"

# Show package information
apt show nmap

# List installed packages
apt list --installed

# Clean up package cache
sudo apt autoremove
sudo apt autoclean

Common Issues

  • Use sudo for system-wide operations
  • apt update before apt upgrade
  • full-upgrade may remove conflicting packages
  • Check dependencies with apt-cache depends

Advanced Package Operations

Advanced APT Usage

# Download package without installing
apt download package-name

# Install specific version
sudo apt install package-name=version

# Hold package at current version
sudo apt-mark hold package-name

# Show changelog
apt changelog package-name

# Check for broken dependencies
sudo apt --fix-broken install

# Show package statistics
apt stats

[DPKG] Low-Level Package Management

DPKG - Direct Package Management

# Install local .deb package
sudo dpkg -i package.deb

# Remove package
sudo dpkg -r package-name

# List installed packages
dpkg -l

# Show package contents
dpkg -L package-name

# Find which package owns a file
dpkg -S /usr/bin/nmap

# Reconfigure package
sudo dpkg-reconfigure package-name

# Fix broken packages
sudo dpkg --configure -a

[FM] File Management

[PERM] File Permissions

Understanding Linux Permissions

Linux uses a 3-tier permission system:

  • User (u): File owner permissions
  • Group (g): Group member permissions
  • Others (o): Everyone else permissions

Permission Types: - Read (r): 4 - View file contents - Write (w): 2 - Modify file contents - Execute (x): 1 - Run as program

Permission Management

chmod - Change File Permissions

# Symbolic notation
chmod u+x script.sh          # Add execute for owner
chmod g-w file.txt           # Remove write for group
chmod o=r file.txt           # Set others to read-only
chmod a+w file.txt           # Add write for all (a=all)

# Octal notation (most common)
chmod 755 script.sh          # rwxr-xr-x (owner:rwx, group:r-x, others:r-x)
chmod 644 file.txt           # rw-r--r-- (owner:rw-, group:r--, others:r--)
chmod 600 secret.txt         # rw------- (owner:rw-, no access for others)

# Recursive directory permissions
chmod -R 755 directory/      # Apply to directory and contents
chmod -R u+w directory/      # Add write for owner recursively

# Common permission patterns:
# 755 - Executables, scripts
# 644 - Regular files, documents  
# 600 - Private files, keys
# 777 - Full access (dangerous!)

chown - Change File Ownership

# Change owner
sudo chown username file.txt

# Change owner and group
sudo chown username:group file.txt

# Change group only
sudo chgrp groupname file.txt

# Recursive ownership change
sudo chown -R username:group directory/

# Common usage patterns:
sudo chown www-data:www-data /var/www/html
sudo chown kali:kali ~/tools

Special Permissions

Advanced Permission Flags

# SetUID - Run as file owner
chmod u+s /usr/bin/passwd    # Always runs as root

# SetGID - Run as file group  
chmod g+s /usr/bin/write     # Runs as tty group

# Sticky Bit - Directory protection
chmod +t /tmp                # Only owner can delete files in /tmp

# Combined examples:
chmod 4755 script.sh         # SetUID with standard permissions
chmod 2755 directory/        # SetGID on directory
chmod 1777 /tmp              # Sticky bit on world-writable directory

[OPS] File Operations

Essential File Operations

# Copy files and directories
cp file1.txt file2.txt
cp -r dir1/ dir2/            # Recursive copy
cp -a source/ destination/    # Archive mode (preserve everything)

# Move/rename files
mv oldname.txt newname.txt
mv file.txt /path/to/destination/

# Remove files and directories
rm file.txt
rm -r directory/             # Recursive remove
rm -f file.txt               # Force remove (no prompt)

# Create directories
mkdir newdir
mkdir -p path/to/nested/dir  # Create parent directories

# View file contents
cat file.txt                 # Display entire file
less file.txt                # Page through file
head -n 10 file.txt          # First 10 lines
tail -n 10 file.txt          # Last 10 lines
tail -f logfile.txt          # Follow (live view)

File Finding & Analysis

Finding Files

# find command - most powerful
find /home -name "*.txt"                    # Find by name
find /var/log -type f -name "*.log"         # Only files
find / -type d -name "config" 2>/dev/null   # Only directories
find . -size +1M                            # Files larger than 1MB
find /etc -mtime -7                         # Modified in last 7 days

# locate - faster but depends on database
sudo updatedb                              # Update file database
locate "*.conf"
locate passwd

# which - find executables in PATH
which nmap
which python3

# whereis - find binaries, sources, manuals
whereis ls
whereis -b nmap                            # Only binaries

[USR] User & Environment

[ENV] Environment Variables

Understanding Environment Variables

Environment variables control shell behavior and store system information:

  • PATH: Directories searched for executables
  • HOME: User's home directory
  • USER: Current username
  • SHELL: Current shell program
  • PWD: Present working directory

Environment Management

Viewing and Setting Environment Variables

# View all environment variables
env
printenv

# View specific variable
echo $PATH
echo $HOME
printenv USER

# Set temporary variable (current session only)
export MY_VAR="value"
export PATH=$PATH:/new/directory

# Set for single command only
MY_VAR="value" command_name

# Remove variable
unset MY_VAR

# Common PATH modifications:
export PATH=$PATH:/usr/local/bin
export PATH=$HOME/tools:$PATH              # Prepend to PATH

Adding to PATH

Permanently Adding to PATH

# Temporary addition (current terminal only)
export PATH=$PATH:/home/kali/my_tools

# Permanent addition - edit ~/.bashrc
nano ~/.bashrc
# Add line:
export PATH=$PATH:/home/kali/my_tools

# Reload bash configuration
source ~/.bashrc
# or
. ~/.bashrc

# Verify PATH
echo $PATH | tr ':' '\n'

# Check if command is in PATH
which new_command

[BASHRC] Bash Configuration

Bash Configuration File

# Edit bash configuration
nano ~/.bashrc
nano ~/.bash_profile        # For login shells

# Common .bashrc additions:

# Aliases for frequently used commands
alias ll='ls -la'
alias ..='cd ..'
alias grep='grep --color=auto'
alias ports='netstat -tulpn'

# Custom prompt
PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

# Environment variables
export EDITOR=nano
export HISTSIZE=10000
export HISTFILESIZE=20000

# Function definitions
function mkcd() {
    mkdir -p "$1" && cd "$1"
}

# Source other files
if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

Useful Bash Aliases for Kali

# Penetration testing aliases
alias scan='nmap -sC -sV -O'
alias quickscan='nmap -T4 -F'
alias vulnscan='nmap --script vuln'
alias webscan='gobuster dir -u'

# Network aliases
alias myip='curl ifconfig.me'
alias ports='netstat -tulpn'
alias listen='lsof -i -P -n | grep LISTEN'

# System monitoring
alias meminfo='free -m -l -t'
alias cpuinfo='lscpu'
alias diskusage='df -h'

# Git shortcuts
alias gs='git status'
alias gc='git commit'
alias gp='git push'

# Safety nets
alias rm='rm -i'              # Confirm before remove
alias cp='cp -i'              # Confirm before overwrite
alias mv='mv -i'              # Confirm before move

[NET] Networking

[SCAN] Network Scanning

Network Discovery Commands

# Show network interfaces
ip addr show
ip link show
ifconfig                    # Legacy, may not be installed

# Show routing table
ip route show
route -n

# Check connectivity
ping google.com
ping -c 4 8.8.8.8          # Send 4 packets

# Trace route
traceroute google.com
tracepath google.com

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

# Network statistics
ss -tuln                    # Show listening ports
netstat -tuln               # Legacy equivalent
ss -tulpn                   # Show processes with ports

Advanced Network Tools

Kali-Specific Network Commands

# Nmap - network scanner
nmap 192.168.1.0/24                    # Network discovery
nmap -sS -sV -O target.com             # Stealth scan + version + OS
nmap -p 1-1000 target.com              # Port range scan
nmap --script vuln target.com          # Vulnerability scripts

# Netcat - network Swiss army knife
nc -zv target.com 1-1000               # Port scanning
nc -lvnp 4444                          # Listen for connection
nc target.com 80                       # Connect to service

# Tcpdump - packet analyzer
tcpdump -i eth0                        # Capture on interface
tcpdump host 192.168.1.100             # Capture specific host
tcpdump port 80                        # Capture HTTP traffic

# Wireshark/tshark
tshark -i eth0 -f "tcp port 80"        # Command-line packet capture

[CONN] Network Connections

File Transfer & Remote Access

# SCP - Secure copy
scp file.txt user@remote:/path/        # Copy to remote
scp user@remote:/path/file.txt .       # Copy from remote
scp -r directory/ user@remote:/path/   # Recursive copy

# SSH - Secure shell
ssh user@remote-server.com
ssh -p 2222 user@remote.com            # Custom port
ssh -i key.pem user@remote.com         # Key authentication

# wget - File download
wget https://example.com/file.zip
wget -O custom-name.zip https://example.com/file.zip
wget --user=username --password=pass https://example.com/file.zip

# curl - Data transfer
curl -O https://example.com/file.zip
curl -o custom-name.zip https://example.com/file.zip
curl -u username:password https://example.com/file.zip

# HTTP server (useful for file sharing)
python3 -m http.server 8000            # Python 3
python -m SimpleHTTPServer 8000        # Python 2

[PRC] Process Management

[PS] Process Control

Understanding Linux Processes

  • PID: Process ID (unique number)
  • PPID: Parent Process ID
  • UID: User ID of process owner
  • State: Running, sleeping, zombie, etc.

Process Monitoring Commands

# View running processes
ps aux                    # All processes detailed format
ps -ef                    # Full format listing
ps aux | grep "process-name"

# Interactive process viewers
top                       # Basic process monitor
htop                      # Enhanced top (install with: sudo apt install htop)

# Process tree
pstree                    # Visual process hierarchy
ps -ef --forest           # Process tree view

# Find process by port
lsof -i :80               # What's using port 80?
netstat -tulpn | grep :80 # Alternative method
ss -tulpn | grep :80      # Modern method

# Process information
cat /proc/PID/status      # Detailed process info

Process Control

Process Management Commands

# Kill processes
kill PID                  # Graceful termination (SIGTERM)
kill -9 PID               # Force kill (SIGKILL)
killall process-name      # Kill all processes by name
pkill -f "pattern"        # Kill by pattern match

# Process priority
nice -n 10 command        # Start with low priority
renice -n 5 PID           # Change running process priority

# Background and foreground
command &                 # Run command in background
jobs                      # List background jobs
fg %1                     # Bring job 1 to foreground
bg %1                     # Continue job 1 in background

# No hangup - keep process running after logout
nohup long-running-command &
disown                    # Remove from job table

[SEC] Security & Permissions

[SUDO] Privilege Escalation

Understanding sudo

sudo allows permitted users to execute commands as root or another user:

  • Configured in /etc/sudoers
  • Provides audit trail of privileged commands
  • More secure than shared root password

sudo Usage Examples

# Run single command as root
sudo apt update
sudo nano /etc/hosts

# Run command as specific user
sudo -u username command
sudo -u www-data whoami

# Switch to root shell
sudo -i                    # Login shell with root's environment
sudo -s                    # Shell with current environment
sudo su -                  # Switch to root

# Preserve environment variables
sudo -E command           # Keep user environment

# List allowed commands
sudo -l                   # What can current user run?

# Edit sudoers file safely
sudo visudo               # Always use visudo, never direct edit!

sudoers Configuration

Common sudoers Entries

# Sample /etc/sudoers entries:

# Allow user to run any command as root
username ALL=(ALL:ALL) ALL

# Allow user to run specific commands without password
username ALL=(ALL) NOPASSWD: /usr/bin/apt, /bin/systemctl

# Allow group members
%admin ALL=(ALL:ALL) ALL
%sudo ALL=(ALL:ALL) ALL

# Command aliases
Cmnd_Alias NETWORKING = /sbin/route, /sbin/ifconfig
user1 ALL=(ALL) NETWORKING

# Important: Always use visudo to edit!
sudo visudo

[PERM] Advanced Permissions

Advanced Permission Management

# View detailed file permissions
ls -la                    # Long listing with permissions
stat file.txt             # Detailed file information

# Access Control Lists (ACLs)
getfacl file.txt          # View ACLs
setfacl -m u:user:rw file.txt    # Add user ACL
setfacl -m g:group:rx file.txt   # Add group ACL
setfacl -x u:user file.txt       # Remove user ACL

# Default ACLs (inheritance)
setfacl -d -m u:user:rw directory/   # Default ACL for new files

# umask - default file permissions
umask                     # Show current umask
umask 022                 # Set umask (files: 644, dirs: 755)
umask 077                 # Restrictive (files: 600, dirs: 700)

[MISC] Miscellaneous

[ARCH] Archive & Compression

File Archiving Commands

# tar - tape archive
tar -czf archive.tar.gz directory/     # Create compressed tar
tar -xzf archive.tar.gz               # Extract compressed tar
tar -tf archive.tar.gz                # List contents without extracting

# zip/unzip
zip -r archive.zip directory/         # Create zip archive
unzip archive.zip                     # Extract zip
unzip -l archive.zip                  # List zip contents

# gzip/gunzip
gzip file.txt                         # Compress to file.txt.gz
gunzip file.txt.gz                    # Decompress

# 7zip (if installed)
7z a archive.7z directory/            # Create 7z archive
7z x archive.7z                       # Extract 7z

# Common compression options:
# -c: create, -x: extract, -z: gzip, -j: bzip2, -v: verbose, -f: file

Command History Management

# Command history
history                    # Show command history
!55                       # Execute command #55 from history
!!                        # Repeat last command
!nmap                     # Execute last nmap command

# Search history
Ctrl + R                  # Reverse search through history
history | grep "ssh"      # Search for commands containing "ssh"

# History configuration (~/.bashrc)
export HISTSIZE=10000     # Number of commands in memory
export HISTFILESIZE=20000 # Number of commands in history file
export HISTTIMEFORMAT="%d/%m/%y %T "  # Add timestamps
export HISTCONTROL=ignoredups:ignorespace  # Don't save duplicates

# Clear history
history -c                # Clear current session history
history -w                # Write current history to file

[DIR] Directory Navigation

Directory Operations

# Basic navigation
pwd                       # Print working directory
cd /path/to/directory     # Change directory
cd ~                      # Home directory
cd -                      # Previous directory

# Directory stack
pushd /path/to/dir        # Save current dir, change to new
popd                      # Return to saved directory
dirs                      # Show directory stack

# Listing files
ls                        # Basic list
ls -la                    # Long list, all files (including hidden)
ls -lh                    # Human readable sizes
ls -ltr                   # Sort by time (reverse)
ls -d */                  # List only directories

# Create directory structure
mkdir -p project/{src,doc,test}   # Create multiple directories
mkdir -p path/to/nested/directory

Quick Reference Matrix

Linux Command Quick Reference

Task Command Example
Install Package apt install sudo apt install nmap
Update System apt update && apt upgrade sudo apt update && sudo apt upgrade
File Permissions chmod chmod 755 script.sh
File Ownership chown sudo chown user:group file.txt
Add to PATH export PATH= export PATH=$PATH:/new/path
Find Files find find /home -name "*.txt"
Process Info ps aux ps aux \| grep ssh
Kill Process kill kill -9 1234
Network Scan nmap nmap -sV target.com
File Transfer scp scp file.txt user@host:/path/
Archive tar tar -czf backup.tar.gz directory/

OPSEC Considerations

Security Best Practices

File Permissions:

  • Avoid chmod 777 - use more restrictive permissions
  • Set proper ownership for sensitive files
  • Use umask 077 for private directories

System Security:

  • Regular updates: sudo apt update && sudo apt upgrade
  • Use sudo instead of su for accountability
  • Secure SSH configuration (/etc/ssh/sshd_config)
  • Firewall configuration with ufw or iptables

Privacy:

  • Clear command history when needed: history -c && history -w
  • Use encrypted directories for sensitive work
  • Secure file deletion: shred -u file.txt

Tool Installation

Essential Kali Tools

Installing Common Penetration Testing Tools

# Metasploit Framework
sudo apt install metasploit-framework

# Nmap - network scanner
sudo apt install nmap

# Wireshark - packet analyzer
sudo apt install wireshark

# Burp Suite - web proxy
sudo apt install burpsuite

# John the Ripper - password cracker
sudo apt install john

# Hydra - login cracker
sudo apt install hydra

# SQLMap - SQL injection tool
sudo apt install sqlmap

# Gobuster - directory brute forcer
sudo apt install gobuster

# Install all common tools
sudo apt install kali-linux-headless

Custom Tool Installation

Manual Tool Installation

# Clone from GitHub
git clone https://github.com/tool-author/tool-name.git
cd tool-name

# Python tools
pip3 install -r requirements.txt
python3 setup.py install

# Build from source
./configure
make
sudo make install

# Install .deb packages
wget https://example.com/tool.deb
sudo dpkg -i tool.deb
sudo apt --fix-broken install  # Fix dependencies if needed

Troubleshooting Common Issues

Common Problems and Solutions

# "Command not found" error
which command-name          # Check if command exists
echo $PATH                 # Check PATH variable

# Permission denied
ls -la file.txt            # Check permissions
sudo command               # Run as root if appropriate

# Package broken dependencies
sudo apt --fix-broken install
sudo dpkg --configure -a

# Service won't start
sudo systemctl status service-name
journalctl -u service-name

# Disk space issues
df -h                      # Check disk usage
du -sh directory/          # Check directory size

# Network connectivity
ping 8.8.8.8              # Check basic connectivity
ip route show             # Check routing table