Linux Networking: The Hacker Guide
Feel like Mr. Robot. Network commands to discover IPs, open ports and diagnose connections like a CyberSec professional.
Sections6
🔍 Basic Diagnostics
15 snippetsFundamental commands for diagnosing connectivity issues, checking network interface configurations, and resolving DNS-related questions. Essential for quick identification of network infrastructure failures.
Test Connectivity with Ping
Tests network connectivity and the accessibility of a specific host by sending ICMP ECHO_REQUEST packets. The `-c 4` flag limits sending to 4 packets, providing a quick test without overloading the network.
ping -c 4 google.comFast Ping with Reduced Interval
Performs a connectivity test with a reduced interval between packets. The `-i 0.5` flag sets an interval of 0.5 seconds between each ping, useful for quick latency tests and to check real-time response.
ping -i 0.5 192.168.1.1Trace Route to Destination (Traceroute)
Displays the route that IP packets take to reach a destination, showing each router (hop) along the path. Helps identify bottlenecks, excessive latency, or failures at specific points in the network route.
traceroute google.comContinuous Traceroute (MTR)
Combines the functionalities of `ping` and `traceroute` into a continuous tool. It displays latency and packet loss statistics for each hop in real-time, ideal for prolonged monitoring and identifying intermittent issues.
mtr google.comDisplay ARP Table
Displays the system's ARP (Address Resolution Protocol) table, which maps IP addresses to MAC (physical) addresses on the local network. The `-a` flag shows all entries, useful for debugging layer 2 address resolution issues.
arp -aDisplay Interfaces and IP Addresses
Displays detailed information about all network interfaces configured on the system, including IP addresses, subnet masks, interface state (UP/DOWN), and scope. It is the modern tool to replace `ifconfig`.
ip addr showActivate Network Interface
Activates the `eth0` network interface. Replace `eth0` with the desired interface name (e.g., `enp0s3`, `wlan0`). Use `ip link set eth0 down` to deactivate it. Requires root privileges.
ip link set eth0 upInterface Details with Ethtool
Displays and allows configuration of low-level parameters for the `eth0` network interface, such as speed, duplex mode, auto-negotiation, and hardware statistics. Useful for checking the physical connection state.
ethtool eth0Network Interface Statistics
Shows concise traffic statistics (bytes sent/received, errors, dropped packets) for the `eth0` network interface. The `-s` flag displays a summary of packet and error statistics.
ip -s link show eth0List Open Ports (Sockets)
Displays information about open network sockets on the system. The flags `-t` (TCP), `-u` (UDP), `-l` (listening sockets), and `-n` (numeric, no name resolution) are commonly used to list ports awaiting connections.
ss -tulnDNS Query with Nslookup
Queries DNS servers for domain name information, such as IP addresses (A records) and other record types. It's an older tool but still useful for basic and quick DNS queries.
nslookup google.comComplete DNS Query with Dig
A more powerful and flexible tool for DNS queries. `ANY` requests all available DNS record types for the specified domain, including A, MX, NS, SOA, etc. Ideal for advanced DNS debugging.
dig google.com ANYTrace DNS Resolution Path
Traces the DNS resolution path for a domain, showing the root, TLD, and authoritative DNS servers queried at each step. Useful for understanding how a name is resolved globally and identifying delegation issues.
dig +trace google.comQuery MX Records with Host
Queries DNS servers for information about a domain. The `-t mx` flag specifically requests MX (Mail Exchanger) records, which indicate the email servers responsible for receiving messages for the domain.
host -t mx google.comSystemd-Resolved DNS Status
Displays the current status of the system's DNS resolver managed by `systemd-resolved`, including configured DNS servers, interfaces, and search domains. Relevant on systems using `systemd` for network management.
systemd-resolve --status📊 Traffic Analysis
16 snippetsCommands for capturing, filtering, and analyzing network packets, plus real-time traffic monitoring to identify patterns, anomalies, and performance issues.
Capturar Tráfego na Interface (tcpdump)
Captura e exibe o tráfego de rede passando pela interface `eth0` em tempo real. Requer privilégios de root. Use `Ctrl+C` para parar a captura. É uma ferramenta fundamental para inspeção de pacotes.
sudo tcpdump -i eth0Capture Traffic without DNS Resolution
Captures traffic on the `eth0` interface without resolving IP addresses to hostnames or port numbers to service names. The `-n` flag speeds up display and is useful in environments without DNS access or to focus only on IPs.
sudo tcpdump -i eth0 -nFilter Traffic by Port
Filters traffic on the `eth0` interface to show only packets using port 80 (usually HTTP). The filter can be applied to source or destination ports, facilitating the analysis of specific services.
sudo tcpdump -i eth0 port 80Filter Traffic by Specific Host
Captures only traffic originating from or destined for the IP address `192.168.1.100` on the `eth0` interface. Essential for isolating traffic from a single device or server.
sudo tcpdump -i eth0 host 192.168.1.100Save Capture to PCAP File
Captures traffic from the `eth0` interface and saves the raw packets to a file named `capture.pcap`. This file can later be analyzed with `tcpdump` or graphical tools like `Wireshark`.
sudo tcpdump -i eth0 -w capture.pcapRead PCAP File with ASCII Content
Reads and displays the content of a previously saved capture file (`.pcap`). The `-A` flag attempts to print each packet (excluding the link-layer header) in ASCII, useful for inspecting text data within packets.
sudo tcpdump -r capture.pcap -AReal-time Capture with Tshark
Starts real-time packet capture on the `eth0` interface using `tshark`, the command-line version of Wireshark. Offers more advanced filtering and analysis capabilities than `tcpdump`.
tshark -i eth0Analyze PCAP File with Tshark
Reads and displays the content of a capture file (`.pcap`) using `tshark`. Allows applying display filters and performing detailed analysis of recorded packets.
tshark -r capture.pcapFilter HTTP Requests in PCAP
Analyzes a `.pcap` file and displays only packets matching the Wireshark display filter `http.request`, showing captured HTTP requests in detail.
tshark -r capture.pcap -Y "http.request"Extract Source/Destination IPs from PCAP
Extracts and displays specific packet fields from a `.pcap` file. `-T fields` specifies the output format as fields, and `-e` lists the fields to be extracted (in this case, source and destination IP addresses).
tshark -r capture.pcap -T fields -e ip.src -e ip.dstIP Conversation Statistics with Tshark
Analyzes a `.pcap` file and generates IP conversation statistics. `-q` suppresses packet output, and `-z conv,ip` enables the IP conversation statistician, showing data and packet volume between IP pairs.
tshark -r capture.pcap -q -z conv,ipMonitor Real-time Traffic (iftop)
Displays real-time bandwidth usage for the `eth0` interface, showing connections consuming the most bandwidth, ordered by volume. Requires `sudo` and `iftop` installation.
iftop -i eth0Monitor Traffic by Process (nethogs)
Shows bandwidth consumption per process on the `eth0` interface. Useful for identifying which applications are generating the most network traffic in real-time. Requires `sudo` and `nethogs` installation.
nethogs eth0Graphical Bandwidth Monitor (bmon)
A bandwidth and network statistics monitor that offers a graphical and detailed view of traffic on all interfaces. Provides an interactive interface for visualizing network metrics. Requires `bmon` installation.
bmonDetailed Network Statistics (iptraf-ng)
An interactive network monitoring tool that collects and displays a variety of statistics, including IP, TCP, UDP, ICMP, Ethernet information, and more. Useful for in-depth traffic analysis. Requires `iptraf-ng` installation.
iptraf-ngNetwork Statistics with Sar
Collects, reports, or saves system activity information. `-n DEV` specifies the network statistics report per device, `1` is the interval in seconds, and `5` is the number of samples to collect. Part of the `sysstat` package.
sar -n DEV 1 5🔒 Firewall and Security
15 snippetsCommands for configuring and managing firewalls (UFW, iptables) and protecting the system against attacks with tools like Fail2Ban.
Enable UFW Firewall
Enables the UFW (Uncomplicated Firewall) firewall. Make sure to have SSH access rules configured before enabling it on remote servers to avoid blocking access. Requires root privileges.
sudo ufw enableDetailed UFW Status
Displays the current UFW status, showing if it's active, configured rules, default profile, and rule log. The `verbose` flag provides more details about rules and traffic.
sudo ufw status verboseAllow SSH Connection (UFW)
Creates a rule to allow TCP connections on port 22 (SSH). It is crucial to allow SSH before enabling the firewall on remote servers to maintain administrative access.
sudo ufw allow 22/tcpBlock Specific IP (UFW)
Creates a rule to block all incoming connections from the IP address `192.168.1.100`. Useful for mitigating attacks or blocking unwanted access from a known IP.
sudo ufw deny from 192.168.1.100Remove UFW Rule
Removes an existing rule that allows traffic on port 80. To remove a specific rule, you can use `ufw status numbered` to see the rules with numbers and then `ufw delete <number>`.
sudo ufw delete allow 80Reload UFW Rules
Reloads UFW rules after modifications, applying the new configurations without the need to restart the service. This ensures that changes take effect immediately.
sudo ufw reloadList Iptables Rules
Lists all `iptables` firewall rules. `-L` lists the rules, `-n` displays addresses and ports numerically (without DNS resolution for faster speed), and `-v` shows details like packet/byte counters.
sudo iptables -L -n -vAllow Specific Port (Iptables)
Adds (`-A`) a rule to the `INPUT` chain to allow (`-j ACCEPT`) TCP connections (`-p tcp`) destined for port 22 (`--dport 22`). This rule allows incoming SSH traffic.
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPTBlock Subnet (Iptables)
Adds a rule to the `INPUT` chain to drop (`-j DROP`) all packets originating from the `192.168.1.0/24` subnet. Useful for isolating or blocking traffic from a specific network.
sudo iptables -A INPUT -s 192.168.1.0/24 -j DROPClear All Iptables Rules
Clears (`-F`, flush) all rules from all `iptables` chains. Use with extreme caution, as this can open your system to all traffic and compromise security.
sudo iptables -FSave Iptables Rules
Saves the current `iptables` rules to a file. In many systems, this file is used to restore rules on system startup, ensuring firewall configuration persistence.
sudo iptables-save > /etc/iptables/rules.v4Fail2Ban General Status
Displays the general status of the Fail2Ban service, including which "jails" (monitored services, such as SSH, Apache) are active and the total number of banned IPs.
sudo fail2ban-client statusSpecific SSHd Jail Status (Fail2Ban)
Shows the specific status of the `sshd` "jail", including how many IPs have been banned and which IPs are currently banned for the SSH service. Useful for monitoring brute-force attempts.
sudo fail2ban-client status sshdUnban IP with Fail2Ban
Manually unbans an IP address (`192.168.1.100`) from the `sshd` "jail". Useful if a legitimate IP was accidentally blocked or if access needs to be quickly restored.
sudo fail2ban-client set sshd unbanip 192.168.1.100Reload Fail2Ban Configuration
Reloads the Fail2Ban configuration, applying any changes made to configuration files (e.g., `jail.local`) without needing to restart the full service.
sudo fail2ban-client reload⚖️ Load Balancing
12 snippetsCommands for managing and monitoring load balancing solutions like HAProxy, Nginx, and IPVS, ensuring efficient traffic distribution and high availability.
Validate HAProxy Configuration
Validates the syntax of the HAProxy configuration file (`/etc/haproxy/haproxy.cfg`) without starting or restarting the service. Essential to prevent errors before applying changes in production.
haproxy -f /etc/haproxy/haproxy.cfg -cRestart HAProxy Service
Restarts the HAProxy service. This applies new configurations and may cause a brief service interruption, depending on the high availability configuration.
sudo systemctl restart haproxyHAProxy Information via Socket
Displays general information about the HAProxy runtime state, such as version, uptime, number of processes, and session statistics. Requires `socat` and access to the HAProxy control socket.
echo "show info" | socat stdio /var/run/haproxy.sockHAProxy Statistics via Socket
Displays detailed statistics about frontends, backends, and servers, including active connections, sessions, request rates, and errors. Useful for performance and server health monitoring.
echo "show stat" | socat stdio /var/run/haproxy.sockTest Nginx Configuration
Tests the syntax of the Nginx configuration file. It is crucial to run this command before reloading or restarting Nginx to ensure there are no configuration errors that could bring down the service.
nginx -tReload Nginx Configuration
Reloads the Nginx configuration without dropping existing connections. It is the preferred way to apply configuration changes to a production Nginx server, ensuring zero downtime.
sudo nginx -s reloadNginx Load Balancer Status
Makes an HTTP HEAD request to the Nginx status URL (if configured), displaying metrics such as active connections, accepted connections, and handled connections. Requires the `ngx_http_stub_status_module` module.
curl -I http://localhost/nginx_statusMonitor Nginx Access Logs
Monitors the Nginx access log file in real-time, showing HTTP requests as they arrive at the server. Useful for debugging, traffic observation, and identifying access patterns.
tail -f /var/log/nginx/access.logList IPVS Rules (Linux Virtual Server)
Lists all virtual service and real server rules configured in IPVS (Linux Virtual Server). `-n` prevents name resolution for IPs and ports, making the output faster and more concise.
sudo ipvsadm -L -nAdd IPVS Virtual Service
Adds (`-A`) a TCP virtual service (`-t`) at address `192.168.1.100` on port 80, using the `rr` (round-robin) scheduling algorithm to distribute the load among real servers.
sudo ipvsadm -A -t 192.168.1.100:80 -s rrAdd Real Server to IPVS
Adds (`-a`) a real server (`-r`) with IP `192.168.1.101` and port 80 to the virtual service `192.168.1.100:80`, using the `masquerading` (`-m`) routing method.
sudo ipvsadm -a -t 192.168.1.100:80 -r 192.168.1.101:80 -mIPVS Connection Rate
Lists IPVS rules, including connection and traffic rates for each virtual service and real server, providing real-time performance and usage metrics.
sudo ipvsadm -L --rate🔐 VPN
12 snippetsCommands for configuring, managing, and monitoring VPN connections using OpenVPN, WireGuard, and IPSec (strongSwan) for secure communications.
OpenVPN Service Status
Checks the status of the OpenVPN service. On `systemd`-based systems, it shows whether the OpenVPN server or client is running, its uptime, and recent activity. Useful for debugging.
sudo systemctl status openvpnConnect OpenVPN Client
Initiates an OpenVPN connection as a client, using the `client.ovpn` configuration file. This command is executed on the client side to establish the secure VPN tunnel.
openvpn --config client.ovpnStart OpenVPN Server in Daemon
Starts the OpenVPN server in the background (`--daemon`), using the `server.conf` configuration file. Requires root privileges. The server listens for client connections.
sudo openvpn --config server.conf --daemonMonitor OpenVPN Logs
Monitors the OpenVPN log file in real-time, which records connection events, authentication, errors, and disconnections. Essential for VPN debugging and auditing.
tail -f /var/log/openvpn.logGenerate WireGuard Keys
Generates a pair of cryptographic keys (private and public) for WireGuard. The private key is saved to `private.key` and the public key to `public.key`. Essential for peer configuration.
wg genkey | tee private.key | wg pubkey > public.keyActivate WireGuard Interface
Activates the WireGuard interface `wg0` (or the configured name), establishing the VPN connection according to the configuration in `/etc/wireguard/wg0.conf`. Requires root privileges.
sudo wg-quick up wg0WireGuard VPN Status
Displays the current status of all active WireGuard interfaces, including public keys, connected peers, IP addresses, and data traffic. Useful for checking connectivity and configuration.
sudo wg showDeactivate WireGuard Interface
Deactivates the WireGuard interface `wg0`, terminating the VPN connection and removing associated network configurations. Requires root privileges.
sudo wg-quick down wg0IPSec Status (strongSwan)
Displays the general status of the strongSwan IPSec service, including information about configured connections, established tunnels, peers, and traffic statistics. Useful for monitoring and debugging.
sudo ipsec statusStart IPSec Connection
Starts a specific IPSec connection, identified by `connection-name`, as configured in strongSwan files (e.g., `ipsec.conf`). Establishes the VPN tunnel.
sudo ipsec up connection-nameTerminate IPSec Connection
Terminates a specific IPSec connection, releasing associated resources and the VPN tunnel. Disconnects the client or server from the VPN.
sudo ipsec down connection-nameReload IPSec Configuration
Reloads the strongSwan configuration without restarting the daemon, applying any changes made to the IPSec configuration files. Ensures new rules take effect.
sudo ipsec reload⚡ Performance and Optimization
13 snippetsCommands for tuning kernel network parameters, configuring Quality of Service (QoS), and running performance tests to optimize throughput and latency.
Display Maximum Receive Buffer
Displays the maximum socket receive buffer value in bytes for all connections. Adjusting this value can improve performance on high-bandwidth and high-latency networks, allowing the system to store more data before processing it.
sysctl net.core.rmem_maxDisplay Maximum Send Buffer
Displays the maximum socket send buffer value in bytes for all connections. Similar to `rmem_max`, its adjustment can optimize send throughput, especially in high-demand scenarios.
sysctl net.core.wmem_maxTCP Congestion Control Algorithm
Displays the TCP congestion control algorithm currently in use (e.g., `cubic`, `bbr`). The choice of algorithm can significantly impact network performance, especially on links with packet loss or high latency.
sysctl net.ipv4.tcp_congestion_controlTCP Listen Queue Size
Displays the maximum listen queue size for TCP sockets. A low value can lead to refused connections (connection refused) on servers with high request volumes, as new connections cannot be queued.
sysctl net.core.somaxconnDisplay Traffic Queue (Qdisc)
Displays the queueing disciplines (qdisc) configured for the `eth0` network interface. Qdiscs are used to manage how packets are queued and transmitted, forming the basis of QoS.
tc qdisc show dev eth0Create HTB Qdisc for QoS
Creates a Hierarchical Token Bucket (HTB) queueing discipline as `root` on the `eth0` interface, with handle `1:` and default class `30`. HTB is used for hierarchical bandwidth control, allowing prioritization and limitation.
sudo tc qdisc add dev eth0 root handle 1: htb default 30Limit Bandwidth with HTB Class
Adds an HTB class (`classid 1:1`) under the parent qdisc `1:` on the `eth0` interface, limiting the egress rate to 1 Megabit per second (`rate 1mbit`). This allows controlling the available bandwidth for specific traffic.
sudo tc class add dev eth0 parent 1: classid 1:1 htb rate 1mbitFilter Traffic by Port for QoS
Adds a filter to direct destination IP traffic on port 80 (`dport 80`) to class `1:10` (which must be previously defined with a rate or priority). `u32` is a powerful classifier for complex filtering rules.
sudo tc filter add dev eth0 protocol ip parent 1:0 prio 1 u32 match ip dport 80 0xffff flowid 1:10Remove QoS Configuration
Removes the root queuing discipline (`root`) from the `eth0` interface, disabling all QoS rules configured for that interface. This restores the default queuing behavior.
sudo tc qdisc del dev eth0 rootStart Iperf3 Server
Starts the `iperf3` server, which awaits client connections to perform network throughput tests. The server listens on the default port 5201. Essential for measuring bandwidth between two points.
iperf3 -sThroughput Test with Iperf3
Starts a throughput test as an `iperf3` client, connecting to `server_ip` and running the test for 30 seconds (`-t 30`). Displays the average bandwidth achieved during the period.
iperf3 -c server_ip -t 30Latency Test with Ping (Summary)
Performs 100 pings with a 0.1-second interval to `server_ip` and displays only the last line of output, which contains the latency statistics summary (min/avg/max/mdev). Useful for quick latency tests.
ping -c 100 -i 0.1 server_ip | tail -1Testar Porta Aberta com Netcat
Testa se uma porta específica (neste caso, 80) está aberta e acessível em um `server_ip`. A flag `-z` faz um scan sem enviar dados, e `-v` fornece saída verbosa, indicando sucesso ou falha na conexão.
netcat -z -v server_ip 80Related cheatsheets
Get-LocationPowerShell: Automate the Boring Stuff
GUIs are for amateurs. Master the One-Liners and Pipelines that manage 100 servers simultaneously. Stop clicking windows and start treating your infrastructure as code.
git status -sGit: The Emergency Kit
Messed up the code? Save this guide. Essential commands to undo mistakes, revert commits and save your job.
docker --versionDocker: Production Commands
Forget manual configuration. Copy and paste commands to spin up containers, clean volumes and deploy in record time.