0% found this document useful (0 votes)
4 views133 pages

Complete Linux System Administration Command Reference3

This document serves as a comprehensive reference guide for Linux system administration commands, organized into various sections covering file operations, permissions, user management, and more. Each command is accompanied by examples demonstrating its usage and options. The guide is structured to facilitate quick access to essential commands for system administrators.

Uploaded by

ogachisam220
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views133 pages

Complete Linux System Administration Command Reference3

This document serves as a comprehensive reference guide for Linux system administration commands, organized into various sections covering file operations, permissions, user management, and more. Each command is accompanied by examples demonstrating its usage and options. The guide is structured to facilitate quick access to essential commands for system administrators.

Uploaded by

ogachisam220
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Complete Linux System Administration Command

Reference
Table of Contents
1. File and Directory Operations

2. File Permissions and Ownership

3. User and Group Management

4. System Information

5. Process Management

6. Networking Commands

7. SSH and Remote Access

8. Service Management

9. Package Management

10. Text Processing

11. Disk and File System Management

12. System Monitoring

13. Security and Firewall

14. Archive and Compression

15. System Boot and Init

16. Kernel and Module Management

17. Logging and Auditing

18. Advanced Networking

File and Directory Operations


ls - List Directory Contents

bash
# Basic listing
ls

# Long format with details


ls -l

# Show hidden files


ls -a

# Long format with hidden files


ls -la

# Human-readable file sizes


ls -lh

# Sort by modification time (newest first)


ls -lt

# Reverse sort order


ls -lr

# Recursive listing
ls -R

# List directories only


ls -d */

# List with inode numbers


ls -i

# Sort by size
ls -lS

# Show file type indicators


ls -F

# Color output
ls --color=auto

# One file per line


ls -1

cd - Change Directory

bash
# Change to home directory
cd
cd ~

# Change to specific directory


cd /var/log

# Go up one directory
cd ..

# Go up two directories
cd ../..

# Return to previous directory


cd -

# Change to root directory


cd /

pwd - Print Working Directory

bash

# Show current directory


pwd

# Show physical path (resolve symlinks)


pwd -P

# Show logical path (with symlinks)


pwd -L

mkdir - Make Directories

bash
# Create single directory
mkdir mydir

# Create multiple directories


mkdir dir1 dir2 dir3

# Create parent directories as needed


mkdir -p /path/to/nested/directory

# Set permissions while creating


mkdir -m 755 mydir

# Verbose output
mkdir -v mydir

rmdir - Remove Empty Directories

bash

# Remove empty directory


rmdir mydir

# Remove nested empty directories


rmdir -p parent/child/grandchild

# Verbose output
rmdir -v mydir

rm - Remove Files and Directories

bash
# Remove file
rm [Link]

# Remove multiple files


rm [Link] [Link] [Link]

# Remove directory and contents recursively


rm -r directory/

# Force removal without prompting


rm -f [Link]

# Force recursive removal


rm -rf directory/

# Interactive removal (prompt for each)


rm -i [Link]

# Verbose output
rm -v [Link]

# Remove files matching pattern


rm *.log

# Remove empty directories only


rm -d emptydir/

cp - Copy Files and Directories

bash
# Copy file
cp [Link] [Link]

# Copy to directory
cp [Link] /path/to/directory/

# Copy multiple files to directory


cp [Link] [Link] /destination/

# Copy directory recursively


cp -r sourcedir/ destdir/

# Preserve file attributes


cp -p [Link] [Link]

# Archive mode (preserve everything)


cp -a sourcedir/ destdir/

# Interactive (prompt before overwrite)


cp -i [Link] [Link]

# Update (copy only if newer)


cp -u [Link] [Link]

# Verbose output
cp -v [Link] [Link]

# Create hard link instead of copying


cp -l [Link] [Link]

# Create symbolic link


cp -s [Link] [Link]

mv - Move/Rename Files

bash
# Rename file
mv [Link] [Link]

# Move file to directory


mv [Link] /path/to/directory/

# Move multiple files


mv [Link] [Link] /destination/

# Move directory
mv olddir/ newdir/

# Interactive mode
mv -i [Link] [Link]

# No overwrite
mv -n [Link] [Link]

# Force overwrite
mv -f [Link] [Link]

# Update only if newer


mv -u [Link] [Link]

# Verbose output
mv -v [Link] [Link]

# Backup before overwrite


mv -b [Link] [Link]

touch - Create or Update File Timestamps

bash
# Create empty file
touch [Link]

# Create multiple files


touch [Link] [Link] [Link]

# Update access and modification time to current


touch [Link]

# Set specific time


touch -t 202301011200 [Link]

# Use reference file's time


touch -r [Link] [Link]

# Change only access time


touch -a [Link]

# Change only modification time


touch -m [Link]

# Don't create file if it doesn't exist


touch -c [Link]

find - Search for Files

bash
# Find by name
find /path -name "[Link]"

# Case-insensitive name search


find /path -iname "[Link]"

# Find directories only


find /path -type d

# Find files only


find /path -type f

# Find by extension
find /path -name "*.log"

# Find and delete


find /path -name "*.tmp" -delete

# Find by size (larger than 100MB)


find /path -size +100M

# Find by size (smaller than 1MB)


find /path -size -1M

# Find modified in last 7 days


find /path -mtime -7

# Find modified more than 30 days ago


find /path -mtime +30

# Find by permissions
find /path -perm 644

# Find and execute command


find /path -name "*.txt" -exec cat {} \;

# Find with multiple conditions (AND)


find /path -name "*.log" -size +10M

# Find with OR condition


find /path \( -name "*.log" -o -name "*.txt" \)

# Find by user
find /path -user username

# Find by group
find /path -group groupname

# Find empty files


find /path -empty

# Find and print with details


find /path -name "*.conf" -ls

locate - Find Files by Name (Uses Database)

bash

# Find file by name


locate filename

# Case-insensitive search
locate -i filename

# Limit results
locate -n 10 filename

# Update locate database


sudo updatedb

# Show statistics
locate -S

which - Show Full Path of Commands

bash

# Find command location


which ls

# Find multiple commands


which python python3

# Show all matches


which -a python

whereis - Locate Binary, Source, and Manual

bash
# Find all locations
whereis ls

# Binary only
whereis -b ls

# Manual only
whereis -m ls

# Source only
whereis -s ls

file - Determine File Type

bash

# Check file type


file [Link]

# Check multiple files


file *

# Show MIME type


file -i [Link]

# Brief mode
file -b [Link]

stat - Display File Status

bash

# Show file statistics


stat [Link]

# Show file system status


stat -f /

# Custom format
stat -c "%n %s bytes" [Link]

# Show access time


stat -c "%x" [Link]
File Permissions and Ownership
chmod - Change File Permissions

bash
# Numeric mode (rwxrwxrwx = 777)
chmod 755 [Link] # rwxr-xr-x
chmod 644 [Link] # rw-r--r--
chmod 600 [Link] # rw-------
chmod 777 [Link] # rwxrwxrwx
chmod 700 directory/ # rwx------

# Symbolic mode - add permissions


chmod u+x [Link] # Add execute for user
chmod g+w [Link] # Add write for group
chmod o+r [Link] # Add read for others
chmod a+x [Link] # Add execute for all

# Symbolic mode - remove permissions


chmod u-x [Link] # Remove execute from user
chmod g-w [Link] # Remove write from group
chmod o-r [Link] # Remove read from others
chmod a-x [Link] # Remove execute from all

# Symbolic mode - set exact permissions


chmod u=rwx [Link] # User: rwx
chmod g=rx [Link] # Group: r-x
chmod o= [Link] # Others: none

# Recursive
chmod -R 755 directory/

# Verbose
chmod -v 644 [Link]

# Change based on reference file


chmod --reference=[Link] [Link]

# Set setuid bit


chmod u+s program

# Set setgid bit


chmod g+s directory/

# Set sticky bit


chmod +t directory/

# Numeric with special bits


chmod 4755 program # setuid + 755
chmod 2755 directory # setgid + 755
chmod 1755 directory # sticky + 755

chown - Change File Owner and Group

bash

# Change owner
chown username [Link]

# Change owner and group


chown username:groupname [Link]

# Change group only


chown :groupname [Link]

# Recursive
chown -R username:groupname directory/

# Verbose
chown -v username [Link]

# Use reference file


chown --reference=[Link] [Link]

# Don't dereference symbolic links


chown -h username symlink

# Change from specific owner


chown --from=olduser:oldgroup newuser:newgroup [Link]

chgrp - Change Group Ownership

bash
# Change group
chgrp groupname [Link]

# Recursive
chgrp -R groupname directory/

# Verbose
chgrp -v groupname [Link]

# Use reference file


chgrp --reference=[Link] [Link]

# Don't dereference symlinks


chgrp -h groupname symlink

umask - Set Default Permissions

bash

# Show current umask


umask

# Set umask (files: 666-022=644, dirs: 777-022=755)


umask 022

# Set umask (more restrictive)


umask 027

# Show in symbolic form


umask -S

# Set in symbolic form


umask u=rwx,g=rx,o=

getfacl - Get File Access Control Lists

bash
# Display ACL
getfacl [Link]

# Display for directory


getfacl directory/

# Omit comment lines


getfacl -c [Link]

# Display recursively
getfacl -R directory/

setfacl - Set File Access Control Lists

bash

# Grant user permission


setfacl -m u:username:rwx [Link]

# Grant group permission


setfacl -m g:groupname:rx [Link]

# Remove ACL entry


setfacl -x u:username [Link]

# Remove all ACLs


setfacl -b [Link]

# Set default ACL for directory


