Automating Network Diagnostics with Hping and Shell Scripts

Automating Network Diagnostics with Hping and Shell ScriptsNetwork administrators and security professionals often need fast, repeatable ways to diagnose connectivity problems, test firewall rules, and simulate network conditions. Hping, a versatile packet crafting tool, combined with shell scripting, provides a powerful, lightweight way to automate many common network diagnostics tasks. This article explains how hping works, shows practical examples, and walks through building robust shell scripts to automate network testing workflows.


What is Hping?

Hping is a command-line packet generator and analyzer for TCP/IP networks. It can send custom TCP, UDP, ICMP, and raw IP packets and offers features such as TTL manipulation, packet fragmentation, and response analysis. Hping is invaluable for tasks like:

  • Probing open ports and testing service reachability
  • Checking firewall and router rules by crafting packets with specific flags
  • Measuring round-trip time under different packet sizes
  • Simulating traffic patterns for stress testing

Hping is not a replacement for full-featured scanners like Nmap; it’s a packet-level tool for crafting and sending custom packets.


Installing Hping

On most Linux distributions you can install hping3:

  • Debian/Ubuntu:

    sudo apt update sudo apt install hping3 
  • Fedora:

    sudo dnf install hping3 
  • macOS (using Homebrew):

    brew install hping 

Core Hping Usage Examples

  • Send a single ICMP echo (ping):

    sudo hping3 -1 -c 1 example.com 
  • TCP SYN scan on a specific port:

    sudo hping3 -S -p 80 -c 1 example.com 
  • UDP packet to port 53:

    sudo hping3 --udp -p 53 -c 1 example.com 
  • Set packet size and measure RTT:

    sudo hping3 -S -p 80 -d 120 -c 5 example.com 
  • Spoof source IP:

    sudo hping3 -a 1.2.3.4 -S -p 80 example.com 

Automating Common Diagnostics: Script Patterns

Below are patterns and sample scripts to automate routine diagnostics. Save scripts with executable permissions (chmod +x script.sh) and run as root where raw sockets are required.

  1. Host reachability and RTT profiling “`bash #!/usr/bin/env bash HOST=”\(1" COUNT="\){2:-5}” if [[ -z “\(HOST" ]]; then echo "Usage: \)0 host [count]” exit 1 fi

echo “Probing \(HOST with \)COUNT ICMP packets…” sudo hping3 -1 -c “\(COUNT" "\)HOST” | awk -F’ ‘ ‘/len/ {print \(0}’ | sed -n ‘s/^.*time=([0-9.]*)ms.*\)/RTT:  ms/p’


2) Port reachability scan (list of ports) ```bash #!/usr/bin/env bash HOST="$1" PORTS="${2:-22,80,443}" IFS=',' read -ra PORT_ARR <<< "$PORTS" if [[ -z "$HOST" ]]; then   echo "Usage: $0 host [comma-separated-ports]"   exit 1 fi for p in "${PORT_ARR[@]}"; do   echo -n "Port $p: "   sudo hping3 -S -p "$p" -c 1 "$HOST" 2>/dev/null | grep -q 'flags=SA' && echo "open" || echo "closed/filtered" done 
  1. Firewall rule verification (SYN with TTL and fragmentation) “`bash #!/usr/bin/env bash HOST=”\(1" PORT="\){2:-80}” if [[ -z “\(HOST" ]]; then echo "Usage: \)0 host [port]” exit 1 fi

echo “Testing firewall behavior to \(HOST:\)PORT…” sudo hping3 -S -p “\(PORT" -c 3 –ttl 64 "\)HOST” sudo hping3 -S -p “\(PORT" -c 3 –frag "\)HOST”


--- ### Building a More Robust Diagnostic Tool Combine the above pieces into a single script that accepts modes, logs structured output, and optionally emails alerts. Example features: - Modes: quick-scan, full-scan, firewall-test, rtt-monitor - JSON or CSV logging for integration with monitoring - Retry/backoff logic and thresholds for alerting - Parallel scans using background jobs or xargs -P Example skeleton: ```bash #!/usr/bin/env bash MODE="$1" HOST="$2" LOGFILE="${3:-./hping_diag.log}" timestamp(){ date -u +"%Y-%m-%dT%H:%M:%SZ"; } case "$MODE" in   quick-scan)     echo "$(timestamp) quick-scan $HOST" >> "$LOGFILE"     ./port_scan.sh "$HOST" "22,80,443" >> "$LOGFILE"     ;;   rtt-monitor)     echo "$(timestamp) rtt-monitor $HOST" >> "$LOGFILE"     sudo hping3 -1 -i u100000 -c 100 "$HOST" | awk '/time=/ {print "'$(timestamp)'" ", $0}' >> "$LOGFILE"     ;;   firewall-test)     echo "$(timestamp) firewall-test $HOST" >> "$LOGFILE"     ./firewall_test.sh "$HOST" 80 >> "$LOGFILE"     ;;   *)     echo "Usage: $0 {quick-scan|rtt-monitor|firewall-test} host [logfile]"     ;; esac 

Parsing and Interpreting Hping Output

Hping prints human-readable packet results. Use awk, grep, sed, or jq (if you format to JSON) to extract RTTs, flags, and counts. Example: extract “flags” and “seq” values from output and summarize open vs filtered ports.


  • Only run hping against systems you own or have explicit permission to test. Crafting packets can trigger IDS/IPS and may be illegal without authorization.
  • Use rate limits and monitoring when running on production networks to avoid disrupting services.
  • Document tests and get stakeholder buy-in for scheduled automated diagnostics.

Integration with Monitoring Systems

  • Have scripts write structured logs (JSON/CSV) and use filebeat/Telegraf to ship them to ELK, Prometheus (pushgateway), or your SIEM.
  • Use exit codes to signal success/failure for cron jobs and let monitoring trigger alerts when thresholds are exceeded.

Example: Cron-based RTT Alerting

  1. Script measures 20 ICMP RTTs, computes average, exits with non-zero if avg > threshold.
  2. Cron runs every 5 minutes; monitoring alerts on non-zero exit.

Simple avg-check:

#!/usr/bin/env bash HOST="$1" THRESH="${2:-200}"  # ms AVG=$(sudo hping3 -1 -c 20 "$HOST" 2>/dev/null | awk -F'time=' '/time=/ {sum+=substr($2,1,index($2," ")-1); n++} END{if(n>0) printf "%.0f", sum/n; else print "NaN"}') if [[ "$AVG" == "NaN" ]]; then   echo "No responses"   exit 2 fi if (( AVG > THRESH )); then   echo "High RTT: ${AVG}ms"   exit 1 fi echo "OK: ${AVG}ms" exit 0 

Troubleshooting Tips

  • If hping shows no responses but ping works, check intermediate firewalls blocking crafted packets or TCP flags.
  • Run with sudo/root to ensure raw socket capability.
  • Use packet captures (tcpdump/wireshark) to verify what leaves and returns to the host.

Conclusion

Automating network diagnostics with hping and shell scripts yields flexible, scriptable tools for probing reachability, firewall behavior, performance, and resilience. With careful parsing, logging, and safety practices, these scripts can be integrated into monitoring systems to provide targeted, actionable insights without heavy toolchains.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *