# ===============================================# Linux Cheat Sheet# ===============================================# -------------------------------# USER MANAGEMENT# -------------------------------sudo useradd -m username # Add a new user and create a home directorysudo passwd username # Set a password for the usersudo userdel -r username # Delete a user and remove their home directorysudo usermod -l newname oldname # Change a user's login namesudo usermod -d /new/home username # Change a user's home directory# -------------------------------# GROUP MANAGEMENT# -------------------------------sudo groupadd groupname # Create a new groupsudo groupdel groupname # Delete an existing groupsudo usermod -aG groupname username # Add user to supplementary group(s)sudo usermod -g groupname username # Change user's primary groupgroups username # Show groups that a user belongs toid username # Show detailed user and group IDs# -------------------------------# USEFUL FILES# -------------------------------# /etc/passwd -> User account information# /etc/shadow -> Hashed passwords (root-only)# /etc/group -> Group definitions and memberships# -------------------------------# FILE AND DIRECTORY PERMISSIONS# -------------------------------ls -l # List files with permissions, owners, and groups# Permissions breakdown: rwx for user, group, others# Example: -rw-r--r-- means owner can read/write, others read-onlyls -a # List files including hidden files# -------------------------------# MODIFYING PERMISSIONS# -------------------------------chmod u+x file.txt # Add execute permission for the userchmod g+w file.txt # Add write permission for the groupchmod o-r file.txt # Remove read permission for otherschmod a=r file.txt # Set read-only for everyonechmod 755 script.sh # Set rwxr-xr-x (owner full, others read/execute)chmod 644 file.txt # Set rw-r--r-- (owner read/write, others read-only)chmod 700 secret.txt # Set rwx------ (owner only)chmod -R 755 myfolder # Apply permissions recursively to folder and contents# -------------------------------# OWNERSHIP CHANGES# -------------------------------chgrp teachers notes.txt # Change group ownership of a filechgrp -R teachers projects/ # Change group recursivelychown alice notes.txt # Change file ownerchown alice:teachers notes.txt # Change both owner and groupchown -R alice:teachers projects/ # Change owner/group recursively# -------------------------------# DEFAULT PERMISSIONS WITH umask# -------------------------------umask # Show current umask valueumask 0007 # Temporarily change umask (new files 660, dirs 770)# -------------------------------# SPECIAL PERMISSION BITS# -------------------------------# setuid (4xxx) -> Run file with owner’s privileges# setgid (2xxx) -> Run file with group’s privileges# sticky (1xxx) -> Restricts file deletion in shared dirs# Example:# chmod 4755 script.sh -> Set setuid bit on a script# chmod 2755 dir/ -> Set setgid bit on a directory# chmod 1777 /tmp -> Set sticky bit (only owners can delete own files)# ===============================================# Investigating File Contents in Linux# ===============================================# Commands to identify, inspect, and analyze file contents.# ===============================================# -------------------------------# 1. FILE — Identify File Type# -------------------------------file filename # Identify the file type (text, binary, executable, etc.)file /bin/ls # Example: Inspect system executable# -------------------------------# 2. HEAD — View Beginning of a File# -------------------------------head filename # Show first 10 lines of a filehead -n 20 filename # Show first 20 lines# -------------------------------# 3. TAIL — View End of a File# -------------------------------tail filename # Show last 10 lines of a filetail -n 50 filename # Show last 50 linestail -f filename # Follow live updates (e.g., logs in real time)# -------------------------------# 4. OBJDUMP — Inspect Binary Executables# -------------------------------objdump -d filename # Disassemble a binary executableobjdump -x filename # Show all headers and metadataobjdump -d /bin/ls | head -n 10 # Example: Disassemble first 10 lines of /bin/ls# -------------------------------# 5. OD — Dump File in Octal/Hex/Binary# -------------------------------od -c filename # Show file contents as ASCII charactersod -x filename # Show contents in hexadecimalod -b filename # Show contents in octal# Example:# od -c notes.txt # See text + hidden characters# -------------------------------# 6. OTHER USEFUL TOOLS# -------------------------------strings /bin/ls # Extract readable ASCII strings from a binary filexxd filename # Create a hex dump of a filexxd -r filename.hex # Reverse hex dump back into original fileless filename # Scroll through a file interactivelycat filename # Display entire file contents in terminal# ===============================================# Finding Files in Linux# ===============================================# Tools and commands to locate files and directories efficiently.# ===============================================# -------------------------------# 1. FIND — Search for Files and Directories# -------------------------------find directory -name targetfile -print # Search for a file by name in a given directory treefind /home -name "*.txt" -print 2>/dev/null # Find all .txt files under /home, hide permission errors# Useful find options:find . -type f # Find only regular filesfind . -type d # Find only directoriesfind . -perm o=r # Find files readable by othersfind . -size +10M # Find files larger than 10 MBfind . -iname "*.jpg" # Case-insensitive search for .jpg files# Execute a command for each match:find . -name "*.txt" -exec wc -l '{}' ';' # Count lines in every .txt file found# -------------------------------# 2. WHICH — Locate Executable Files# -------------------------------which ls # Show path to the binary for a command (e.g., /bin/ls)type ls # Show if a command is built-in, alias, or binarycommand -v ls # POSIX-compliant way to find command location# -------------------------------# 3. LOCATE — Fast Filename Search Using Index# -------------------------------locate ".txt" # Find all files with ".txt" in their pathsudo updatedb # Manually update the locate database index# Notes:# - locate is very fast but may show outdated results.# - Cannot search by size, type, or permissions like find can.# -------------------------------# 4. OTHER USEFUL TOOLS# -------------------------------whereis ls # Show binary, source, and man page locations for a commandfd pattern # Modern, faster replacement for find (if installed)grep -rl pattern directory/ # Find files containing specific text recursively# ===============================================# UNIX File Compression & Backup Guide# ===============================================# Tools for archiving, compressing, and backing up files in UNIX/Linux.# Includes tar, cpio, compress, gzip, and modern alternatives.# ===============================================# -------------------------------# 1. TAR — Tape Archiver# -------------------------------tar -cvf backup.tar /home/user/documents # Create an archive file (no compression)tar -czvf backup.tar.gz /home/user/documents # Create and compress archive with gziptar -cjvf backup.tar.bz2 /home/user/documents # Create and compress archive with bzip2tar -cJvf backup.tar.xz /home/user/documents # Create and compress archive with xztar -tvf backup.tar # List contents of an archivetar -xvf backup.tar # Extract archive contentstar -xvf backup.tar -C /tmp/restore # Extract archive into a specific directorytar --exclude="*.tmp" -czvf backup.tar.gz dir/ # Exclude files matching pattern from archive# Common tar options:# -c : Create archive# -x : Extract archive# -t : List contents# -v : Verbose (show files as processed)# -f : Specify archive filename# -z : Use gzip compression# -j : Use bzip2 compression# -J : Use xz compression# --exclude=PATTERN : Skip files matching pattern# -------------------------------# 2. CPIO — Copy In/Out Archiver# -------------------------------find . -depth -print | cpio -ov -Htar > backup.tar # Create a tar-format archive using cpiocpio -tv < backup.tar # List contents of a cpio archivecpio -idv < backup.tar # Extract files from a cpio archivecpio -iduv < backup.tar # Extract and overwrite existing files# Common cpio options:# -o : Create archive (copy-out mode)# -i : Extract archive (copy-in mode)# -t : List contents# -v : Verbose output# -d : Create directories as needed# -u : Overwrite existing files# -H : Set archive format (tar, crc, odc, etc.)# -------------------------------# 3. COMPRESS & GZIP — File Compression Tools# -------------------------------compress file.txt # Compress file to file.txt.Zcompress -d file.txt.Z # Decompress .Z filegzip file.txt # Compress file to file.txt.gzgzip -d file.txt.gz # Decompress .gz filezcat file.txt.gz # View compressed file contents without decompressing# -------------------------------# 4. MODERN ALTERNATIVES & IMPROVEMENTS# -------------------------------tar -cjvf backup.tar.bz2 dir/ # Use bzip2 for better compression than gziptar -cJvf backup.tar.xz dir/ # Use xz for maximum compressionzip -r backup.zip dir/ # Create a cross-platform .zip archiversync -avz /source user@host:/backup # Perform incremental backups over network# ------------------------------# DHCP# ------------------------------# ------------------------------# SERVER: Identify network interfaces# ------------------------------echo "Listing all network interfaces..."ip link showip addr show# ------------------------------# SERVER: Assign static IP to Host-only adapter (ens4 example)# Adjust 'ens4' to your actual interface name# ------------------------------echo "Configuring static IP for ens4..."sudo tee /etc/netplan/99-static-dhcp-server.yaml > /dev/null <<EOFnetwork: version: 2 ethernets: ens4: dhcp4: no addresses: [192.168.100.1/24] nameservers: addresses: [1.1.1.1, 8.8.8.8]EOFsudo netplan generatesudo netplan applyip addr show dev ens4# ------------------------------# SERVER: Create lease database & set permissions# ------------------------------echo "Creating DHCP lease file and setting permissions..."sudo mkdir -p /var/lib/dhcpsudo touch /var/lib/dhcp/dhcpd.leasessudo chown root:dhcpd /var/lib/dhcp /var/lib/dhcp/dhcpd.leasessudo chmod 0644 /var/lib/dhcp/dhcpd.leases# ------------------------------# SERVER: Configure DHCP server# ------------------------------echo "Configuring /etc/dhcp/dhcpd.conf..."sudo tee /etc/dhcp/dhcpd.conf > /dev/null <<EOFauthoritative;ddns-update-style none;default-lease-time 600;max-lease-time 7200;option domain-name "lab.local";option domain-name-servers 1.1.1.1, 8.8.8.8;subnet 192.168.100.0 netmask 255.255.255.0 { range 192.168.100.100 192.168.100.200; option routers 192.168.100.1; option broadcast-address 192.168.100.255;}EOF# ------------------------------# SERVER: Specify listening interface# Replace 'ens4' with your interface# ------------------------------echo "Setting DHCP server interface..."sudo sed -i 's/^INTERFACESv4=.*/INTERFACESv4="ens4"/' /etc/default/isc-dhcp-serversudo sed -i 's/^INTERFACESv6=.*/INTERFACESv6=""/' /etc/default/isc-dhcp-server# ------------------------------# SERVER: Start and enable DHCP service# ------------------------------echo "Starting and enabling DHCP server..."sudo systemctl daemon-reloadsudo systemctl enable --now isc-dhcp-serversudo systemctl status isc-dhcp-server --no-pager# Watch DHCP logs in real time (press Ctrl+C to exit)...sudo journalctl -u isc-dhcp-server -f# ------------------------------# CLIENT: Install DHCP client and request lease# ------------------------------# Installing DHCP client (if missing)...sudo apt install isc-dhcp-client -y# Requesting DHCP lease on interface ens4...sudo dhclient -v ens4# ------------------------------# CLIENT/SERVER: Capture DORA exchange# ------------------------------#To capture DHCP packets, run the following command:sudo tcpdump -n -i ens4 udp and \(port 67 or port 68\) -vv# ------------------------------# CLIENT: Verify IP assignment# ------------------------------#Check assigned IP and routing:ip addr show dev ens4ip route showping -c3 1.1.1.1ping -c3 google.com# ------------------------------# SERVER: View lease file# ------------------------------#Check DHCP leases on server:sudo cat /var/lib/dhcp/dhcpd.leases# ------------------------------# DNS# ------------------------------# ------------------------------# 1) Update & install BIND9# ------------------------------#Updating packages and installing BIND9...sudo apt updatesudo apt install -y bind9 bind9-utils# Start & enable BIND9 servicesudo systemctl start bind9sudo systemctl enable bind9sudo systemctl status bind9 --no-pager# ------------------------------# 2) Configure Forward Zone# ------------------------------FORWARD_ZONE="mynetwork.local"FORWARD_DB="/etc/bind/db.${FORWARD_ZONE}"# Add zone to named.conf.local if not already presentgrep -q "${FORWARD_ZONE}" /etc/bind/named.conf.local || sudo tee -a /etc/bind/named.conf.local > /dev/null <<EOFzone "${FORWARD_ZONE}" { type master; file "${FORWARD_DB}";};EOF# Copy template to create zone filesudo cp /etc/bind/db.local ${FORWARD_DB}# Replace zone file with example contentsudo tee ${FORWARD_DB} > /dev/null <<EOF\$TTL 604800@ IN SOA ns1.${FORWARD_ZONE}. admin.${FORWARD_ZONE}. ( 2 ; Serial 604800 ; Refresh 86400 ; Retry 2419200 ; Expire 604800 ) ; Negative Cache TTL; Name server@ IN NS ns1.${FORWARD_ZONE}.; A recordsns1 IN A 192.168.56.10www IN A 192.168.56.20www2 IN A 192.168.56.21; MX records@ IN MX 10 mail.${FORWARD_ZONE}.@ IN MX 20 mail2.${FORWARD_ZONE}.mail IN A 192.168.56.30mail2 IN A 192.168.56.31EOF# ------------------------------# 3) Configure Reverse Zone# ------------------------------REVERSE_ZONE="56.168.192.in-addr.arpa"REVERSE_DB="/etc/bind/db.192.168.56"grep -q "${REVERSE_ZONE}" /etc/bind/named.conf.local || sudo tee -a /etc/bind/named.conf.local > /dev/null <<EOFzone "${REVERSE_ZONE}" { type master; file "${REVERSE_DB}";};EOFsudo cp /etc/bind/db.127 ${REVERSE_DB}sudo tee ${REVERSE_DB} > /dev/null <<EOF\$TTL 604800@ IN SOA ns1.${FORWARD_ZONE}. admin.${FORWARD_ZONE}. ( 2 ; Serial 604800 ; Refresh 86400 ; Retry 2419200 ; Expire 604800 ) ; Negative Cache TTL; Name server@ IN NS ns1.${FORWARD_ZONE}.; PTR records10 IN PTR ns1.${FORWARD_ZONE}.20 IN PTR www.${FORWARD_ZONE}.21 IN PTR www2.${FORWARD_ZONE}.30 IN PTR mail.${FORWARD_ZONE}.EOF# ------------------------------# 4) Check configuration# ------------------------------sudo named-checkconfsudo named-checkzone ${FORWARD_ZONE} ${FORWARD_DB}sudo named-checkzone ${REVERSE_ZONE} ${REVERSE_DB}# Restart BIND9sudo systemctl restart bind9# ------------------------------# 5) Optional: Configure DDNS (Dynamic DNS)# ------------------------------echo "Setting up optional DDNS integration..."# Generate TSIG key for DHCP <-> DNS# NOTE: Replace "XXXXXXXXXXXXXXXXXXXX==" with your actual secretKEY_NAME="dhcpupdate"SECRET="XXXXXXXXXXXXXXXXXXXX=="sudo tee /etc/bind/keys.conf > /dev/null <<EOFkey "${KEY_NAME}" { algorithm hmac-sha256; secret "${SECRET}";};EOF# Include DDNS key in forward/reverse zonessudo sed -i "/zone \"${FORWARD_ZONE}\" {/a \ allow-update { key ${KEY_NAME}; };" /etc/bind/named.conf.localsudo sed -i "/zone \"${REVERSE_ZONE}\" {/a \ allow-update { key ${KEY_NAME}; };" /etc/bind/named.conf.local# Restart BIND to apply DDNSsudo systemctl restart bind9# ------------------------------# 6) Testing DNS from server# ------------------------------# Testing forward lookups...dig @127.0.0.1 www.${FORWARD_ZONE}dig @127.0.0.1 www2.${FORWARD_ZONE}dig @127.0.0.1 mail.${FORWARD_ZONE}# Testing reverse lookup...dig -x 192.168.56.20