setfacl -d -m u:username:rwx directory/

# Recursive
setfacl -R -m u:username:rx directory/

# Copy ACL from one file to another


getfacl [Link] | setfacl --set-file=- [Link]

lsattr - List File Attributes

bash
# List attributes
lsattr [Link]

# List directory attributes


lsattr -d directory/

# Recursive listing
lsattr -R directory/

# List all files including hidden


lsattr -a

chattr - Change File Attributes

bash

# Make file immutable (can't delete/modify)


chattr +i [Link]

# Remove immutable
chattr -i [Link]

# Append only
chattr +a [Link]

# Remove append only


chattr -a [Link]

# No dump
chattr +d [Link]

# Synchronous updates
chattr +S [Link]

# Recursive
chattr -R +i directory/

User and Group Management


useradd - Create User Account

bash
# Create basic user
useradd username

# Create with home directory


useradd -m username

# Specify home directory


useradd -d /custom/home username

# Specify shell
useradd -s /bin/bash username

# Specify UID
useradd -u 1500 username

# Add to groups
useradd -G group1,group2 username

# Set primary group


useradd -g groupname username

# Create system user


useradd -r username

# Set expiry date


useradd -e 2024-12-31 username

# Complete example
useradd -m -d /home/john -s /bin/bash -G sudo,developers -c "John Doe" john

usermod - Modify User Account

bash
# Change username
usermod -l newname oldname

# Change home directory


usermod -d /new/home -m username

# Change shell
usermod -s /bin/zsh username

# Add to supplementary groups


usermod -aG group1,group2 username

# Change primary group


usermod -g newgroup username

# Lock account
usermod -L username

# Unlock account
usermod -U username

# Set expiry date


usermod -e 2024-12-31 username

# Change UID
usermod -u 1500 username

# Change comment
usermod -c "New Comment" username

userdel - Delete User Account

bash

# Delete user (keep home directory)


userdel username

# Delete user and home directory


userdel -r username

# Force delete even if logged in


userdel -f username

passwd - Change User Password

bash
# Change your own password
passwd

# Change another user's password (root)


passwd username

# Force password change on next login


passwd -e username

# Lock account
passwd -l username

# Unlock account
passwd -u username

# Delete password (passwordless login)


passwd -d username

# Set password expiry


passwd -x 90 username

# Show password status


passwd -S username

# Set minimum password age


passwd -n 7 username

# Set warning period


passwd -w 14 username

# Set inactivity period


passwd -i 30 username

groupadd - Create Group

bash
# Create group
groupadd groupname

# Create with specific GID


groupadd -g 1500 groupname

# Create system group


groupadd -r groupname

# Force create even if group exists


groupadd -f groupname

groupmod - Modify Group

bash

# Rename group
groupmod -n newname oldname

# Change GID
groupmod -g 1500 groupname

groupdel - Delete Group

bash

# Delete group
groupdel groupname

id - Display User and Group IDs

bash
# Show current user info
id

# Show specific user info


id username

# Show only UID


id -u

# Show only GID


id -g

# Show all groups


id -G

# Show group names


id -Gn

# Show user name


id -un

who - Show Logged In Users

bash

# Show logged in users


who

# Show with more details


who -a

# Show boot time


who -b

# Show current runlevel


who -r

# Show login time


who -u

# Count users
who -q

w - Show Who Is Logged In and What They're Doing

bash
# Show logged in users with activity
w

# Show without header


w -h

# Show specific user


w username

# Short format
w -s

last - Show Login History

bash

# Show recent logins


last

# Show specific user


last username

# Show last 10 entries


last -n 10

# Show since specific date


last -s 2024-01-01

# Show until specific date


last -t 2024-12-31

# Show system reboots


last reboot

# Show failed login attempts


lastb

su - Switch User

bash
# Switch to root
su

# Switch to specific user


su username

# Switch with environment


su - username

# Execute command as another user


su -c "command" username

# Switch to root and run command


su -c "apt update"

sudo - Execute Command as Superuser

bash
# Run command as root
sudo command

# Run command as specific user


sudo -u username command

# Switch to root shell


sudo -i

# Switch to root shell keeping environment


sudo -s

# Edit file with default editor


sudo -e /etc/hosts

# List sudo privileges


sudo -l

# Validate sudo credentials


sudo -v

# Remove sudo credentials


sudo -k

# Run with specific group


sudo -g groupname command

# Set environment variable


sudo VAR=value command

visudo - Edit Sudoers File Safely

bash

# Edit sudoers file


visudo

# Check sudoers syntax


visudo -c

# Edit specific file


visudo -f /etc/sudoers.d/custom

chage - Change Password Expiry Information

bash
# Show password expiry info
chage -l username

# Set password expiry date


chage -E 2024-12-31 username

# Set minimum password age


chage -m 7 username

# Set maximum password age


chage -M 90 username

# Set warning period


chage -W 14 username

# Set inactivity period


chage -I 30 username

# Force password change on next login


chage -d 0 username

# Interactive mode
chage username

System Information
uname - Print System Information

bash
# Show kernel name
uname

# Show all information


uname -a

# Show kernel release


uname -r

# Show kernel version


uname -v

# Show machine hardware name


uname -m

# Show processor type


uname -p

# Show hardware platform


uname -i

# Show operating system


uname -o

# Show nodename
uname -n

hostname - Show or Set System Hostname

bash
# Show hostname
hostname

# Show FQDN
hostname -f

# Show IP address
hostname -I

# Show all addresses


hostname -A

# Set hostname (temporary)


hostname newhostname

# Show domain name


hostname -d

hostnamectl - Control System Hostname (systemd)

bash

# Show hostname info


hostnamectl

# Set hostname
hostnamectl set-hostname newhostname

# Set pretty hostname


hostnamectl set-hostname "My Server" --pretty

# Set static hostname


hostnamectl set-hostname server01 --static

# Set transient hostname


hostnamectl set-hostname temp-name --transient

uptime - Show System Uptime

bash
# Show uptime and load average
uptime

# Show in pretty format


uptime -p

# Show since when system is up


uptime -s

date - Display or Set System Date/Time

bash

# Show current date and time


date

# Show in specific format


date "+%Y-%m-%d"
date "+%Y-%m-%d %H:%M:%S"

# Show in UTC
date -u

# Show date for specific time


date -d "2 days ago"
date -d "next monday"
date -d "tomorrow"

# Set system date (requires root)


date -s "2024-01-01 12:00:00"

# Show date in different timezone


TZ="America/New_York" date

# Show timestamp
date +%s

# Convert timestamp to date


date -d @1234567890

timedatectl - Control System Time and Date (systemd)

bash
# Show time settings
timedatectl

# Set time zone


timedatectl set-timezone America/New_York

# List available timezones


timedatectl list-timezones

# Set system time


timedatectl set-time "2024-01-01 12:00:00"

# Enable NTP synchronization


timedatectl set-ntp true

# Disable NTP synchronization


timedatectl set-ntp false

# Set RTC to UTC


timedatectl set-local-rtc 0

# Set RTC to local time


timedatectl set-local-rtc 1

cal - Display Calendar

bash

# Show current month


cal

# Show specific year


cal 2024

# Show specific month and year


cal 12 2024

# Show three months


cal -3

# Show year calendar


cal -y

# Show monday as first day


cal -m
df - Report File System Disk Space Usage

bash

# Show disk usage


df

# Human-readable format
df -h

# Show inode usage


df -i

# Show file system type


df -T

# Show all file systems


df -a

# Exclude specific type


df -x tmpfs

# Show specific filesystem


df /dev/sda1

# Show total
df -h --total

du - Estimate File Space Usage

bash
# Show directory size
du

# Human-readable
du -h

# Summary only
du -s

# Summary with human-readable


du -sh

# Show all files and directories


du -a

# Max depth
du -h --max-depth=1

# Sort by size
du -h | sort -h

# Show total
du -ch

# Exclude pattern
du -h --exclude="*.log"

# Show apparent size


du -h --apparent-size

free - Display Memory Usage

bash
# Show memory usage
free

# Human-readable
free -h

# Show in MB
free -m

# Show in GB
free -g

# Continuous update every 2 seconds


free -s 2

# Show wide format


free -w

# Show total line


free -t

lscpu - Display CPU Information

bash

# Show CPU information


lscpu

# Show online CPUs


lscpu -p

# Extended information
lscpu -e

lsblk - List Block Devices

bash
# List all block devices
lsblk

# Show filesystem info


lsblk -f

# Show all information


lsblk -a

# Show size in bytes


lsblk -b

# Tree format
lsblk -t

# Include empty devices


lsblk -a

# Show specific device


lsblk /dev/sda

lspci - List PCI Devices

bash

# List all PCI devices


lspci

# Verbose output
lspci -v

# Very verbose
lspci -vv

# Show numeric IDs


lspci -nn

# Show kernel drivers


lspci -k

# Tree format
lspci -t

# Show specific device


lspci -s 00:1f.2
lsusb - List USB Devices

bash

# List USB devices


lsusb

# Verbose output
lsusb -v

# Tree format
lsusb -t

# Show specific device


lsusb -d 046d:

dmidecode - DMI/SMBIOS Information

bash

# Show all DMI information


sudo dmidecode

# Show BIOS info


sudo dmidecode -t bios

# Show system info


sudo dmidecode -t system

# Show memory info


sudo dmidecode -t memory

# Show processor info


sudo dmidecode -t processor

# Show chassis info


sudo dmidecode -t chassis

Process Management
ps - Report Process Status

bash
# Show your processes
ps

# Show all processes


ps -e
ps aux

# Show process tree


ps -ef
ps auxf

# Show threads
ps -eLf

# Show specific user processes


ps -u username

# Show by command name


ps -C nginx

# Custom format
ps -eo pid,ppid,cmd,%mem,%cpu

# Sort by memory
ps aux --sort=-%mem

# Sort by CPU
ps aux --sort=-%cpu

# Show process hierarchy


ps -ejH

# Long format
ps -l

# Wide output
ps -w

top - Display Running Processes

bash
# Start top
top

# Inside top:
# Press 'h' for help
# Press 'k' to kill process
# Press 'r' to renice process
# Press 'M' to sort by memory
# Press 'P' to sort by CPU
# Press 'q' to quit
# Press '1' to show individual CPUs
# Press 'c' to show full command

# Run with specific options


top -u username # Show specific user
top -p PID # Show specific process
top -b -n 1 # Batch mode (one iteration)
top -d 5 # Update every 5 seconds

htop - Interactive Process Viewer

bash

# Start htop
htop

# Inside htop:
# F1 - Help
# F2 - Setup
# F3 - Search
# F4 - Filter
# F5 - Tree view
# F6 - Sort by
# F9 - Kill process
# F10 - Quit

# Filter by user
htop -u username

# Filter by command
htop -p PID1,PID2

pgrep - Find Process by Name

bash
# Find process by name
pgrep process_name

# Show full command


pgrep -a process_name

# Show count
pgrep -c process_name

# List by user
pgrep -u username

# Show newest process


pgrep -n process_name

# Show oldest process


pgrep -o process_name

# List PIDs separated by delimiter


pgrep -d, process_name

pkill - Kill Process by Name

bash

# Kill process by name


pkill process_name

# Send specific signal


pkill -9 process_name
pkill -SIGKILL process_name

# Kill by user
pkill -u username

# Kill by terminal
pkill -t pts/0

# Kill by full command


pkill -f "full command string"

# Kill newest process


pkill -n process_name

# Kill oldest process


pkill -o process_name
kill - Send Signal to Process

bash

# Kill process by PID


kill PID

# Force kill
kill -9 PID
kill -SIGKILL PID

# Graceful termination
kill -15 PID
kill -SIGTERM PID

# Hangup signal
kill -1 PID
kill -SIGHUP PID

# List available signals


kill -l

# Send signal to process group


kill -TERM -PID

# Check if process exists


kill -0 PID

killall - Kill Processes by Name

bash
# Kill all processes with name
killall process_name

# Force kill
killall -9 process_name

# Interactive mode
killall -i process_name

# Kill by user
killall -u username

# Verbose output
killall -v process_name

# Wait for processes to die


killall -w process_name

# Case insensitive
killall -I process_name

nice - Run with Modified Priority

bash

# Run with default priority (10)


nice command

# Run with specific priority (-20 to 19, lower = higher priority)


nice -n 10 command

# Run with lowest priority


nice -n 19 command

# Run with highest priority (requires root)


nice -n -20 command

renice - Change Priority of Running Process

bash
# Change priority by PID
renice -n 5 -p PID

# Change priority for all processes of user


renice -n 10 -u username

# Change priority for process group


renice -n 0 -g groupid

# Set to specific value


renice 15 PID

jobs - List Background Jobs

bash

# List jobs
jobs

# List with PIDs


jobs -l

# List only running jobs


jobs -r

# List only stopped jobs


jobs -s

# List specific job


jobs %1

bg - Resume Suspended Job in Background

bash

# Resume last suspended job


bg

# Resume specific job


bg %1

# Resume multiple jobs


bg %1 %2 %3
fg - Bring Job to Foreground

bash

# Bring last job to foreground


fg

# Bring specific job


fg %1

# Bring by command name


fg %command_name

nohup - Run Command Immune to Hangups

bash

# Run command in background


nohup command &

# Redirect output
nohup command > [Link] 2>&1 &

# Multiple commands
nohup sh -c 'command1 && command2' &

screen - Terminal Multiplexer

bash
# Start new screen session
screen

# Start with name


screen -S session_name

# List sessions
screen -ls

# Attach to session
screen -r
screen -r session_name

# Detach from session: Ctrl+A, D

# Create new window: Ctrl+A, C


# Next window: Ctrl+A, N
# Previous window: Ctrl+A, P
# List windows: Ctrl+A, "

# Kill session
screen -X -S session_name quit

# Share session
screen -x session_name

tmux - Terminal Multiplexer

bash
# Start new session
tmux

# Start with name


tmux new -s session_name

# List sessions
tmux ls

# Attach to session
tmux attach
tmux attach -t session_name

# Detach: Ctrl+B, D

# New window: Ctrl+B, C


# Next window: Ctrl+B, N
# Previous window: Ctrl+B, P
# List windows: Ctrl+B, W

# Split vertical: Ctrl+B, %


# Split horizontal: Ctrl+B, "
# Switch pane: Ctrl+B, Arrow

# Kill session
tmux kill-session -t session_name

# Rename session: Ctrl+B, $

systemctl - Control Systemd Services

bash
# Start service
systemctl start service_name

# Stop service
systemctl stop service_name

# Restart service
systemctl restart service_name

# Reload configuration
systemctl reload service_name

# Enable service (start at boot)


systemctl enable service_name

# Disable service
systemctl disable service_name

# Check service status


systemctl status service_name

# Check if service is active


systemctl is-active service_name

# Check if service is enabled


systemctl is-enabled service_name

# List all services


systemctl list-units --type=service

# List failed services


systemctl --failed

# Show service dependencies


systemctl list-dependencies service_name

# Mask service (prevent starting)


systemctl mask service_name

# Unmask service
systemctl unmask service_name

# Reload systemd manager configuration


systemctl daemon-reload
Networking Commands
ip - Show/Manipulate Network Configuration

bash
# Show all interfaces
ip addr
ip a

# Show specific interface


ip addr show eth0

# Add IP address
ip addr add [Link]/24 dev eth0

# Delete IP address
ip addr del [Link]/24 dev eth0

# Show routing table


ip route
ip r

# Add route
ip route add [Link]/24 via [Link]

# Delete route
ip route del [Link]/24

# Add default gateway


ip route add default via [Link]

# Show link status


ip link show

# Bring interface up
ip link set eth0 up

# Bring interface down


ip link set eth0 down

# Change MAC address


ip link set eth0 address 00:11:22:33:44:55

# Show neighbor table (ARP)


ip neigh
ip neighbor show

# Add static ARP entry


ip neigh add [Link] lladdr 00:11:22:33:44:55 dev eth0

# Delete ARP entry


ip neigh del [Link] dev eth0

# Show network statistics


ip -s link

# Show IPv6 addresses


ip -6 addr

# Show IPv6 routes


ip -6 route

# Monitor network changes


ip monitor

ifconfig - Configure Network Interface (Legacy)

bash
# Show all interfaces
ifconfig

# Show specific interface


ifconfig eth0

# Assign IP address
ifconfig eth0 [Link] netmask [Link]

# Bring interface up
ifconfig eth0 up

# Bring interface down


ifconfig eth0 down

# Set MAC address


ifconfig eth0 hw ether 00:11:22:33:44:55

# Set MTU
ifconfig eth0 mtu 1500

# Add alias IP
ifconfig eth0:0 [Link]

# Enable promiscuous mode


ifconfig eth0 promisc

# Disable promiscuous mode


ifconfig eth0 -promisc

ping - Test Network Connectivity

bash
# Ping host
ping hostname
ping [Link]

# Ping specific count


ping -c 4 hostname

# Ping with interval


ping -i 2 hostname

# Ping with packet size


ping -s 1000 hostname

# Ping with timeout


ping -w 10 hostname

# Flood ping (requires root)


ping -f hostname

# IPv6 ping
ping6 hostname

# Set TTL
ping -t 64 hostname

# Record route
ping -R hostname

# Timestamp
ping -D hostname

traceroute - Trace Route to Host

bash
# Trace route
traceroute hostname

# Use ICMP instead of UDP


traceroute -I hostname

# Use TCP SYN


traceroute -T hostname

# Set max hops


traceroute -m 20 hostname

# Set number of queries per hop


traceroute -q 3 hostname

# Set packet size


traceroute 1000 hostname

# Don't resolve hostnames


traceroute -n hostname

# IPv6 traceroute
traceroute6 hostname

# Set source address


traceroute -s [Link] hostname

netstat - Network Statistics (Legacy)

bash
# Show all connections
netstat -a

# Show listening ports


netstat -l

# Show listening TCP ports


netstat -lt

# Show listening UDP ports


netstat -lu

# Show with PID and program name


netstat -p

# Show routing table


netstat -r

# Show network interfaces


netstat -i

# Show statistics
netstat -s

# Continuous monitoring
netstat -c

# Show numeric addresses


netstat -n

# TCP connections with PIDs


netstat -tnp

# Listening services with PIDs


netstat -tlnp

# UDP listening with PIDs


netstat -ulnp

ss - Socket Statistics

bash
# Show all sockets
ss -a

# Show listening sockets


ss -l

# Show TCP sockets


ss -t

# Show UDP sockets


ss -u

# Show listening TCP


ss -tln

# Show listening UDP


ss -uln

# Show process information


ss -p

# Show summary
ss -s

# Show with numeric addresses


ss -n

# Show extended information


ss -e

# Show memory usage


ss -m

# Filter by state
ss state established

# Filter by port
ss -tn sport = :80
ss -tn dport = :443

# Show IPv4 connections


ss -4

# Show IPv6 connections


ss -6
# Kill socket
ss -K dst [Link]

nmap - Network Mapper

bash
# Scan single host
nmap [Link]

