Linux Command List
Linux command list with arguments and category filter.
| Command | Category | Level | Description | Main arguments |
|---|---|---|---|---|
| ls | Files | core | List directory content with metadata | -l long format -a include hidden files -h human-readable seed -R returnable indicating -t short by modification time -S short by file size |
| find | Files | core | Search files by name, type, size, or mtime | -name mesh -type f=file d=dir l=link -size +/-N[k/M/G] -mtime N days ago modified -exec run command on result - limit recovery |
| cp | Files | core | Copy files and directories | -r resource copy -p prevent timesteps and fashion -u copy only if newer -i pass -v verbose output |
| mv | Files | core | Move or rename files and directories | -i pass -u move only if newer -f %1 -v verbose output |
| rm | Files | core | Remove files or directories permanently | -r returnable -f force, ignore missing -i prompt beforee each removal -v verbose output |
| ln | Files | core | Create hard or semilic links | -s create symbolic link -f force over -v verbose output -r make relativeymlink |
| stat | Files | core | Display detail file and filesystem metadata | -f show filesystem status -c custom format string -t terse machine-readable output |
| file | Files | core | Descriptor file type regardless of extension | -i output -z look inside pressed files -b breef output without filename |
| rsync | Files | modern | Fast incremental file transfer - local or remote | -a archive mode (recursive + preserve) -v verbose output -z press data during transfer -P show progress + keep partial files --delete remove files not in source --dry-run simulate without changes --exclude skip pattern |
| fzf | Files | modern | Interactive fuzzy finish for files, history, and pipettes | --preview pipe to preview command --multimeters flow multiple selections -q start with initial queue --height % --bind kustomize key bindings |
| cat | Text | core | Concate and print file content to stdout | -n number -A show all non-printing chars -s suppress |
| less | Text | core | Interactively page through file content | -N show line numbers -S disable line wrapping -i case-intensive search -F exit if content points one screen |
| head | Text | core | Output the first | -n number of lines (default 10) -c of -q suppress filename heads |
| tail | Text | core | Output the last N lines of a file | -n number of lines (default 10) -f below file for new content -c of -q suppress filename heads |
| grep | Text | core | Search text using shelters and regular expressions | -i case-intensive match -r resource directory search -n prefix output with line number -v invert match (exclude patch) - E use extended regex (ERE) -P use Perl-compable regex -l print matching files only -c count -A/-B lines of context after/ before |
| sed | Text | core | Stream editor - filter and transform text in-place or piped | -i edit files in-place -n toppress output -e add script expression -r use extended regex s/old/new/g substitute panttern |
| awk | Text | core | Pattern scanning and structured text processing | -F set field separator -v signal variable before run -f read program from file NR current record number $1..$N access fields |
| sort | Text | core | Short lines of text files | -n numeric short -r reverse short order -u output unique lines only -k short by key/field -t set field decimalr -h human-numeric assortment (1K, 2M) |
| cut | Text | core | Remove sections from each line of input | -d set field decimalr -f select field numbers -c select character position -b select byte positions |
| wc | Text | core | Count lines, words, and bytes in files | -l count lines only -w count words only -c count -m count characters |
| diff | Text | core | Compare files line by line and show differences | -u unified diff format -r company directories pursuant to article 4 (1) of directive 2013/34/eu -i ignore case differences -w ignore all whitespace |
| tr | Text | core | Translate or delta characters from input | -d member of the commission -s squeeze reproduced characters -c complement the character set |
| bat | Text | modern | cat replacement with syntax highlighting and git makers | --style header, grid, numbers, changes --language yield -n show line numbers --diff show only changed lines --pager override pager |
| ripgrep (rg) | Text | modern | Extremely fast grep - respects .gitignore by default | -i case-intensive -n show line numbers -l list matching files only --type filter -A/-B lines of context --hidden include hidden files --no-ignore override .gitignore |
| jq | Text | modern | JSON processor - slice, filter, map, and transform | 'key' extract object field '.[]' -r raw string output (from quotes) --arg pass 'select' () 'conditional filter 'keys' list all keys of object |
| ps | Processes | core | Report a snapshot of current running processes | -e show all processes -f full-format lighting aux BSD-style all processes --forest show process -o custom output format |
| top | Processes | core | Interactive real-time process and resource monitor | -d update -u filter by username -n number -b match (non-inactive) mode kill process |
| htop | Processes | modern | Enhanced interactive process viewer with tree view and meters | -u filter by user -p watch specific PIDs -d left --no- force F5 toggle tree view F9 send signal to process |
| kill | Processes | core | Send a signal to a process by PID | -9 SIGKILL - force terminate immediately -15 SIGTERM - graceful shutdown (default) -1 SIGHUP - reload configuration -l list all available signals |
| killall | Processes | core | Send a signal to all processes | -9 force kill -15 graceful terminate -i interactive firm -u only processes of user -v verbose output |
| nice | Processes | core | Launch a command with adjusted CPU scheduling priority | -n naeneness value from -20 (highest) to 19 |
| renice | Processes | core | Change the priority of a running process | -n new nieneness value -p apply to PID -u apply to all processes of user -g apply to process group |
| nohup | Processes | core | Run command IMmune to terminal hangup (SIGHUP) | nohup cmd output goes to nohup.out by default |
| strace | Processes | modern | Track system calls and signals made by a process | -p attach to running PID -e %1 -o write output to file -f follow child processes (fork) -c print sum -T show |
| lsof | Processes | modern | List open files, network pockets, and device hands | -p list files for PID -u list files for user -i wool -t output PIDs only for scripting lsof /path what has this file open |
| systemctl | System | core | Control and query the system service manager | start / stop / restart manage service state enable / disable set boot behavior list-units --type=service all services daemon-reload reload unit files is-active / is-enabled check state |
| journalctl | System | core | Query and display systemd journal window | -u %1 -f continue log in real time -n show last N lines --since / --until time range -p filter by priority level (err, warm...) -o json structured JSON output --disk-usage show journeynal size |
| uname | System | core | Print system body and OS information | -a print all information -r kernel release version -m machine hardware architecture -n network hostname -s kernel |
| uptime | System | core | Show how long the system has been running | -p pretty human-readable format -s show |
| dmesg | System | core | Print or control the kernel ring buffer message log | -T human-readable timesteps -l filter by log level -f filter by facility --follow live stream new messages -H colored human output |
| sysctl | System | modern | Read and modify the parameters at runtime | -a list all current parameters -w write param=value -p load settings from file (default /etc/sysctl.conf) net.ipv4.ip forward=1 enable routing |
| timedatectl | System | modern | Query and change system block, timezone, and NTP | status st. Petersburg set-time 'YYYY-MM-DD HH:MM:SS' set-ntp true enabled NTP sync |
| env / export | System | core | Display, set, or export environment variable | export VAR=value set and export env list all current variations printenv Var print specific variable unset Var remove variable env -i cmd run with empirical environment |
| crontab | System | core | Schedule return tasks via the cron daemon | -e edit current user's crontab -l list current user's crontab -r remove current user's crontab -u user operated on another user's crontab format: min hr dom mon dow command |
| git | System | modern | Distributed version control - track and collaborate on code | status log-oneline--graph compact history diff HEAD changes since last committee stash push/pop hatche and restore changes rebase -i interactive squash/reorderer bisect start/good/bad find bug committee blame show line-by-line authority |
| ansible | System | modern | Agent IT automation and configuration management | -i record file path --check dry-run (from changes) -v / -vvv verbosity level --tag run only tagged task --limit restrict to host subject --vault-id decrypt vault secrets -m specific module for ad-hoc task |
| terraform | System | modern | Infrastructure as Code - provision cloud and on-prem resources | init initialize working directory plan preview changes apply only changes to infra destroy ear down resources state list show tracked resources importbring existing resource under management |
| chmod | Rights | core | Change file fashion bits | -R only monthly u/g/o/a user/group/other/all +/-/= add/ remove/set exactly 755 rwxr-xr-x common executable 644 rw-r--r--common file chmod +x make available |
| chown | Rights | core | Change file owner and/or group ownership | -R resource -v verbose, print each file user:group change both owner and group --from=user change only if current owner matches |
| chgrp | Rights | core | Change the group ownership of files | -R resource -v verbose output -h changes |
| sudo | Rights | core | Executive a command as root or another user | -u user run as specified user -i start root login shell -l list lowered communities -s run shell as target user -v validate and extend timestep -k invalidate cached credentials |
| umask | Rights | core | Set the default permission mask for new files | 022 files 644, dirs 755 027 files 640, dirs 750 (stracter) -S display -p print as umask command for reuse |
| getfacl / setfacl | Rights | modern | Get and set POSIX Access Control Lists on files | -m modification or add ACL entry -x remove specific ACL entry -R only monthly -b remove all extended ACL entities -d set default ACL (for new files in dir) getfacel display all ACL entities |
| auditctl | Rights | modern | Configure the Linux Audit subsystem with watch rules | -w add filesystem watch on path -p permission filter: r w x a -l list all current rules -D delete all audit rules asearch -f search window by file information general audit reports |
| passwd | Rights | core | Change User Password and manage account blocks | -l lock user account -u unlock user account -e force -d delete password --stdin read password from stdin (RHEL) |
| ip | Network | core | Manage network interfaces, addresses, routes, and ARPs | add show display all IP addresses addr add/del add/remove address route show display selectable link set up/downbring interface up or down next show display ARP table rule list show policy setting rules |
| ss | Network | core | Socket statistics - modern replacement for netstat | -t TCP pockets -u UDP pockets -l litering pockets only -n numeric (no hostname resolution) -p show process using pocket -s print summary statistics -4/-6 IPv4 or IPv6 only |
| ping | Network | core | Test network host reachability using ICMP echo | -c number of packages -i interval between packages -t set IP TTL value -s package payload size -W time |
| traceroute | Network | core | Track the network path packages take to a host | -n numeric output, skip DNS lookup -m set maximum TTL (hops) -w wait timeout per probe -I use ICMP echo requests -T use TCP SYN package |
| dig | Network | core | DNA query tool - lookup and troubleshoot records | + +trace follow full delegation chain server ANY request all record types AAAA request IPv6 address record + |
| nslookup | Network | core | Interactive and non-interactive DNA lookup | nslookup domain basic lookup nslookup domain server set type=MX change queue type |
| ssh | Network | core | Secure Shell - remote login, execution, and tunneling | -i identity (private key) file -p remote port number -L local port forwarding -R remote port forwarding -J jump -N do not execute remote command -X enabled X11 forwarding -v verbose debug output |
| nftables (nft) | Network | modern | Modern kernel package filtering - replicates iptables | list ruleset show all rules add table ip create table add chain add chain to table add roule append filtering roule flush rouleset delete all rules -f file load from rule file |
| iptables | Network | core | Kernel IPv4 package filtering and NAT firewall | -A append rules to chain -D delete specific rule -L list chain rules -F flush / clear chain -P set default chain policy -j jump to target: ACCEPT DROP REJECT |
| firewall-cmd | Network | modern | Management tool for fuel (used on RHEL/CentOS/Rocky) | --list-all show zone config --add-port=80/tcp open port --add-service=https all service --remove-port close port --permanent persimmon --reload apply permanent rules |
| curl | Transmission | core | Transfer data over HTTP, HTTPS, FTP, and many other protons | -o write output to file -X specific HTTP method (GET POST PUT...) -H add custom request header -d send POST body data -L follow 3xx redirects -k skip TLS certificate verification --retry N rtry on transient file --compressed request and handle gzip --data-binary send raw binary data -u user:pass HTTP basic authentication --form send multipart/form-data -s silent mode (from progress bar) |
| wget | Transmission | core | Non-interactive network file downloader | -r resource download -O save to specified filename -q quiet mode -c continue interrupted download -P set local directory prefix --spider check URL without downloading --limit-rate third download speed --user / --password authentication |
| scp | Transmission | core | Securely copy files between hosts over SSH | -r resource copy of directories -P specific remote port -i identity (private key) file -p prevent timesteps and fashion -v verbose debug output |
| sftp | Transmission | core | Interactive secure file transfer over SSH | -P specify port -i identity file get / put download / upload file ls / lls list remote / local files mget / mput match transfer |
| tcpdump | Monitoring | modern | Capture and analysis raw network traffic packages | -i specific interface -w write package to pcap file -r read from pcap file -n no hostname/port resolution host X filter by IP address port -A print payload in ASCII -c N receipt N packages 'tcp and port 443' BPF filter example |
| nethogs | Monitoring | modern | Per-process real-time network bandwideth monitor | -d refresh -t run in track (non-interactive) mode -p enabled promiscuous fashion device specific interface to monitor |
| iftop | Monitoring | modern | Display real-time band | -i network interface to choose on -n suppress DNA hostname lookups -P show port numbers -B display |
| iostat | Monitoring | modern | Report CPU utilisation and I/O statistics for devices | -x extended device statistics -d display device I/O only -c display CPU statistics only -k display stats -m display stats intercount |
| vmstat | Monitoring | modern | Report virtual memory, CPU, and disk I/O statistics | -s display memory statistics table -d display disk statistics -w side output format intercount periodic sampling |
| sar | Monitoring | modern | Collection, report, and save system activity data | -u CPU utilisation -r memory statistics -n DEV network interface status -d disk activity -f read from data file -s specify start time 1 5 single every second, 5 times |
| glances | Monitoring | modern | Cross-platform courses system monitor with export plugins | -w start as web server --port web server port -1 per-CPU core display -t refresh interval --export csv/json output data --browser discover remote glosses |
| netstat | Monitoring | core | Network statistics - legacy tool | -t TCP connections -u UDP pockets -l lighting port only -n numeric IPs and port -p show program using pocket -r show selectable |
| df | Discs | core | Report file system disk space usage | -h human-readable seed -T show filesystem type -i show -a include all files -x exclude filesystem type |
| du | Discs | core | Estimate file and directory space on disk | -h human-readable output -s display summary total only -a report for all files -d N limit depth to N level --exclude skip matching pattern du -sh ./* size of each item in CWD |
| lsblk | Discs | core | List block devices and parts in tree format | -a show all including empirical devices -f show filesystem and UUID -o specialy output lumps -d do not show device children -p print full device path |
| fdisk | Discs | core | Manipulate MBR partition tables interactively | -l list all partition tablets -u %1 zettameters p print table n new d delete w write and exit q quit no save |
| parted | Discs | core | Partition manipulation - support GPT and large disc | -l list all disks and parts mkpart create new partition resizepart resize existing partition print show partition table rm N remove partition N |
| mount / umount | Discs | core | Attach or detailed filesystems to the directory tree | -t specific filesystem type -o mount options (rw, ro, noexec...) -a mount all entities in /etc/fstab -r mount as read-only --bind %1 umount -l lazy unmount |
| lvm (pvs/vgs/lvs) | Discs | modern | Logical Volume Manager | pvcreate initialize physical volume vgcreate create volume group lvcreate -L -n created logical volume lvextend -L +size grow EN lvreduce -L-size shrimp vgdisplay / endisplay inspect |
| smartctl | Discs | modern | Monitor disc health using S.M.A.R.T. diagnostics | -a print all SMART information -H check health summation only -t short/long run self-test -l selftest view test results --scan find all SMART-capable drives |
| tar | core | Create and extract archives; compose with compressors | -c create new archive -x extract archive contents -z filter through gzip (.tar.gz) -j filter through bzip2 (.tar.bz2) --zstd filter through zstd (.tar.zst) -v verbose - list files processed -f specify archive filename -t list archive contents without extract --strip-compponents N strip N path level |
|
| gzip / gunzip | core | Compass or decompress files in .gz format | -d decompress file -k keep original file -v verbose output -9 maximum compression level -1 fascest compression -l list compression statistics |
|
| zip / unzip | core | Create or extract ZIP archives | zip -r returnive add directory -e insert with password -9 maximum compression unzip -l list archive contents unzip -d dir extract to directory -v verbose listing |
|
| zstd | modern | Fast modern compression - high speed at good ratios | -d decompress file -k keep original -T0 use all CPU threes -19 high compression level --fast a.k.a --progress show progress during compress |
|
| nmap | Intrusion test | security | Network Scanner - host discovery, port scan, service detection | -sV detect service versions -sC run default NSE scripts -O enable OS fingerprinting -p specific port range (e.g. 1-65535) -A aggressive: OS+version+scripts+traceroute --script nSE Script -oN / -oX output to file (normal/XML) -Pn slip host discovery (size up) -sS TCP SYN stealth scan |
| netcat (nc) | Intrusion test | security | TCP/UDP multipurpose tool - banner grab, file pipe, reverse shell | -l listen mode (server side) -v verbose output -z zero-I/O scan mode (port check) -u use UDP -e execute command on connect -p specific source port nc -lvnp 4444 listener for reverse shell |
| openssl | Intrusion test | security | TLS/SSL toolkit - certificates, keys, entry, and testing | s client -connect host:443 test TLS x509 -in cert.pem -text inspect cert genrsa -out key.pem 4096 generate RSA key req -new generation CSR enc -aes-256-cbc encrypt/decrypt file verify -CAfile validate certificate chain speed benchmark cipher performance |
| ssh-keygen | Intrusion test | security | Generation, management, and convert SSH authentication keys | -t ed25519 modern key type (recommended) -b 4096 key bit length (for RWA) -C 'comment' add identifying comment -f exit file path -p change or remove -l print -A generate all default host key types |
| gpg | Intrusion test | security | GNU Privacy Guard - encrypt, decrypt, sign, and verify data | --gen-key generic new key pair -e -r recipient encrypt file --decrypt decrypt .gpg file -s create detailed signature --verify verify signature file --armo output in ASCII armor format --export / --import key management |
| lynis | Intrusion test | security | Security auditing tool - scan and harden Linux systems | audit system run full system audit --test-from-group auth focus on group --quiet volume --no-colors played --pentest pentest-oriented mode --report-file write report to file |
| fail2ban-client | Intrusion test | security | Manage file2ban - auto-ban IPs on reviewed files | status status set sshd unbanip IP manually unban reload removal configuration start / stop control service banned list currently banned IPs |
| hashcat | Intrusion test | security | GPU-qualified password hash cracking tool | -m hash type (0=MD5, 1800=sha512crypt) -a image mode (0=dict, 3=bruteforce) -w workload profile (12.2006,4) -r apply roules file --show show already cracked hashes --status live progress update |
| john (JtR) | Intrusion test | security | CPU-based password hash cracker with auto-detection | --wordlist dictionary file path --rolls apply mangling rules --format specific hash type --show display cracked passwords --fork N run N parallel processes unshadow merge passwd and shadow |
| docker | Containers | modern | Build, ship, and run application containers | run -d run container detached run --rm auto-remove on exit exec -it open shell in running container window -f follow container log stream inspect detailed JSON metadata ps -a list all holders (including stopped) building -t building image with tag network ls / inspection management networks volume ls/inspect manage volumes system usage |
| kubectl | Containers | modern | CLI to manage Cubanetes clusters and jobs | get pot/svc/nodes list resources describe pod applicable -f manifest.yaml employment/update resource exec -it pod -- bash shell into pod window -f pod follow pod log stream top node / top pod resource use rollout status/undo employment control port-ward forward local port to pod config use-text |
| podman | Containers | modern | Rootless daemonless OCI contains engine - docker-compatible | run --rm auto-remove after exit --user 1000 run as non-root UID --pod attach to pod group -v single mount host volume generale kube export as Kubernetes Yaml play kube run from Cubanettes YAML pod creation / start / stop manage pot |
| helm | Containers | modern | Cubanettes package manager for tempered chart employments | install release upgrade --install upsert employment rollback release list show all requested releases value repo add / update management chart repos template tender manifests locally |
System audit
The checks are grouped by the auditor's questions: what happened, who has access, what starts by itself, what is exposed to the network, whether files are intact and whether the configuration matches recommendations. All commands only read and change nothing. Some need root privileges (sudo). Save the output as a baseline - in the next audit, changes against it stand out more than the values themselves.
How an audit runs from planning to the report is explained in the security audit guide.
Logs and sign-ins
-
Failed SSH logins
sudo journalctl --since "24 hours ago" | grep -Ei "failed password|invalid user"sudo grep -Ei "failed password|invalid user" /var/log/auth.logWhat to look for: Many attempts from one address are password guessing. Attempts with real usernames are more dangerous than random ones, and a successful login right after a series of failures must be investigated. On the RHEL family the log file is /var/log/secure.
-
Who logged in, when and from where
last -a | head -30sudo lastb -a | head -30What to look for: Logins at unusual hours, from unknown addresses or to accounts that should not log in. The second command shows failed attempts. On Debian 13 and newer distributions, last is replaced by wtmpdb last.
-
What was run with root privileges
sudo journalctl _COMM=sudo --since "7 days ago"What to look for: Lines with COMMAND= show which user ran what. Suspicious: sudo from an account that does not need it, opening a shell (sudo -i, sudo su, sudo bash) and commands from /tmp.
-
Errors and reboots
sudo journalctl -p err -bsudo journalctl --list-bootsWhat to look for: Recurring service errors and reboots that nobody planned. An unexpected reboot can mean a crash or tampering.
-
Whether logs were deleted or damaged
sudo journalctl --verifysudo ls -la /var/logWhat to look for: The first command reports damaged journal files. Empty or suddenly truncated log files and a gap in the timeline suggest that someone is covering their tracks.
-
Audit subsystem (auditd)
sudo aureport --summarysudo ausearch -m USER_LOGIN -sv no -ts today -iWhat to look for: The summary shows event counts by type, ausearch shows today's failed logins. If auditd is not installed, that is a finding in itself: without it there is no record of who changed files and permissions. Watch rules are set with auditctl (in the command table).
Accounts and privileges
-
Accounts with root privileges (UID 0)
awk -F: '$3 == 0 {print $1}' /etc/passwdWhat to look for: There must be only root. Any other account with UID 0 is a full administrator under another name.
-
Accounts that can log in
awk -F: '$7 !~ /(nologin|false)$/ {print $1, $7}' /etc/passwdWhat to look for: Service accounts (www-data, postgres, etc.) do not need a shell. Every account on the list should belong to someone who actually works on this system.
-
Accounts without a password and password expiry
sudo awk -F: '$2 == "" {print $1}' /etc/shadowsudo chage -l <lietotājs>What to look for: An empty password field means login without a password. The chage command shows when the password was changed and whether the account expires.
-
Who has sudo rights
getent group sudo wheelsudo grep -rEv '^\s*(#|$)' /etc/sudoers /etc/sudoers.d/What to look for: Look for NOPASSWD and ALL=(ALL) ALL on accounts that do not need full privileges. A file in sudoers.d that nobody remembers adding is suspicious.
-
SSH keys
sudo find /root /home -name authorized_keys -type f -exec ls -l {} +What to look for: Every key allows login without a password. An unknown key or a recently changed file is one of the most common persistence methods (MITRE ATT&CK T1098.004). Review the file contents too.
Autostart and scheduled tasks
-
Services that start automatically
systemctl list-unit-files --type=service --state=enabledsystemctl cat <serviss>What to look for: Every service should have a known purpose. An unknown name or an ExecStart pointing to /tmp, /dev/shm or a user directory must be investigated.
-
Recently changed service files
sudo find /etc/systemd /usr/lib/systemd -type f -mtime -30What to look for: Files changed in the last 30 days that match neither an update nor your own changes.
-
Scheduled tasks (cron and timers)
systemctl list-timers --allls -la /etc/cron.d /etc/cron.daily /etc/cron.hourlyfor u in $(cut -d: -f1 /etc/passwd); do sudo crontab -l -u "$u" 2>/dev/null | sed "s/^/$u: /"; doneWhat to look for: Tasks that download and run code (curl, wget, base64) and user crontab entries that nobody scheduled.
Services
-
Running services
systemctl list-units --type=service --state=running --no-pagerWhat to look for: Every service should have a known purpose and owner. A service nobody can explain is unnecessary attack surface - record it in the report and agree on disabling it with the system owner.
-
Failed services
systemctl --failed --no-pagersystemctl is-system-runningWhat to look for: The answer degraded means at least one service failed to start. A failed security service (firewall, logging, backups) is a finding even if the system otherwise works.
-
One service's state and log
systemctl status <serviss> --no-pagersudo journalctl -u <serviss> --since "24 hours ago" --no-pagerWhat to look for: Whether the service is enabled and active, how often it restarted and what errors it logs. Frequent restarts hide a crash users have not noticed yet.
-
Which service holds a port
sudo ss -tlpn 'sport = :<ports>'systemctl status <PID> --no-pagerWhat to look for: The first command gives the process PID, the second the service it belongs to. A port with no service (a process started by hand or from cron) must be explained.
-
Service sandboxing
systemd-analyze security --no-pagersystemd-analyze security <serviss> --no-pagerWhat to look for: A score from 0 (sandboxed) to 10 (no restrictions). For a network service rated UNSAFE, recommend restrictions such as NoNewPrivileges and ProtectSystem. It is a recommendation, not an error.
Network exposure
-
Listening ports
sudo ss -tulpnWhat to look for: Every port should belong to a known service. Address 0.0.0.0 or [::] means the service is reachable from the network. A database or an admin panel should usually listen on 127.0.0.1 only.
-
Established connections
sudo ss -tnp state establishedWhat to look for: Connections to unknown external addresses, especially from processes that have no reason to talk to the internet.
-
Firewall rules
sudo nft list rulesetsudo iptables -SWhat to look for: The default policy for incoming traffic should be drop or deny. A rule that allows everything without restriction overrides the rest.
-
The ufw firewall and open ports
sudo ufw status verbosesudo ufw status numberedsudo ufw show listeningWhat to look for: The first line says whether ufw is active at all, and the default for incoming should be deny. show listening puts the listening ports next to the rules: a port without an allow rule is not reachable from the network, and a rule without a service is unnecessary.
-
Ports published by containers
docker ps --format 'table {{.Names}}\t{{.Ports}}'sudo iptables -S DOCKER-USERWhat to look for: Docker forwards published ports before the ufw rules, so ufw status neither shows nor blocks them. 0.0.0.0:5432->5432 means the database is open to the network regardless of ufw. Restrictions for containers belong in the DOCKER-USER chain.
Integrity and updates
-
SUID and SGID files
sudo find / -xdev -type f \( -perm -4000 -o -perm -2000 \) 2>/dev/nullWhat to look for: These files run with the owner's (often root's) privileges. Compare with the previous list. A new file, or one in /tmp, /home or /dev/shm, is a privilege escalation path.
-
World-writable files
sudo find / -xdev -type f -perm -0002 2>/dev/nullWhat to look for: There must be none in system directories (/etc, /usr, /opt). If anyone can change a script that root runs, that is a direct path to full privileges.
-
Integrity of installed packages
sudo dpkg --verifysudo rpm -VaWhat to look for: A 5 in the third position (??5??????) means the file content differs from the package. That is normal for configuration files (marked c), not for executables in /usr/bin and /usr/sbin. The first command is for Debian and Ubuntu, the second for the RHEL family.
-
Recently changed system files
sudo find /etc /usr/bin /usr/sbin -xdev -type f -mtime -2What to look for: Changes in the last 2 days that match neither an update nor your own changes.
-
Pending security updates
apt list --upgradablesudo dnf updateinfo list --securityWhat to look for: A missing security fix is a known vulnerability with a public description. Also check when the system was last updated.
Configuration
-
Effective SSH server settings
sudo sshd -T | grep -Ei "^(permitrootlogin|passwordauthentication|pubkeyauthentication|maxauthtries|x11forwarding) "What to look for: The sshd -T command shows the configuration in effect after all included files. Recommended: permitrootlogin no (or prohibit-password) and passwordauthentication no when logging in with keys.
-
Kernel security parameters
sysctl kernel.randomize_va_space kernel.kptr_restrict net.ipv4.ip_forward net.ipv4.conf.all.accept_redirectsWhat to look for: The value of randomize_va_space should be 2 (full address space randomisation), kptr_restrict 1 or 2 hides kernel addresses, and accept_redirects 0 protects against route rewriting. Setting ip_forward to 1 is only appropriate on a router or a container host.
-
Automated security audit
sudo lynis audit systemWhat to look for: Lynis checks hundreds of settings and gives a hardening index with specific recommendations. The full report is in /var/log/lynis-report.dat.
Troubleshooting
Start with two questions: what changed, and does the problem affect one user or everyone. Then work up the layers from the bottom - interface and address, route, DNS and only then the service. The commands only read the state, the note says what to change.
Network
-
Is the interface up and does it have an address
ip -br linkip -br addressnmcli device statusWhat to do: State DOWN means there is no link - cable, Wi-Fi or switch port. Only a 169.254.x.x address or no IPv4 address at all means DHCP did not answer.
-
Route and gateway
ip routeip route get <mērķa IP>ip neigh showWhat to do: Without a default line the machine reaches only its own subnet. ip route get shows which interface and gateway a given target uses - a VPN often changes it. A gateway in state FAILED or INCOMPLETE does not answer ARP, so the problem is on the local network.
-
Where the path breaks
ping -c 4 <vārteja>ping -c 4 1.1.1.1tracepath -n <mērķis>What to do: The gateway answers but an outside address does not - the problem is beyond the router. A silent ping does not yet mean the target is down. Many servers block ICMP, so test the port itself.
-
Is the port reachable
nc -zv -w 5 <mērķis> 443curl -sv -o /dev/null https://<mērķis>env | grep -i proxyWhat to do: Connection refused means the target answered but nothing listens on the port or a firewall rejects the connection. A timeout means packets are silently dropped somewhere on the way. curl also shows TLS errors, and the proxy variables show whether the command line goes through a proxy. That is often where a browser and a script differ.
-
Large packets get stuck (MTU)
ping -c 3 -M do -s 1472 <mērķis>ip link show | grep -o 'mtu [0-9]*'What to do: The classic symptom - the connection opens and small pages load, but large downloads or the TLS handshake hang, especially over a VPN or PPPoE. If a 1472-byte packet returns Message too long or gets no reply, lower -s until you find the path MTU.
DNS
-
Which DNS server is in use
resolvectl statuscat /etc/resolv.confWhat to do: If the server is wrong or unreachable, domains are not found even though the network works. With systemd-resolved resolv.conf points to 127.0.0.53, and the real servers - including those a VPN interface adds - appear in the resolvectl output.
-
What the DNS server answers
dig <domēns>dig @1.1.1.1 <domēns>resolvectl query <domēns>What to do: Look at the status line: NXDOMAIN - the domain does not exist, SERVFAIL - the server could not answer (often DNSSEC or an upstream failure), NOERROR without an ANSWER section - no record of that type. If the public server answers but the local one does not, the fault is in local DNS. A public server does not know internal domains, so a difference there is normal. dig comes in the dnsutils or bind-utils package.
-
What programs see
getent hosts <domēns>grep -v '^#' /etc/hostsgrep '^hosts' /etc/nsswitch.confWhat to do: getent follows the same path as programs - the hosts file and DNS in the order nsswitch.conf sets. If dig answers correctly but getent does not, the fault is in the hosts file or the cache. A stale line in the hosts file is a common forgotten mistake, resolvectl flush-caches clears the cache.
Services
-
State and exit code
systemctl status <serviss> --no-pagersystemctl --failed --no-pagerWhat to do: The Main PID line shows the exit code, below it the last log lines. status=203/EXEC means the executable was not found, 217/USER that the given user does not exist.
-
The log since boot
journalctl -u <serviss> -b --no-pagerjournalctl -u <serviss> -p err --since today --no-pagerWhat to do: Read the first error, not the last - the last ones are often consequences. Permission denied points to permissions or SELinux, Address already in use to a port that is taken.
-
Is the configuration valid
systemctl cat <serviss>systemd-analyze verify <serviss>.servicesudo sshd -tsudo nginx -tWhat to do: Most services have their own check that changes nothing (sshd -t, nginx -t, apachectl configtest, named-checkconf). Run it before a restart, otherwise a broken configuration stops a working service.
-
What already holds the port
sudo ss -tlpn 'sport = :<ports>'What to do: If another process holds the port, one of them must be reconfigured or stopped. Often it is an old instance of the same service or another web server.
Disk and file system
-
Is the disk full
df -hdf -iWhat to do: A full disk stops databases and logs. df -i shows inodes - once they run out, no new files can be created even with free space left (millions of small files, such as sessions or a cache).
-
What takes up the space
sudo du -xh --max-depth=1 / 2>/dev/null | sort -h | tail -15journalctl --disk-usagedocker system dfWhat to do: Common culprits: logs, old backups, Docker images. Clean up with the tool's own command (journalctl --vacuum-time, docker image prune), not with rm.
-
df shows full but du cannot find the space
sudo lsof +L1What to do: A deleted file that a process still holds open keeps taking space until the process closes it - typically a deleted log. lsof +L1 names the process, and the space is freed when it restarts.
-
Are the disk and file system healthy
findmnt -no OPTIONS /findmnt --verifysudo dmesg -T | grep -iE 'i/o error|ext4-fs error|xfs.*error' | tailsudo smartctl -H /dev/<disks>What to do: I/O errors in the kernel log or a SMART result other than PASSED are a sign of disk damage - back up first, then replace. After errors the kernel may switch the file system to read-only (ro in the options). findmnt --verify finds errors in the fstab file.
Performance
-
What loads the CPU
nprocuptimetop -b -n 1 | head -20What to do: A load average that stays above the core count (nproc) means a queue. Linux also counts processes waiting for the disk (state D), so a high load with low CPU is usually a disk problem, not a CPU one.
-
Has memory run out
free -hps aux --sort=-%mem | head -10sudo journalctl -k --no-pager | grep -i 'out of memory' | tailWhat to do: The available column matters, not free - Linux uses spare memory for cache. Low available memory with active swap makes the system slow, and the OOM killer in the log names the process the kernel stopped.
-
Is the system waiting for the disk
vmstat 1 5cat /proc/pressure/ioiostat -xz 1 3What to do: A high wa column in vmstat output means the CPU waits for the disk. iostat (sysstat package) shows which disk - %util near 100 and a high await point to a bottleneck. iotop shows which process writes.
Boot and updates
-
Errors in the previous and current boot
journalctl --list-boots --no-pager | tail -5journalctl -b -1 -p err --no-pagerjournalctl -b -p err --no-pagerWhat to do: The previous boot log (-b -1) shows what happened before a crash or reboot. It needs a persistent journal - if --list-boots shows only one entry, create the /var/log/journal folder.
-
Kernel and hardware errors
sudo dmesg -T --level=err,warn | tail -30What to do: Driver and hardware errors appear here earlier than in application logs. After a kernel update, booting the previous kernel from the GRUB menu may help.
-
What slows down boot
systemd-analyze blame --no-pager | head -15systemd-analyze critical-chain --no-pagerWhat to do: A service waiting for the network or a missing disk can hold up the whole start. A common culprit is an fstab entry for a disk that is gone - without the nofail option the system waits 90 seconds and may drop into emergency mode.
-
What changed in the last update
grep -E ' (install|upgrade) ' /var/log/dpkg.log | tail -20dnf history list | headcat /var/run/reboot-requiredWhat to do: If the problem began after an update, this list narrows down the culprit. The reboot-required file means the new kernel or libraries are not loaded yet. Roll back with the package manager (dnf history undo, apt with a specific older version).
Access and time
-
Why Permission denied
namei -l <ceļš>id <lietotājs>What to do: namei shows permissions for every step of the path - often a folder higher up blocks, not the file itself. id shows the user's groups, and a new group takes effect only after signing in again.
-
SELinux or AppArmor denial
getenforcesudo ausearch -m AVC -ts recentsudo aa-statussudo journalctl -k --no-pager | grep -i 'apparmor="denied"'What to do: If permissions look right but access is denied, SELinux or AppArmor may be doing it - the denial shows in the audit or kernel log. Do not disable the module - adjust the policy or the file context (restorecon).
-
Why SSH sign-in fails
ssh -v <lietotājs>@<serveris>sudo journalctl -u ssh -u sshd --since '1 hour ago' --no-pagerls -ld ~ ~/.ssh ~/.ssh/authorized_keysWhat to do: The client's -v output shows at which step the server refused - key, password or algorithm. Authentication refused: bad ownership or modes in the server log means permissions are too wide - others must not have write access to the home folder and .ssh, and authorized_keys must be 600.
-
Is the time correct
timedatectlchronyc trackingWhat to do: Wrong time breaks TLS (certificate not yet valid), Kerberos and 2FA codes. The System clock synchronized line should say yes.
Penetration testing
Penetration testing checks defences from an attacker's point of view. The section follows the stages: reconnaissance, web surface, TLS, passwords and availability resilience. Every entry carries its defence alongside - a penetration test is only worth doing if the findings get fixed. The tools usually run from the tester's machine (often Kali Linux), so they are the same for both systems.
The attack surface and how to reduce it is explained in the attack surface guide.
This section is for educational purposes. Use these methods ONLY against systems you own or have written permission to test. Unauthorised scanning and testing is a criminal offence. Replace <target> with your own test system.
Reconnaissance and port scanning
-
Host and open-port discovery
nmap -sn 10.0.0.0/24nmap -sV -p- <mērķis>Defence: Every open port is an entry point. Close unused services, bind management and databases to 127.0.0.1, and put anything exposed to the internet behind a firewall. The same view is in the network area of the system audit.
-
Service and version detection
nmap -sV --script=banner <mērķis>whatweb <url>Defence: A version tells the attacker which public vulnerability to look up. Remove version-revealing headers (Server, X-Powered-By) and keep services patched.
-
DNS and zone transfer
dig AXFR @<ns> <domēns>dnsrecon -d <domēns>Defence: An open zone transfer hands over the entire internal name list. Deny AXFR to unauthorised peers and keep internal hosts out of public DNS.
Web applications
-
Scanning for known vulnerabilities
nuclei -u <url>nikto -h <url>Defence: Scanners look for publicly known vulnerabilities and misconfiguration. Defence: a web application firewall (WAF) in front, input validation on the server, and regular patching.
-
Probing for hidden files and paths
ffuf -w <wordlist> -u <url>/FUZZgobuster dir -u <url> -w <wordlist>Defence: The attacker tries to find .env, .git and backups. Never put secrets under the webroot, and reject these paths at the web server edge before they reach the application.
-
Intercepting proxy (Burp, ZAP)
# Burp Suite / OWASP ZAP - manuāla pieprasījumu pārtveršanazap-baseline.py -t <url>Defence: An intercepting proxy shows that client-side checks can be bypassed. Enforce every gate on the SERVER, not only in the browser, and use CSRF tokens and ownership checks.
TLS and encryption
-
TLS configuration check
testssl.sh <host>:443sslscan <host>Defence: Disable protocols below TLS 1.2 and weak ciphers, enable HSTS. An obsolete protocol is a slow but sure path to a man-in-the-middle attack.
-
Certificate check
openssl s_client -connect <host>:443 -servername <host>Defence: Check that the certificate is valid, not expired and matches the domain. Automate renewal so it does not expire silently.
Password and hash auditing
-
Hash strength audit (on your own hashes)
hashcat -m <režīms> hashes.txt <wordlist>john --wordlist=<wordlist> hashes.txtDefence: Run it against YOUR OWN extracted hashes to see how fast weak passwords fall. Defence: a strong, slow hashing algorithm, sufficiently long passwords, and account lockout after failed attempts.
-
Login resilience against guessing
# autorizēts tests pret SAVU pieteikšanās galapunktunmap -p 80,443 --script http-brute <mērķis>Defence: Rate limiting and account lockout make direct guessing unprofitable. Against distributed guessing from many addresses you need a reputation layer that blocks addresses by their behaviour elsewhere.
Availability resilience (DoS)
-
Slow HTTP resilience (Slowloris class)
slowhttptest -c 500 -H -u <url>Defence: Slowloris holds connections open with slowly sent headers. Defence: request timeouts and a per-IP concurrent connection limit. Test ONLY your own test environment.
-
Load resilience
ab -n 10000 -c 100 <url># vai slodzes ģenerators (wrk, Locust) - TIKAI pret savu vidiDefence: Measure how many requests per second the system can take. Defence: a cache for anonymous pages and rate limits; save the measured baseline and compare after every change.