Skip to main content
Shell Scripting – Complete Beginner to Advanced Guide
CHAPTER 14 Intermediate

Networking and Remote Commands

Updated: May 16, 2026
35 min read

# CHAPTER 14

Networking and Remote Commands

1. Introduction

A Unix server does not exist in a vacuum; its entire purpose is to process data across a network. When a massive distributed application suddenly goes offline, the fault could exist anywhere: the database server might have lost routing connectivity, the web API might be returning a 500 Internal Server Error, or a configuration file on a remote server might be corrupt. Attempting to manually ping fifty different microservices or manually SSH into a cluster of nodes to check their status during an active outage is incredibly slow. In this chapter, we will leverage Shell Scripting to automate our network diagnostic toolkit. We will write scripts to mass-ping subnets, monitor Application-Layer HTTP responses using curl, and execute remote administrative commands securely using ssh.

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.
  • Extract and evaluate HTTP status codes (e.g., 200 OK) using curl.
  • Download external dependencies autonomously utilizing wget or curl.
  • Execute administrative commands on remote servers utilizing ssh.
  • Transfer files securely between servers utilizing scp.
  • Enforce strict timeouts on network commands to prevent script hanging.

3. Layer 3 Automation (The Ping Sweep)

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

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

sh
123456789101112131415161718
#!/bin/sh

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

echo "Initiating ICMP Ping Sweep..."

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

4. Layer 7 Automation (HTTP API Checks)

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

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).*

5. Remote Administration (ssh and scp)

Why log into 5 servers individually to run uptime when your script can do it for you? You can pass commands directly to ssh. *(Note: This requires SSH Keys to be pre-configured, otherwise the script will pause and ask for a password).*

1. Remote Command Execution:

sh
123456
#!/bin/sh
TARGET="admin@10.0.0.50"

echo "Checking disk space on remote server..."
# Pass the 'df -h' command to SSH
ssh "$TARGET" 'df -h /'

2. Automated Secure File Transfer (scp): If you generate a backup archive locally, you can push it to a remote storage server securely.

sh
123
#!/bin/sh
# Copy backup.tar to the /archives folder on the remote server
scp /tmp/backup.tar admin@10.0.0.60:/archives/

6. Diagrams/Visual Suggestions

*Visual Concept: The Network 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?"
  • Bottom layer (Narrowest): Curl (Layer 7). "Is the web application actually returning healthy HTML data?"
This visualizes the logical sequence a script must follow. If ping fails, there is no logical 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 naturally 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 phrase "bytes from" to determine 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 status code (0 for success, 1 for failure) which is universally standardized across all Unix distributions.

9. Mini Project: Remote Health Dashboard

Let's build a script that queries a cluster of remote servers to check their system load using SSH.
  1. 1. nano cluster_health.sh
  1. 2. Write the code:
sh
12345678910111213141516171819
#!/bin/sh

# List of remote nodes (Assuming SSH keys are configured)
NODES="node1.corp.com node2.corp.com node3.corp.com"

echo "=== CLUSTER HEALTH DASHBOARD ==="

for SERVER in $NODES; do
    echo "Querying $SERVER..."
    
    # Use SSH with an explicit timeout to prevent hanging on a dead node
    LOAD=$(ssh -o ConnectTimeout=3 "$SERVER" 'uptime' 2>/dev/null)
    
    if [ $? -eq 0 ]; then
        echo "[OK] $SERVER | $LOAD"
    else
        echo "[FATAL] $SERVER is unreachable or SSH timed out!"
    fi
done
  1. 3. Run it. You now have a centralized dashboard gathering live telemetry from an entire cloud fleet.

10. Practice Exercises

  1. 1. Explain the operational difference between monitoring a web server via ping 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 absolute architectural requirement to include a timeout flag (e.g., --max-time 5) when writing automated curl scripts?

11. MCQs with Answers

Question 1

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

Question 2

When writing a script to automate file backups to a remote offsite server across the internet, which command-line utility provides encrypted, secure file transfer utilizing the SSH protocol?

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 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 shell 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 shell script, and describe the mathematically superior alternative.

13. FAQs

Q: My curl script is checking an HTTPS website and failing because the SSL certificate is expired or self-signed. 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 an internal 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 14, we extended our automation's reach beyond the local filesystem and out into the global network. We constructed diagnostic pipelines utilizing ping to verify fundamental Layer 3 routing pathways. We operated at the Application Layer, harnessing the advanced formatting capabilities of curl to surgically extract and evaluate HTTP response codes. We integrated ssh and scp to project our administrative commands and files securely across clusters of remote nodes. 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

You can communicate with the entire network. Now it is time to combine everything we have learned—variables, logic, loops, and files—into massive, practical administrative tools. Proceed to Chapter 15: System Administration Automation.

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: ·