# Scan subnet
nmap [Link]/24

# Scan range
nmap [Link]-50

# Scan specific ports


nmap -p 22,80,443 hostname

# Scan all ports


nmap -p- hostname

# Service version detection


nmap -sV hostname

# OS detection
nmap -O hostname

# Aggressive scan
nmap -A hostname

# Fast scan
nmap -F hostname

# TCP SYN scan


nmap -sS hostname

# TCP connect scan


nmap -sT hostname

# UDP scan
nmap -sU hostname

# Ping scan (no port scan)


nmap -sn [Link]/24

# Skip ping
nmap -Pn hostname

# Save output
nmap -oN [Link] hostname
nmap -oX [Link] hostname
curl - Transfer Data from URLs

bash
# GET request
curl [Link]

# Save to file
curl -o [Link] [Link]

# Save with remote filename


curl -O [Link]

# Follow redirects
curl -L [Link]

# Show headers only


curl -I [Link]

# Show headers with content


curl -i [Link]

# POST request
curl -X POST [Link]

# POST with data


curl -X POST -d "key=value" [Link]

# POST JSON
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' [Link]

# PUT request
curl -X PUT -d "data" [Link]

# DELETE request
curl -X DELETE [Link]

# Upload file
curl -F "file=@/path/to/file" [Link]

# Basic authentication
curl -u username:password [Link]

# Custom headers
curl -H "Authorization: Bearer token" [Link]

# Set user agent


curl -A "Mozilla/5.0" [Link]

# Use proxy
curl -x proxy:port [Link]

# Show progress
curl --progress-bar -O [Link]

# Limit rate
curl --limit-rate 1M -O [Link]

# Resume download
curl -C - -O [Link]

# Verbose output
curl -v [Link]

# Silent mode
curl -s [Link]

# Cookie handling
curl -b [Link] [Link]
curl -c [Link] [Link]

wget - Download Files from Web

bash
# Download file
wget [Link]

# Download to specific file


wget -O [Link] [Link]

# Continue interrupted download


wget -c [Link]

# Download in background
wget -b [Link]

# Limit download speed


wget --limit-rate=1M [Link]

# Download recursively
wget -r [Link]

# Download with depth limit


wget -r -l 2 [Link]

# Mirror website
wget -m [Link]

# Download specific file types


wget -r -A pdf,zip [Link]

# Reject specific file types


wget -r -R gif,jpg [Link]

# Set user agent


wget --user-agent="Mozilla/5.0" [Link]

# Basic authentication
wget --user=username --password=password [Link]

# Use proxy
wget -e use_proxy=yes -e http_proxy=proxy:port [Link]

# Retry on failure
wget --tries=10 [Link]

# Wait between requests


wget --wait=2 [Link]

# Quiet mode
wget -q [Link]

# Show progress bar


wget --progress=bar [Link]

# Download multiple files


wget -i [Link]

dig - DNS Lookup

bash
# Basic query
dig [Link]

# Query specific DNS server


dig @[Link] [Link]

# Query specific record type


dig [Link] A
dig [Link] MX
dig [Link] NS
dig [Link] TXT
dig [Link] AAAA

# Short answer
dig +short [Link]

# Reverse DNS lookup


dig -x [Link]

# Trace DNS resolution


dig +trace [Link]

# Query all record types


dig [Link] ANY

# No recursion
dig +norecurse [Link]

# Show only answer section


dig +noall +answer [Link]

# TCP instead of UDP


dig +tcp [Link]

# Set timeout
dig +time=5 [Link]

# Multiple queries
dig [Link] [Link]

nslookup - Query DNS

bash
# Simple lookup
nslookup [Link]

# Query specific DNS server


nslookup [Link] [Link]

# Interactive mode
nslookup

# Reverse lookup
nslookup [Link]

# Query specific record type


nslookup -type=MX [Link]
nslookup -type=NS [Link]
nslookup -type=TXT [Link]

host - DNS Lookup Utility

bash

# Simple lookup
host [Link]

# Query specific DNS server


host [Link] [Link]

# Reverse lookup
host [Link]

# Query specific type


host -t MX [Link]
host -t NS [Link]
host -t TXT [Link]

# Verbose output
host -v [Link]

# Query all records


host -a [Link]

arp - Manipulate ARP Cache

bash
# Show ARP cache
arp

# Show with numeric addresses


arp -n

# Add static ARP entry


arp -s [Link] 00:11:22:33:44:55

# Delete ARP entry


arp -d [Link]

# Show specific interface


arp -i eth0

route - Show/Manipulate IP Routing Table

bash

# Show routing table


route

# Show with numeric addresses


route -n

# Add default gateway


route add default gw [Link]

# Add route to network


route add -net [Link]/24 gw [Link]

# Add route to host


route add -host [Link] gw [Link]

# Delete route
route del -net [Link]/24

# Delete default gateway


route del default

# Show IPv6 routes


route -A inet6

tcpdump - Packet Analyzer

bash
# Capture on interface
tcpdump -i eth0

# Capture specific count


tcpdump -i eth0 -c 100

# Save to file
tcpdump -i eth0 -w [Link]

# Read from file


tcpdump -r [Link]

# Show ASCII content


tcpdump -i eth0 -A

# Show hex and ASCII


tcpdump -i eth0 -X

# Capture specific host


tcpdump -i eth0 host [Link]

# Capture specific port


tcpdump -i eth0 port 80

# Capture TCP traffic


tcpdump -i eth0 tcp

# Capture UDP traffic


tcpdump -i eth0 udp

# Capture ICMP traffic


tcpdump -i eth0 icmp

# Source filter
tcpdump -i eth0 src [Link]

# Destination filter
tcpdump -i eth0 dst [Link]

# Port range
tcpdump -i eth0 portrange 80-443

# Multiple conditions
tcpdump -i eth0 'host [Link] and port 80'

# Don't resolve hostnames


tcpdump -i eth0 -n

# Verbose output
tcpdump -i eth0 -v
tcpdump -i eth0 -vv
tcpdump -i eth0 -vvv

# Snapshot length
tcpdump -i eth0 -s 0

ethtool - Query Network Driver and Hardware

bash
# Show interface information
ethtool eth0

# Show driver information


ethtool -i eth0

# Show statistics
ethtool -S eth0

# Set speed and duplex


ethtool -s eth0 speed 1000 duplex full

# Enable/disable autonegotiation
ethtool -s eth0 autoneg on

# Show offload parameters


ethtool -k eth0

# Enable/disable offload
ethtool -K eth0 tso on
ethtool -K eth0 gso on

# Show ring parameters


ethtool -g eth0

# Set ring parameters


ethtool -G eth0 rx 4096 tx 4096

# Test cable
ethtool -t eth0

# Flash LED
ethtool -p eth0 10

SSH and Remote Access


ssh - OpenSSH Client

bash
# Connect to remote host
ssh user@hostname

# Connect with specific port


ssh -p 2222 user@hostname

# Execute command remotely


ssh user@hostname 'command'

# Use specific key


ssh -i ~/.ssh/id_rsa user@hostname

# Forward X11
ssh -X user@hostname

# Verbose output
ssh -v user@hostname
ssh -vv user@hostname
ssh -vvv user@hostname

# Disable strict host key checking


ssh -o StrictHostKeyChecking=no user@hostname

# Keep connection alive


ssh -o ServerAliveInterval=60 user@hostname

# Compression
ssh -C user@hostname

# Background execution
ssh -f user@hostname command

# Allocate pseudo-TTY
ssh -t user@hostname

# Escape sequence
# ~. disconnect
# ~^Z background ssh
# ~# list forwarded connections
# ~? help

ssh-keygen - Generate SSH Keys

bash
# Generate RSA key
ssh-keygen

# Generate RSA key with specific size


ssh-keygen -t rsa -b 4096

# Generate ED25519 key (recommended)


ssh-keygen -t ed25519

# Specify output file


ssh-keygen -f ~/.ssh/mykey

# Add comment
ssh-keygen -C "email@[Link]"

# Change passphrase
ssh-keygen -p

# Show fingerprint
ssh-keygen -lf ~/.ssh/id_rsa.pub

# Show ASCII art


ssh-keygen -lvf ~/.ssh/id_rsa.pub

# Remove host from known_hosts


ssh-keygen -R hostname

# Generate host keys


ssh-keygen -A

ssh-copy-id - Install SSH Key on Remote Host

bash

# Copy default key


ssh-copy-id user@hostname

# Copy specific key


ssh-copy-id -i ~/.ssh/[Link] user@hostname

# Specify port
ssh-copy-id -p 2222 user@hostname

# Force mode
ssh-copy-id -f user@hostname
ssh-agent - SSH Authentication Agent

bash

# Start ssh-agent
eval $(ssh-agent)

# Add key to agent


ssh-add

# Add specific key


ssh-add ~/.ssh/id_rsa

# Add with timeout (seconds)


ssh-add -t 3600 ~/.ssh/id_rsa

# List loaded keys


ssh-add -l

# Delete key from agent


ssh-add -d ~/.ssh/id_rsa

# Delete all keys


ssh-add -D

# Kill agent
ssh-agent -k

scp - Secure Copy

bash
# Copy file to remote
scp [Link] user@hostname:/path/

# Copy file from remote


scp user@hostname:/path/[Link] .

# Copy directory recursively


scp -r directory/ user@hostname:/path/

# Use specific port


scp -P 2222 [Link] user@hostname:/path/

# Preserve attributes
scp -p [Link] user@hostname:/path/

# Use specific key


scp -i ~/.ssh/id_rsa [Link] user@hostname:/path/

# Limit bandwidth (KB/s)


scp -l 1000 [Link] user@hostname:/path/

# Compression
scp -C [Link] user@hostname:/path/

# Copy between two remote hosts


scp user1@host1:/path/file user2@host2:/path/

# Verbose mode
scp -v [Link] user@hostname:/path/

rsync - Remote File Synchronization

bash
# Sync directory to remote
rsync -avz /local/dir/ user@hostname:/remote/dir/

# Sync from remote to local


rsync -avz user@hostname:/remote/dir/ /local/dir/

# Dry run (test without changes)


rsync -avzn /local/dir/ user@hostname:/remote/dir/

# Delete files in destination not in source


rsync -avz --delete /local/dir/ user@hostname:/remote/dir/

# Use specific SSH port


rsync -avz -e "ssh -p 2222" /local/dir/ user@hostname:/remote/dir/

# Show progress
rsync -avz --progress /local/dir/ user@hostname:/remote/dir/

# Exclude files
rsync -avz --exclude='*.log' /local/dir/ user@hostname:/remote/dir/

# Exclude from file


rsync -avz --exclude-from='[Link]' /local/dir/ user@hostname:/remote/dir/

# Limit bandwidth (KB/s)


rsync -avz --bwlimit=1000 /local/dir/ user@hostname:/remote/dir/

# Preserve hard links


rsync -avzH /local/dir/ user@hostname:/remote/dir/

# Partial transfer resume


rsync -avz --partial /local/dir/ user@hostname:/remote/dir/

# Keep partially transferred files


rsync -avz --partial-dir=.rsync-partial /local/dir/ user@hostname:/remote/dir/

# Update only (skip newer files)


rsync -avzu /local/dir/ user@hostname:/remote/dir/

# Sync with checksum verification


rsync -avzc /local/dir/ user@hostname:/remote/dir/

# Stats summary
rsync -avz --stats /local/dir/ user@hostname:/remote/dir/

sftp - Secure File Transfer


bash

# Connect to remote host


sftp user@hostname

# Use specific port


sftp -P 2222 user@hostname

# SFTP commands (interactive):


# ls - list remote files
# lls - list local files
# pwd - remote working directory
# lpwd - local working directory
# cd - change remote directory
# lcd - change local directory
# get file - download file
# put file - upload file
# mget *.txt - download multiple
# mput *.txt - upload multiple
# mkdir - create remote directory
# lmkdir - create local directory
# rm - remove remote file
# rmdir - remove remote directory
# exit or quit - close connection

# Batch mode
sftp -b [Link] user@hostname

ssh-tunnel - Port Forwarding

bash
# Local port forwarding
ssh -L local_port:destination:remote_port user@hostname

# Example: Access remote MySQL


ssh -L 3306:localhost:3306 user@hostname

# Remote port forwarding


ssh -R remote_port:localhost:local_port user@hostname

# Example: Expose local web server


ssh -R 8080:localhost:80 user@hostname

# Dynamic port forwarding (SOCKS proxy)


ssh -D 1080 user@hostname

# Keep tunnel open in background


ssh -fN -L 3306:localhost:3306 user@hostname

# Multiple forwards
ssh -L 3306:localhost:3306 -L 5432:localhost:5432 user@hostname

Service Management
systemctl - Systemd Service Manager

bash
# Start service
systemctl start nginx

# Stop service
systemctl stop nginx

# Restart service
systemctl restart nginx

# Reload configuration
systemctl reload nginx

# Reload or restart
systemctl reload-or-restart nginx

# Enable service at boot


systemctl enable nginx

# Disable service at boot


systemctl disable nginx

# Enable and start


systemctl enable --now nginx

# Check status
systemctl status nginx

# Check if active
systemctl is-active nginx

# Check if enabled
systemctl is-enabled nginx

# List all services


systemctl list-units --type=service

# List running services


systemctl list-units --type=service --state=running

# List failed services


systemctl --failed

# List all unit files


systemctl list-unit-files

# Show service dependencies


systemctl list-dependencies nginx

# Edit service file


systemctl edit nginx

# Edit full service file


systemctl edit --full nginx

# Show service file


systemctl cat nginx

# Mask service (prevent start)


systemctl mask nginx

# Unmask service
systemctl unmask nginx

# Reload systemd configuration


systemctl daemon-reload

# Reexecute systemd
systemctl daemon-reexec

# Show service properties


systemctl show nginx

# Set service property


systemctl set-property nginx CPUShares=1024

# Isolate target
systemctl isolate [Link]

# Get default target


systemctl get-default

# Set default target


systemctl set-default [Link]

service - Service Control (SysV Init)

bash
# Start service
service nginx start

# Stop service
service nginx stop

# Restart service
service nginx restart

# Reload configuration
service nginx reload

# Check status
service nginx status

# List all services


service --status-all

journalctl - Query Systemd Journal

bash
# Show all logs
journalctl

# Follow logs (like tail -f)


journalctl -f

# Show logs for service


journalctl -u nginx

# Follow service logs


journalctl -u nginx -f

# Show logs since boot


journalctl -b

# Show logs from previous boot


journalctl -b -1

# Show logs since time


journalctl --since "2024-01-01 00:00:00"

# Show logs until time


journalctl --until "2024-01-31 23:59:59"

# Show logs for last hour


journalctl --since "1 hour ago"

# Show logs for today


journalctl --since today

# Show kernel messages


journalctl -k

# Show logs by priority


journalctl -p err

# Show with different output


journalctl -o json
journalctl -o json-pretty
journalctl -o verbose

# Show disk usage


journalctl --disk-usage

# Vacuum by time
journalctl --vacuum-time=7d
# Vacuum by size
journalctl --vacuum-size=100M

# Show log for specific PID


journalctl _PID=1234

# Show log for specific user


journalctl _UID=1000

# Reverse order (newest first)


journalctl -r

# Show number of lines


journalctl -n 50

# No pager
journalctl --no-pager

# Verify journal files


journalctl --verify

chkconfig - System Services Manager (Legacy)

bash

# List all services


chkconfig --list

# Enable service
chkconfig nginx on

# Disable service
chkconfig nginx off

# Add service
chkconfig --add nginx

# Remove service
chkconfig --del nginx

# Set service for specific runlevels


chkconfig --level 345 nginx on

update-rc.d - Update System Services (Debian)

bash
# Enable service
update-rc.d nginx enable

# Disable service
update-rc.d nginx disable

# Remove service
update-rc.d nginx remove

# Add service with defaults


update-rc.d nginx defaults

# Set start/stop priorities


update-rc.d nginx start 20 2 3 4 5 . stop 20 0 1 6 .

Package Management
APT - Debian/Ubuntu Package Manager

bash
# Update package lists
apt update
apt-get update

# Upgrade packages
apt upgrade
apt-get upgrade

# Full upgrade (remove obsolete packages)


apt full-upgrade
apt-get dist-upgrade

# Install package
apt install package_name
apt-get install package_name

# Install specific version


apt install package_name=version

# Install without recommends


apt install --no-install-recommends package_name

# Remove package
apt remove package_name

# Remove package and configuration


apt purge package_name
apt-get purge package_name

# Remove unused packages


apt autoremove
apt-get autoremove

# Clean package cache


apt clean
apt-get clean

# Remove downloaded packages


apt autoclean

# Search for package


apt search package_name
apt-cache search package_name

# Show package information


apt show package_name
apt-cache show package_name

# List installed packages


apt list --installed

# List upgradable packages


apt list --upgradable

# Show package dependencies


apt-cache depends package_name

# Show reverse dependencies


apt-cache rdepends package_name

# Download package without installing


apt download package_name

# Check for broken dependencies


apt check

# Edit sources list


apt edit-sources

dpkg - Debian Package Manager

bash
# Install package from file
dpkg -i [Link]

# Remove package
dpkg -r package_name

# Remove package and configuration


dpkg -P package_name

# List installed packages


dpkg -l

# List files in package


dpkg -L package_name

# Search which package owns file


dpkg -S /path/to/file

# Show package information


dpkg -s package_name

# Show package contents


dpkg -c [Link]

# Extract package
dpkg -x [Link] /path/

# Configure unpacked packages


dpkg --configure -a

# Verify package integrity


dpkg -V package_name

# List package contents


dpkg --contents [Link]

YUM - Red Hat/CentOS Package Manager

bash
# Update package lists
yum check-update

# Update packages
yum update

# Update specific package


yum update package_name

# Install package
yum install package_name

# Install local package


yum localinstall [Link]

# Remove package
yum remove package_name

# Search for package


yum search package_name

# Show package information


yum info package_name

# List installed packages


yum list installed

# List available packages


yum list available

# Show dependencies
yum deplist package_name

# Clean cache
yum clean all

# Show history
yum history

# Undo transaction
yum history undo ID

# Check for updates


yum check-update

# Download package only


yumdownloader package_name

# What provides file


yum provides /path/to/file

DNF - Fedora Package Manager

bash
# Update packages
dnf update

# Install package
dnf install package_name

# Remove package
dnf remove package_name

# Search package
dnf search package_name

# Show package information


dnf info package_name

# List installed packages


dnf list installed

# List available packages


dnf list available

# Show dependencies
dnf repoquery --requires package_name

# Clean cache
dnf clean all

# Show history
dnf history

# Undo transaction
dnf history undo ID

# Download package
dnf download package_name

# What provides file


dnf provides /path/to/file

# List repositories
dnf repolist

# Enable repository
dnf config-manager --enable repo_name
# Disable repository
dnf config-manager --disable repo_name

RPM - Red Hat Package Manager

bash
# Install package
rpm -ivh [Link]

