Skip to main content
Bash Scripting – Complete Beginner to Advanced Guide
CHAPTER 15 Intermediate

Networking Automation Scripts

Updated: May 16, 2026
30 min read

# CHAPTER 15

Networking Automation Scripts

1. Introduction

A Linux server does not exist in a vacuum; its entire purpose is to process data across a network. When a massive e-commerce web application suddenly goes offline, the fault could exist anywhere in the pipeline: the database server might have lost routing connectivity, the internal firewall might have blocked a port, or the web API might be returning a 500 Internal Server Error. Attempting to manually ping or curl fifty different microservices during an active outage is incredibly slow. In this chapter, we will leverage Bash to automate our network diagnostic toolkit. We will write scripts to mass-ping subnets, verify TCP port availability using netcat (nc), and monitor Application-Layer HTTP responses using curl.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Write an automated ICMP ping sweep script to verify host connectivity.
  • Utilize the nc (Netcat) utility inside a script to verify open TCP ports.
  • Extract and evaluate HTTP status codes (e.g., 200 OK) using curl.
  • Architect a unified, multi-layer network diagnostic dashboard script.
  • Understand how to suppress verbose network command output during automation.

3. Layer 3 Automation (The Ping Sweep)

If you manage a cluster of 5 database nodes, you need a script to verify they are all responding to network traffic. The ping command is the standard sonar.

*Important:* In a script, you must use -c 1 to limit the ping to a single pulse, and you must use -W 1 to limit the timeout to 1 second. If a server is offline, you don't want the script pausing for 10 seconds waiting for a response!

bash
1234567891011121314151617
#!/bin/bash

# Define the cluster nodes
NODES=("192.168.1.10" "192.168.1.11" "192.168.1.12")

echo "Initiating Layer 3 Ping Sweep..."

for IP in "${NODES[@]}"; do
    # Ping once (-c 1), Timeout in 1 sec (-W 1), suppress output
    ping -c 1 -W 1 "$IP" > /dev/null 2>&1
    
    if [ $? -eq 0 ]; then
        echo "[ONLINE] Node $IP is responding."
    else
        echo "[OFFLINE] Node $IP is DOWN!"
    fi
done

4. Layer 4 Automation (Port Checks)

A server might reply to a ping, but the MySQL database (Port 3306) running on it might have crashed. Ping cannot tell you if a port is open. We must use Netcat (nc). We will use nc -z (Zero-I/O mode), which simply scans the port and instantly returns an exit code.
bash
123456789101112131415
#!/bin/bash

TARGET="192.168.1.50"
PORT=3306

echo "Verifying Database Port..."

# -z (Scan mode), -v (Verbose, which we redirect), -w 2 (Timeout 2 secs)
nc -z -w 2 "$TARGET" "$PORT" > /dev/null 2>&1

if [ $? -eq 0 ]; then
    echo "SUCCESS: Port $PORT on $TARGET is open and listening."
else
    echo "CRITICAL: Port $PORT on $TARGET is closed or blocked by firewall!"
fi

5. Layer 7 Automation (HTTP API Checks)

The server is online, the port is open, but the web application's code is broken and displaying a blank white screen. Port checks cannot detect application errors. We must use curl to grab the actual HTTP Status Code (like 200 for OK, or 404 for Not Found).
bash
12345678910111213
#!/bin/bash

URL="https://example.com/api/health"

# -s (Silent), -o /dev/null (Discard the actual HTML page data)
# -w "%{http_code}" (Write out ONLY the 3-digit HTTP response code)
STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$URL")

if [ "$STATUS" == "200" ]; then
    echo "API is Healthy (HTTP 200)."
else
    echo "API Failure! Returned HTTP Code: $STATUS"
fi

*(This 10-line script replaces thousands of dollars of commercial website monitoring software).*

6. Diagrams/Visual Suggestions

*Visual Concept: The OSI Troubleshooting Funnel* Draw a funnel showing the progression of network diagnostics in a script.
  • Top layer (Widest): Ping (Layer 3). "Is the machine turned on?"
  • Middle layer: Netcat (Layer 4). "Is the firewall allowing traffic to the web port?"
  • Bottom layer (Narrowest): Curl (Layer 7). "Is the web application actually returning healthy data?"
This visualizes the logical sequence a script must follow. If ping fails, there is no reason for the script to execute curl.

7. Best Practices

  • Implement Strict Timeouts: Network commands are historically dangerous in scripts because they "hang." If a script runs curl http://offline-server.com without a timeout flag, the script will literally freeze in the terminal for 2 minutes waiting for the network request to drop. Always enforce timeouts (curl --max-time 5, ping -W 1) to ensure scripts fail rapidly and continue execution.

8. Common Mistakes

  • Grepping for Ping output: Beginners often try to run ping and pipe the output into grep to look for the word "bytes from" to see if it succeeded. This is incredibly inefficient and error-prone depending on the operating system's exact ping string format. Always rely on the $? exit code (0 for success, 1 for failure) which is universally standardized across all Linux distributions.

9. Mini Project: Build a Full-Stack Uptime Monitor

Let's synthesize all three layers into a single, professional network diagnostic tool.
  1. 1. nano uptime_monitor.sh
  1. 2. Write the code:
bash
123456789101112131415161718192021222324252627282930313233
#!/bin/bash

TARGET_IP="1.1.1.1" # Example target (Cloudflare DNS)
TARGET_PORT=443     # HTTPS port
TARGET_URL="https://1.1.1.1"

echo "=== INITIATING FULL-STACK DIAGNOSTIC ==="

# 1. Layer 3: ICMP Check
ping -c 1 -W 1 "$TARGET_IP" > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "[FATAL] Server is totally offline. Aborting further tests."
    exit 1
fi
echo "[OK] Server is reachable (Ping successful)."

# 2. Layer 4: TCP Port Check
nc -z -w 2 "$TARGET_IP" "$TARGET_PORT" > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "[FATAL] Firewall is blocking Port $TARGET_PORT. Aborting."
    exit 1
fi
echo "[OK] Port $TARGET_PORT is open and listening."

# 3. Layer 7: HTTP Application Check
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$TARGET_URL")
if [ "$HTTP_STATUS" != "200" ] && [ "$HTTP_STATUS" != "301" ]; then
    echo "[ERROR] Web Application failure. HTTP Code: $HTTP_STATUS"
    exit 1
fi
echo "[OK] Application is responding with HTTP $HTTP_STATUS."

echo "=== DIAGNOSTIC COMPLETE: SERVER IS 100% HEALTHY ==="

10. Practice Exercises

  1. 1. Explain the operational difference between monitoring a web server via nc (Netcat) versus curl. Which tool would successfully detect if a web application developer accidentally broke the website's code resulting in a 500 Internal Server Error?
  1. 2. Why is it an architectural requirement to include a timeout flag (e.g., -W 1) when writing automated network diagnostic scripts?

11. MCQs with Answers

Question 1

When writing a network monitoring script, an administrator must verify that a remote database server is actively listening for connections on TCP Port 5432. Which command-line utility is explicitly designed to perform this zero-I/O port scan?

Question 2

To extract only the numerical HTTP status code (e.g., "404") from a web request without downloading or displaying the actual HTML body of the webpage, which curl flag combination is utilized?

12. Interview Questions

  • Q: A developer complains that their automated deployment script freezes for exactly two minutes before reporting an error when attempting to download an asset via curl from a broken URL. Explain the mechanical network networking behavior causing this freeze, and provide the exact flag required to enforce a "Fail Fast" methodology in the script.
  • Q: You are tasked with writing a Bash script to monitor a critical REST API. Walk me through the logical progression of troubleshooting steps your script should execute, starting from Layer 3 (Network) and ending at Layer 7 (Application).
  • Q: Explain why a systems engineer should never parse the literal text output of the ping command using grep to determine success within a Bash script, and describe the mathematically superior alternative.

13. FAQs

Q: My script is checking an HTTPS website and failing because the SSL certificate is expired. How do I bypass this? A: By default, curl enforces strict cryptographic security and will block connections to sites with invalid or expired certificates. If you are testing a development server without a real certificate, you can append the -k (Insecure) flag to curl to force it to connect anyway.

14. Summary

In Chapter 15, we extended our automation's reach beyond the local filesystem and out into the global network. We constructed a multi-layered diagnostic pipeline, utilizing ping to verify fundamental Layer 3 routing pathways. We advanced to Layer 4, deploying nc (Netcat) to interrogate firewall rules and TCP port availability. Finally, we operated at the Application Layer, harnessing the advanced formatting capabilities of curl to surgically extract and evaluate HTTP response codes. Most importantly, we enforced rigid timeout protocols across all network utilities, ensuring our automated pipelines fail rapidly rather than locking up in perpetual wait states.

15. Next Chapter Recommendation

Your scripts are powerful, but powerful scripts can cause catastrophic damage if they encounter unexpected data. You must learn to debug them and handle errors gracefully. Proceed to Chapter 16: Error Handling and Debugging.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·