# Upgrade package
rpm -Uvh [Link]

# Remove package
rpm -e package_name

# Query all packages


rpm -qa

# Query specific package


rpm -q package_name

# Show package information


rpm -qi package_name

# List files in package


rpm -ql package_name

# Show package file info


rpm -qip [Link]

# List files in package file


rpm -qlp [Link]

# Which package owns file


rpm -qf /path/to/file

# Verify package
rpm -V package_name

# Import GPG key


rpm --import /path/to/key

# Check dependencies
rpm -qpR [Link]

# Show scripts
rpm -q --scripts package_name

snap - Snap Package Manager

bash
# Install snap
snap install package_name

# Install from specific channel


snap install package_name --channel=edge

# Install classic snap


snap install package_name --classic

# List installed snaps


snap list

# Find snaps
snap find package_name

# Show snap info


snap info package_name

# Update snap
snap refresh package_name

# Update all snaps


snap refresh

# Remove snap
snap remove package_name

# Revert to previous version


snap revert package_name

# Show snap connections


snap connections

# Connect interface
snap connect package:interface

# Disconnect interface
snap disconnect package:interface

# Show snap changes


snap changes

# Watch change
snap watch 1

flatpak - Flatpak Package Manager


bash

# Install flatpak
flatpak install package_name

# Install from specific remote


flatpak install flathub package_name

# List installed flatpaks


flatpak list

# Search flatpaks
flatpak search package_name

# Show flatpak info


flatpak info package_name

# Update flatpak
flatpak update package_name

# Update all flatpaks


flatpak update

# Uninstall flatpak
flatpak uninstall package_name

# Run flatpak
flatpak run package_name

# List remotes
flatpak remotes

# Add remote
flatpak remote-add --if-not-exists flathub [Link]

# Remove remote
flatpak remote-delete remote_name

# Remove unused runtimes


flatpak uninstall --unused
Text Processing
grep - Search Text Patterns

bash
# Search for pattern
grep "pattern" [Link]

# Case-insensitive search
grep -i "pattern" [Link]

# Recursive search
grep -r "pattern" /path/

# Show line numbers


grep -n "pattern" [Link]

# Count matches
grep -c "pattern" [Link]

# Show only filenames


grep -l "pattern" *.txt

# Show files without match


grep -L "pattern" *.txt

# Invert match
grep -v "pattern" [Link]

# Show lines before match


grep -B 3 "pattern" [Link]

# Show lines after match


grep -A 3 "pattern" [Link]

# Show lines around match


grep -C 3 "pattern" [Link]

# Whole word match


grep -w "word" [Link]

# Extended regex
grep -E "pattern1|pattern2" [Link]

# Fixed strings (no regex)


grep -F "[Link]" [Link]

# Multiple patterns
grep -e "pattern1" -e "pattern2" [Link]

# Patterns from file


grep -f [Link] [Link]

# Color output
grep --color=auto "pattern" [Link]

# Show only matched part


grep -o "pattern" [Link]

# Quiet mode (exit status only)


grep -q "pattern" [Link]

# Exclude files
grep -r --exclude="*.log" "pattern" /path/

# Exclude directories
grep -r --exclude-dir=".git" "pattern" /path/

sed - Stream Editor

bash
# Substitute first occurrence
sed 's/old/new/' [Link]

# Substitute all occurrences


sed 's/old/new/g' [Link]

# Substitute on specific line


sed '5s/old/new/' [Link]

# Substitute in range
sed '1,10s/old/new/g' [Link]

# Delete lines
sed '5d' [Link]
sed '/pattern/d' [Link]

# Delete range
sed '1,10d' [Link]

# Print specific line


sed -n '5p' [Link]

# Print range
sed -n '1,10p' [Link]

# Print matching lines


sed -n '/pattern/p' [Link]

# Insert before line


sed '5i\new line' [Link]

# Append after line


sed '5a\new line' [Link]

# Change line
sed '5c\replacement line' [Link]

# Multiple commands
sed -e 's/old/new/g' -e 's/foo/bar/g' [Link]

# Edit in place
sed -i 's/old/new/g' [Link]

# Edit in place with backup


sed -[Link] 's/old/new/g' [Link]
# Case-insensitive substitution
sed 's/old/new/gi' [Link]

# Use different delimiter


sed 's|/old/path|/new/path|g' [Link]

# Delete empty lines


sed '/^$/d' [Link]

# Delete lines starting with #


sed '/^#/d' [Link]

# Add line at beginning


sed '1i\first line' [Link]

# Add line at end


sed '$a\last line' [Link]

# Print every other line


sed -n '1~2p' [Link]

# Transform characters
sed 'y/abc/ABC/' [Link]

awk - Pattern Scanning and Processing

bash
# Print entire file
awk '{print}' [Link]

# Print specific field


awk '{print $1}' [Link]

# Print multiple fields


awk '{print $1, $3}' [Link]

# Print with custom separator


awk '{print $1 ":" $2}' [Link]

# Print lines matching pattern


awk '/pattern/ {print}' [Link]

# Print fields from matching lines


awk '/pattern/ {print $1}' [Link]

# Use custom field separator


awk -F: '{print $1}' /etc/passwd

# Print line number


awk '{print NR, $0}' [Link]

# Print number of fields


awk '{print NF}' [Link]

# Print last field


awk '{print $NF}' [Link]

# Sum column
awk '{sum+=$1} END {print sum}' [Link]

# Average column
awk '{sum+=$1; count++} END {print sum/count}' [Link]

# Print if column matches


awk '$3 > 100' [Link]

# Multiple conditions
awk '$1 == "error" && $3 > 100' [Link]

# BEGIN and END blocks


awk 'BEGIN {print "Start"} {print $0} END {print "End"}' [Link]

# Custom output separator


awk 'BEGIN {OFS=","} {print $1,$2}' [Link]

# Length of field
awk 'length($1) > 10' [Link]

# Count occurrences
awk '{count[$1]++} END {for (i in count) print i, count[i]}' [Link]

# Print unique lines


awk '!seen[$0]++' [Link]

# Format output
awk '{printf "%-10s %5d\n", $1, $2}' [Link]

cut - Remove Sections from Lines

bash

# Cut by character position


cut -c 1-5 [Link]

# Cut by field (tab delimiter)


cut -f 1,3 [Link]

# Custom delimiter
cut -d: -f1 /etc/passwd

# Cut from field to end


cut -d: -f3- /etc/passwd

# Cut multiple ranges


cut -c 1-5,10-15 [Link]

# Complement selection
cut -d: --complement -f2 [Link]

# Output delimiter
cut -d: -f1,3 --output-delimiter=" " /etc/passwd

sort - Sort Lines

bash
# Basic sort
sort [Link]

# Reverse sort
sort -r [Link]

# Numeric sort
sort -n [Link]

# Sort by column
sort -k 2 [Link]

# Sort by multiple columns


sort -k 2 -k 3 [Link]

# Custom delimiter
sort -t: -k3 -n /etc/passwd

# Unique lines
sort -u [Link]

# Case-insensitive sort
sort -f [Link]

# Human numeric sort (1K, 1M, 1G)


sort -h [Link]

# Check if sorted
sort -c [Link]

# Month sort
sort -M [Link]

# Random sort
sort -R [Link]

# Stable sort
sort -s [Link]

# Output to file
sort -o [Link] [Link]

uniq - Report or Omit Repeated Lines

bash
# Remove adjacent duplicates
uniq [Link]

# Count occurrences
uniq -c [Link]

# Show only duplicates


uniq -d [Link]

# Show only unique lines


uniq -u [Link]

# Ignore case
uniq -i [Link]

# Skip fields
uniq -f 1 [Link]

# Skip characters
uniq -s 5 [Link]

# Compare specific characters


uniq -w 10 [Link]

tr - Translate Characters

bash
# Convert to uppercase
tr 'a-z' 'A-Z' < [Link]

# Convert to lowercase
tr 'A-Z' 'a-z' < [Link]

# Delete characters
tr -d '0-9' < [Link]

# Squeeze repeats
tr -s ' ' < [Link]

# Replace characters
tr ':' ',' < [Link]

# Delete complement
tr -cd '0-9' < [Link]

# Translate with sets


echo "hello" | tr 'aeiou' '12345'

# Delete newlines
tr -d '\n' < [Link]

# Convert spaces to tabs


tr -s ' ' '\t' < [Link]

wc - Word Count

bash
# Count lines, words, and bytes
wc [Link]

# Count lines only


wc -l [Link]

# Count words only


wc -w [Link]

# Count characters
wc -m [Link]

# Count bytes
wc -c [Link]

# Count longest line length


wc -L [Link]

# Multiple files
wc [Link] [Link]

head - Output First Part of Files

bash

# First 10 lines (default)


head [Link]

# First n lines
head -n 20 [Link]
head -20 [Link]

# All except last n lines


head -n -5 [Link]

# First n bytes
head -c 100 [Link]

# Multiple files
head [Link] [Link]

# Quiet mode (no headers)


head -q [Link] [Link]

# Verbose mode (always headers)


head -v [Link]
tail - Output Last Part of Files

bash

# Last 10 lines (default)


tail [Link]

# Last n lines
tail -n 20 [Link]
tail -20 [Link]

# Skip first n lines


tail -n +5 [Link]

# Last n bytes
tail -c 100 [Link]

# Follow file (monitor)


tail -f [Link]

# Follow with retry


tail -F [Link]

# Follow multiple files


tail -f [Link] [Link]

# Follow with PID (stop when process dies)


tail -f --pid=1234 [Link]

# Show last n lines and follow


tail -n 50 -f [Link]

diff - Compare Files Line by Line

bash
# Compare files
diff [Link] [Link]

# Unified format
diff -u [Link] [Link]

# Context format
diff -c [Link] [Link]

# Side by side
diff -y [Link] [Link]

# Ignore case
diff -i [Link] [Link]

# Ignore whitespace
diff -w [Link] [Link]

# Ignore blank lines


diff -B [Link] [Link]

# Brief output
diff -q [Link] [Link]

# Recursive directory compare


diff -r dir1/ dir2/

# Show which files differ


diff -rq dir1/ dir2/

# Create patch file


diff -u [Link] [Link] > [Link]

# Exclude files
diff -r --exclude="*.log" dir1/ dir2/

patch - Apply Diff File

bash
# Apply patch
patch < [Link]

# Apply to specific file


patch [Link] < [Link]

# Reverse patch
patch -R < [Link]

# Dry run
patch --dry-run < [Link]

# Backup original
patch -b < [Link]

# Strip directory levels


patch -p1 < [Link]

# Force patch
patch -f < [Link]

comm - Compare Sorted Files

bash

# Show unique and common lines


comm [Link] [Link]

# Show only lines in file1


comm -23 [Link] [Link]

# Show only lines in file2


comm -13 [Link] [Link]

# Show only common lines


comm -12 [Link] [Link]

# Suppress column 1 (unique to file1)


comm -1 [Link] [Link]

# Suppress column 2 (unique to file2)


comm -2 [Link] [Link]

# Suppress column 3 (common)


comm -3 [Link] [Link]
paste - Merge Lines of Files

bash

# Merge files side by side


paste [Link] [Link]

# Custom delimiter
paste -d: [Link] [Link]

# Serial merge (one file at a time)


paste -s [Link]

# Multiple delimiters
paste -d:, [Link] [Link] [Link]

join - Join Lines on Common Field

bash

# Join on first field


join [Link] [Link]

# Join on specific field


join -1 2 -2 1 [Link] [Link]

# Custom delimiter
join -t: [Link] [Link]

# Print unpairable lines


join -a 1 [Link] [Link]

# Ignore case
join -i [Link] [Link]

# Empty field replacement


join -e NULL [Link] [Link]

column - Format Input into Columns

bash
# Create columns
column [Link]

# Table format
column -t [Link]

# Custom separator
column -t -s: [Link]

# Fill rows before columns


column -x [Link]

# Specify column width


column -c 80 [Link]

expand - Convert Tabs to Spaces

bash

# Convert tabs to spaces (default 8)


expand [Link]

# Custom tab width


expand -t 4 [Link]

# Multiple tab stops


expand -t 4,8,12 [Link]

# Initial tabs only


expand -i [Link]

unexpand - Convert Spaces to Tabs

bash

# Convert spaces to tabs


unexpand [Link]

# Convert all spaces


unexpand -a [Link]

# Custom tab width


unexpand -t 4 [Link]

# First blanks only


unexpand --first-only [Link]
Disk and File System Management
fdisk - Partition Table Manipulator

bash

# List partitions
fdisk -l

# Edit partition table


fdisk /dev/sda

# Inside fdisk:
# m - help
# p - print partition table
# n - new partition
# d - delete partition
# t - change partition type
# w - write changes
# q - quit without saving
# l - list partition types
# a - toggle bootable flag

# List specific device


fdisk -l /dev/sda

# Show sector size


fdisk -s /dev/sda1

parted - Partition Editor

bash
# Interactive mode
parted /dev/sda

# Print partition table


parted /dev/sda print

# Create GPT partition table


parted /dev/sda mklabel gpt

# Create MBR partition table


parted /dev/sda mklabel msdos

# Create partition
parted /dev/sda mkpart primary ext4 0% 100%

# Delete partition
parted /dev/sda rm 1

# Resize partition
parted /dev/sda resizepart 1 20GB

# Set boot flag


parted /dev/sda set 1 boot on

# Rescue partition
parted /dev/sda rescue 1000 2000

# Align check
parted /dev/sda align-check optimal 1

mkfs - Make File System

bash
# Create ext4 filesystem
mkfs.ext4 /dev/sda1

# Create ext3 filesystem


mkfs.ext3 /dev/sda1

# Create ext2 filesystem


mkfs.ext2 /dev/sda1

# Create XFS filesystem


[Link] /dev/sda1

# Create Btrfs filesystem


[Link] /dev/sda1

# Create FAT32 filesystem


[Link] -F 32 /dev/sda1

# Create NTFS filesystem


[Link] /dev/sda1

# With label
mkfs.ext4 -L mylabel /dev/sda1

# With custom options


mkfs.ext4 -b 4096 -m 1 /dev/sda1

# Force creation
mkfs.ext4 -F /dev/sda1

mount - Mount File System

bash
# Mount partition
mount /dev/sda1 /mnt

# Mount with type


mount -t ext4 /dev/sda1 /mnt

# Mount read-only
mount -o ro /dev/sda1 /mnt

# Mount with options


mount -o rw,noexec,nosuid /dev/sda1 /mnt

# Show mounted filesystems


mount

# Mount by UUID
mount UUID=xxxxx /mnt

# Mount by label
mount LABEL=mylabel /mnt

# Mount ISO
mount -o loop [Link] /mnt/iso

# Bind mount
mount --bind /source /destination

# Remount with different options


mount -o remount,rw /mnt

# Mount all filesystems in fstab


mount -a

# Mount NFS share


mount -t nfs server:/share /mnt

# Mount CIFS/SMB share


mount -t cifs //server/share /mnt -o username=user,password=pass

# Mount with credentials file


mount -t cifs //server/share /mnt -o credentials=/path/to/creds

umount - Unmount File System

bash
# Unmount by mount point
umount /mnt

# Unmount by device
umount /dev/sda1

# Force unmount
umount -f /mnt

# Lazy unmount
umount -l /mnt

# Unmount all
umount -a

# Unmount specific type


umount -a -t nfs

# Verbose output
umount -v /mnt

fsck - File System Check

bash
# Check filesystem
fsck /dev/sda1

# Automatic repair
fsck -a /dev/sda1

# Interactive repair
fsck -r /dev/sda1

# Force check
fsck -f /dev/sda1

# Check all filesystems


fsck -A

# Verbose output
fsck -v /dev/sda1

# Dry run
fsck -n /dev/sda1

# Check ext4 filesystem


fsck.ext4 /dev/sda1

# Bad blocks check


fsck -c /dev/sda1

tune2fs - Adjust Ext2/3/4 Parameters

bash
# Show filesystem info
tune2fs -l /dev/sda1

# Set filesystem label


tune2fs -L mylabel /dev/sda1

# Set mount count before check


tune2fs -c 30 /dev/sda1

# Set check interval


tune2fs -i 30d /dev/sda1

# Disable forced checks


tune2fs -c 0 -i 0 /dev/sda1

# Set reserved blocks percentage


tune2fs -m 1 /dev/sda1

# Enable journaling
tune2fs -j /dev/sda1

# Add filesystem features


tune2fs -O has_journal /dev/sda1

# Remove filesystem features


tune2fs -O ^has_journal /dev/sda1

# Set last mount point


tune2fs -M /mnt /dev/sda1

# Set UUID
tune2fs -U random /dev/sda1

blkid - Locate/Print Block Device Attributes

bash
# Show all block devices
blkid

# Show specific device


blkid /dev/sda1

# Show only UUID


blkid -s UUID /dev/sda1

# Show only type


blkid -s TYPE /dev/sda1

# Show only label


blkid -s LABEL /dev/sda1

# Machine-readable output
blkid -o export

# Probe specific device


blkid -p /dev/sda1

lsof - List Open Files

bash
# List all open files
lsof

# Files opened by user


lsof -u username

# Files opened by process


lsof -p PID

# Files opened by command


lsof -c command_name

# Files in directory
lsof +D /path/

# Network connections
lsof -i

# TCP connections
lsof -i tcp

# UDP connections
lsof -i udp

# Specific port
lsof -i :80

# Specific address
lsof -i @[Link]

# Listening ports
lsof -i -sTCP:LISTEN

# Files on device
lsof /dev/sda1

# Deleted files still open


lsof | grep deleted

# Combine conditions (AND)


lsof -u user -c command

# Combine conditions (OR)


lsof -u user -o -c command
# Repeat mode
lsof -r 2

dd - Convert and Copy Files

bash
# Copy disk to disk
dd if=/dev/sda of=/dev/sdb

# Create disk image


dd if=/dev/sda of=[Link]

# Restore disk image


dd if=[Link] of=/dev/sda

# Copy with progress


dd if=/dev/sda of=/dev/sdb status=progress

# Copy specific size


dd if=/dev/sda of=[Link] bs=4M count=100

# Copy MBR
dd if=/dev/sda of=[Link] bs=512 count=1

# Create empty file


dd if=/dev/zero of=[Link] bs=1M count=100

# Random data file


dd if=/dev/urandom of=[Link] bs=1M count=10

# Wipe disk
dd if=/dev/zero of=/dev/sda bs=4M status=progress

# Clone partition
dd if=/dev/sda1 of=/dev/sdb1 bs=4M

# Convert to uppercase
dd if=[Link] of=[Link] conv=ucase

# Sync after write


dd if=input of=output conv=fsync

# Skip bytes
dd if=input of=output skip=100 bs=1

# Seek position
dd if=input of=output seek=100 bs=1

sync - Flush File System Buffers

bash
# Sync all filesystems
sync

# Sync specific file


sync -f [Link]

# Sync filesystem
sync -f /mnt

# Sync data only (no metadata)


sync -d [Link]

System Monitoring
vmstat - Virtual Memory Statistics

bash

# Show statistics
vmstat

# Update every 2 seconds


vmstat 2

# Update 5 times
vmstat 2 5

# Show memory in MB
vmstat -S M

# Show disk statistics


vmstat -d

# Show disk partition statistics


vmstat -p /dev/sda1

# Show slab info


vmstat -m

# Active/inactive memory
vmstat -a

# Wide output
vmstat -w
iostat - I/O Statistics

bash

# Show CPU and I/O stats


iostat

# Update every 2 seconds


iostat 2

# Extended statistics
iostat -x

# Show in MB/s
iostat -m

# Show specific devices


iostat -p sda

# CPU statistics only


iostat -c

# Device statistics only


iostat -d

# Human-readable
iostat -h

# Show timestamps
iostat -t

# JSON output
iostat -o JSON

mpstat - Processor Statistics

bash
# Show CPU statistics
mpstat

# All processors
mpstat -P ALL

# Specific processor
mpstat -P 0

# Update every 2 seconds


mpstat 2

# Update 5 times
mpstat 2 5

# Show interrupts
mpstat -I ALL

sar - System Activity Reporter

bash
# CPU usage
sar

# Memory usage
sar -r

# Swap usage
sar -S

# I/O statistics
sar -b

# Network statistics
sar -n DEV

# Load average
sar -q

# All statistics
sar -A

# From specific time


sar -s 10:00:00

# To specific time
sar -e 11:00:00

# From file
sar -f /var/log/sa/sa01

# Real-time monitoring
sar 2 10

dstat - Versatile Resource Statistics

bash
# Default output
dstat

# Full output
dstat -a

# CPU stats
dstat -c

# Disk stats
dstat -d

# Network stats
dstat -n

# Memory stats
dstat -m

# System stats
dstat -s

# Top CPU process


dstat --top-cpu

# Top memory process


dstat --top-mem

# Top I/O process


dstat --top-io

# Custom interval
dstat 5

# Output to CSV
dstat --output [Link]

iftop - Network Bandwidth Monitor

bash
# Monitor default interface
iftop

# Monitor specific interface


iftop -i eth0

# Don't resolve hostnames


iftop -n

# Don't resolve ports


iftop -N

# Show bytes instead of bits


iftop -B

# Filter by network
iftop -F [Link]/24

# Show bars
iftop -b

# No promiscuous mode
iftop -p

nethogs - Network Per-Process Bandwidth

bash

# Monitor all interfaces


nethogs

# Monitor specific interface


nethogs eth0

# Don't resolve hostnames


nethogs -n

# Trace mode
nethogs -t

# Update interval
nethogs -d 5

# Monitor multiple interfaces


nethogs eth0 wlan0
iotop - I/O Monitor

bash

# Monitor I/O
iotop

# Only show processes doing I/O


iotop -o

# Batch mode
iotop -b

# Iterations
iotop -n 5

# Delay between iterations


iotop -d 2

# Only show specific PID


iotop -p PID

# Accumulate I/O
iotop -a

# Show kilobytes
iotop -k

atop - Advanced System Monitor

bash
# Start atop
atop

# Update interval
atop 5

# Log to file
atop -w /var/log/[Link]

# Read from file


atop -r /var/log/[Link]

# Show specific time


atop -r /var/log/[Link] -b 10:00 -e 11:00

# Inside atop:
# m - memory
# d - disk
# n - network
# c - command line
# q - quit

nmon - Performance Monitor

bash

# Start nmon
nmon

# Inside nmon:
# c - CPU
# m - Memory
# d - Disk
# n - Network
# t - Top processes
# q - Quit

# Capture mode
nmon -f -s 60 -c 60

# Output to file
nmon -F [Link]

glances - System Monitor

bash
# Start glances
glances

# Update interval
glances -t 2

# Export to CSV
glances --export csv --export-csv-file [Link]

# Client/server mode
glances -s # Server
glances -c server # Client

# Web interface
glances -w

# Disable modules
glances --disable-network

# Enable additional modules


glances --enable-process-extended

Security and Firewall


iptables - IPv4 Firewall Administration

bash
# List rules
iptables -L

# List with line numbers


iptables -L --line-numbers

# List with verbose info


iptables -L -v

# List specific chain


iptables -L INPUT

# Show numeric addresses


iptables -L -n

# Allow incoming SSH


iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow incoming HTTP/HTTPS


iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow from specific IP


iptables -A INPUT -s [Link] -j ACCEPT

# Block specific IP
iptables -A INPUT -s [Link] -j DROP

# Allow established connections


iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow loopback
iptables -A INPUT -i lo -j ACCEPT

# Delete rule by number


iptables -D INPUT 5

# Delete specific rule


iptables -D INPUT -p tcp --dport 80 -j ACCEPT

# Insert rule at position


iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT

# Replace rule
iptables -R INPUT 1 -p tcp --dport 22 -j ACCEPT
# Flush all rules
iptables -F

# Flush specific chain


iptables -F INPUT

# Set default policy


iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Create custom chain


iptables -N custom_chain

# Delete custom chain


iptables -X custom_chain

# Save rules (Debian/Ubuntu)


iptables-save > /etc/iptables/rules.v4

# Restore rules
iptables-restore < /etc/iptables/rules.v4

# NAT (masquerading)
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

# Port forwarding
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

# Limit connections
iptables -A INPUT -p tcp --dport 22 -m connlimit --connlimit-above 3 -j REJECT

# Rate limiting
iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT

firewalld - Dynamic Firewall Manager

bash
# Check status
firewall-cmd --state

# List all zones


firewall-cmd --get-zones

# Get default zone


firewall-cmd --get-default-zone

# Set default zone


firewall-cmd --set-default-zone=public

# List active zones


firewall-cmd --get-active-zones

# List all services


firewall-cmd --get-services

# List rules in zone


firewall-cmd --zone=public --list-all

# Add service
firewall-cmd --zone=public --add-service=http
firewall-cmd --zone=public --add-service=https

# Remove service
firewall-cmd --zone=public --remove-service=http

# Add port
firewall-cmd --zone=public --add-port=8080/tcp

# Remove port
firewall-cmd --zone=public --remove-port=8080/tcp

# Add port range


firewall-cmd --zone=public --add-port=5000-5100/tcp

# Add source
firewall-cmd --zone=public --add-source=[Link]/24

# Remove source
firewall-cmd --zone=public --remove-source=[Link]/24

# Block/unblock ICMP
firewall-cmd --zone=public --add-icmp-block=echo-request
firewall-cmd --zone=public --remove-icmp-block=echo-request
# Make changes permanent
firewall-cmd --runtime-to-permanent

# Add permanent rule


firewall-cmd --permanent --zone=public --add-service=http

# Reload firewall
firewall-cmd --reload

# Complete reload
firewall-cmd --complete-reload

# Add rich rule


firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="[Link]/24" accept'

# Port forwarding
firewall-cmd --zone=public --add-forward-port=port=80:proto=tcp:toport=8080

# Enable masquerading
firewall-cmd --zone=public --add-masquerade

# Panic mode (block all)


firewall-cmd --panic-on
firewall-cmd --panic-off

ufw - Uncomplicated Firewall

bash
# Enable firewall
ufw enable

# Disable firewall
ufw disable

# Show status
ufw status

# Verbose status
ufw status verbose

# Numbered rules
ufw status numbered

# Allow service
ufw allow ssh
ufw allow http
ufw allow https

# Allow port
ufw allow 8080/tcp
ufw allow 53/udp

# Allow from IP
ufw allow from [Link]

# Allow from subnet


ufw allow from [Link]/24

# Allow to specific port


ufw allow from [Link] to any port 22

# Deny service
ufw deny ssh

# Deny port
ufw deny 23/tcp

# Delete rule
ufw delete allow 80/tcp

# Delete by number
ufw delete 5

# Set default policies


ufw default deny incoming
ufw default allow outgoing

# Logging
ufw logging on
ufw logging off
ufw logging low
ufw logging medium
ufw logging high

# Rate limiting
ufw limit ssh

# Application profiles
ufw app list
ufw allow 'Apache Full'
ufw allow 'OpenSSH'

# Reset firewall
ufw reset

# Advanced syntax
ufw allow proto tcp from [Link]/24 to any port 22

SELinux - Security-Enhanced Linux

bash
# Check SELinux status
sestatus

# Get current mode


getenforce

# Set mode temporarily


setenforce 0 # Permissive
setenforce 1 # Enforcing

# Set mode permanently (edit /etc/selinux/config)


# SELINUX=enforcing
# SELINUX=permissive
# SELINUX=disabled

# List booleans
getsebool -a

# Set boolean
setsebool -P httpd_can_network_connect on

# File context
ls -Z

# Process context
ps -eZ

# Restore default context


restorecon /path/to/file

# Restore recursively
restorecon -R /path/to/directory

# Change file context


chcon -t httpd_sys_content_t /var/www/html/[Link]

# Set file context permanently


semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
restorecon -R /web

# Allow port for service


semanage port -a -t http_port_t -p tcp 8080

# List ports
semanage port -l
# Check why something was denied
ausearch -m avc -ts recent

# Generate policy module from audit log


audit2allow -a

# Create and install policy module


audit2allow -a -M mypolicy
semodule -i [Link]

# List loaded modules


semodule -l

# Remove module
semodule -r mypolicy

AppArmor - Application Armor

bash

# Check status
apparmor_status

# List profiles
aa-status

# Set profile to enforce mode


aa-enforce /etc/apparmor.d/[Link]

# Set profile to complain mode

You might also like