dotlinux guide

Shell Scripting for Network Administrators: Essential Commands

Table of Contents

  1. Why Shell Scripting for Network Administrators?
  2. Fundamentals of Shell Scripting
  3. Essential Network Commands in Shell Scripts
  4. Common Use Cases & Script Examples
  5. Best Practices for Network Shell Scripts
  6. Conclusion
  7. References

Why Shell Scripting for Network Administrators?

Shell scripting (e.g., with Bash) is ideal for network admins for three key reasons:

  • Automation: Eliminate manual tasks like daily connectivity checks or log analysis.
  • Flexibility: Combine low-level network commands with logic (loops, conditionals) to build custom tools.
  • Accessibility: Requires no specialized programming knowledge—leverages existing Linux/Unix command-line skills.

Fundamentals of Shell Scripting

Before diving into network commands, let’s recap core shell scripting concepts:

Shebang

The first line of a script specifies the interpreter (e.g., Bash):

#!/bin/bash

Variables

Store data (e.g., hostnames, IPs, file paths):

HOST="google.com"
LOG_FILE="/var/log/network_monitor.log"

Loops

Iterate over lists (e.g., hosts, ports):

HOSTS=("192.168.1.1" "8.8.8.8" "example.com")
for host in "${HOSTS[@]}"; do
  echo "Checking $host..."
done

Conditionals

Add logic (e.g., check if a host is reachable):

if ping -c 1 "$HOST" &> /dev/null; then
  echo "$HOST is UP"
else
  echo "$HOST is DOWN"
fi

Functions

Reuse code (e.g., a reusable connectivity check):

check_connectivity() {
  local host=$1
  if ping -c 1 "$host" &> /dev/null; then
    return 0  # Success
  else
    return 1  # Failure
  fi  
}

Essential Network Commands in Shell Scripts

Below are critical network commands and how to integrate them into scripts.

ping: Test Connectivity

Purpose: Send ICMP echo requests to check if a host is reachable.
Script Usage: Validate host availability in bulk.

Example: Check Multiple Hosts

#!/bin/bash
# ping_check.sh: Check connectivity to a list of hosts and log results

HOSTS=("192.168.1.1" "8.8.8.8" "example.com" "invalid.host")
LOG_FILE="/var/log/ping_checks.log"

# Log timestamp
echo "=== $(date '+%Y-%m-%d %H:%M:%S') ===" >> "$LOG_FILE"

for host in "${HOSTS[@]}"; do
  if ping -c 2 -W 3 "$host" &> /dev/null; then  # -c: 2 packets, -W: 3s timeout
    echo "[$(date '+%H:%M:%S')] $host: UP" >> "$LOG_FILE"
  else
    echo "[$(date '+%H:%M:%S')] $host: DOWN" >> "$LOG_FILE"
    # Optional: Send alert (requires 'mail' utility)
    # echo "$host is DOWN" | mail -s "Network Alert" [email protected]
  fi
done

traceroute/mtr: Diagnose Path Issues

Purpose: Trace the route packets take to a host (identify hops/failures).
Script Usage: Troubleshoot connectivity gaps.

Example: Trace Route to Unreachable Host

#!/bin/bash
# trace_issue.sh: Run traceroute if ping fails

HOST="example.com"

if ! ping -c 1 "$HOST" &> /dev/null; then
  echo "Ping failed. Running traceroute to $HOST..."
  traceroute "$HOST" > "/tmp/traceroute_$HOST.log"
  echo "Traceroute saved to /tmp/traceroute_$HOST.log"
fi

netstat/ss: Monitor Network Connections

Purpose: List active connections, open ports, and process IDs (PIDs).

  • netstat: Legacy tool (use ss for faster, modern alternative).
  • ss: Socket statistics (more efficient for high-traffic systems).

Example: Monitor Open Ports

#!/bin/bash
# monitor_ports.sh: List top 5 open TCP ports by connection count

echo "Top 5 Open TCP Ports (as of $(date '+%H:%M:%S')):"
ss -tuln  # -t: TCP, -u: UDP, -l: listening, -n: numeric (no DNS)
# For connection counts per port:
ss -tna | awk '{print $4}' | cut -d: -f2 | sort | uniq -c | sort -nr | head -5

ip: Manage Network Interfaces & Routes

Purpose: Configure interfaces (IP, subnet), routes, and ARP tables (replaces ifconfig).

Example: Check Interface Status

#!/bin/bash
# check_interface.sh: Verify status of a specific interface

INTERFACE="eth0"

if ip link show "$INTERFACE" | grep -q "UP"; then
  echo "$INTERFACE is UP"
  ip addr show "$INTERFACE" | grep "inet "  # Print IP address
else
  echo "$INTERFACE is DOWN"
fi

curl/wget: Test HTTP/HTTPS Services

Purpose: Send HTTP requests to test web servers, APIs, or download files.

Example: Check Web Service Availability

#!/bin/bash
# check_web_service.sh: Validate HTTP status of a URL

URL="https://example.com"
TIMEOUT=10  # Seconds

response=$(curl -s -w "%{http_code}" -o /dev/null --connect-timeout "$TIMEOUT" "$URL")

if [ "$response" -eq 200 ]; then
  echo "Service $URL is UP (HTTP 200)"
elif [ "$response" -eq 000 ]; then
  echo "Service $URL is DOWN (timeout)"
else
  echo "Service $URL returned HTTP $response"
fi

dig/nslookup: Validate DNS Records

Purpose: Query DNS servers to check A, CNAME, MX, or TXT records.

Example: Audit DNS Resolution

#!/bin/bash
# dns_audit.sh: Verify DNS resolution for a list of domains

DOMAINS=("google.com" "github.com" "example.invalid")
DNS_SERVER="8.8.8.8"  # Use Google DNS

for domain in "${DOMAINS[@]}"; do
  echo "Checking $domain..."
  ip=$(dig +short "@$DNS_SERVER" "$domain" A)  # Query A record
  if [ -z "$ip" ]; then
    echo "  No A record found for $domain"
  else
    echo "  A record: $ip"
  fi
done

iptables: Manage Firewall Rules

Purpose: Configure Linux kernel firewall rules (e.g., allow/block ports).

Example: Backup Firewall Rules

#!/bin/bash
# backup_iptables.sh: Backup and restore iptables rules

BACKUP_DIR="/var/backups/iptables"
TIMESTAMP=$(date '+%Y%m%d_%H%M%S')
BACKUP_FILE="$BACKUP_DIR/iptables_rules_$TIMESTAMP.txt"

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

# Backup rules
iptables-save > "$BACKUP_FILE"
echo "iptables rules backed up to $BACKUP_FILE"

# Optional: Restore from latest backup (uncomment to use)
# LATEST_BACKUP=$(ls -t "$BACKUP_DIR" | head -1)
# iptables-restore < "$BACKUP_DIR/$LATEST_BACKUP"

tcpdump: Capture and Analyze Traffic

Purpose: Capture live network packets for debugging (e.g., dropped packets, unusual traffic).

Example: Capture HTTP Traffic

#!/bin/bash
# capture_http.sh: Capture HTTP traffic on port 80 (requires root)

INTERFACE="eth0"
OUTPUT_FILE="/tmp/http_traffic.pcap"

if [ "$(id -u)" -ne 0 ]; then
  echo "Error: Run as root (tcpdump requires privileges)" >&2
  exit 1
fi

echo "Capturing HTTP traffic on $INTERFACE (Ctrl+C to stop)..."
tcpdump -i "$INTERFACE" port 80 -w "$OUTPUT_FILE"  # -w: Write to file
echo "Capture saved to $OUTPUT_FILE (use Wireshark to analyze)"

ssh/scp: Remote Execution & File Transfer

Purpose: Run commands on remote servers or transfer files securely.

Example: Remote Service Check

#!/bin/bash
# remote_service_check.sh: Check if Apache is running on a remote server

REMOTE_USER="admin"
REMOTE_HOST="web-server.example.com"

# Run 'systemctl' command remotely via SSH
status=$(ssh "$REMOTE_USER@$REMOTE_HOST" "systemctl is-active apache2")

if [ "$status" = "active" ]; then
  echo "Apache is RUNNING on $REMOTE_HOST"
else
  echo "Apache is NOT RUNNING on $REMOTE_HOST (status: $status)"
fi

Common Use Cases & Script Examples

Automated Connectivity Monitoring

Goal: Check multiple hosts hourly and alert on failures.

#!/bin/bash
# hourly_connectivity_check.sh (Add to crontab: 0 * * * *)

HOSTS=("192.168.1.1" "8.8.8.8" "example.com")
LOG_FILE="/var/log/hourly_connectivity.log"
ALERT_EMAIL="[email protected]"

echo "=== $(date '+%Y-%m-%d %H:%M') ===" >> "$LOG_FILE"

for host in "${HOSTS[@]}"; do
  if ! ping -c 1 -W 2 "$host" &> /dev/null; then
    echo "ALERT: $host is DOWN" | tee -a "$LOG_FILE"
    echo "$host is unreachable at $(date)" | mail -s "Network Alert: $host DOWN" "$ALERT_EMAIL"
  else
    echo "$host is UP" >> "$LOG_FILE"
  fi
done

Port and Service Health Checker

Goal: Verify critical ports (e.g., 22, 80, 443) are open on remote servers.

#!/bin/bash
# port_checker.sh

SERVERS=(
  "web-server:80"
  "db-server:3306"
  "ssh-server:22"
)
TIMEOUT=5  # Seconds

for server_port in "${SERVERS[@]}"; do
  server=$(echo "$server_port" | cut -d: -f1)
  port=$(echo "$server_port" | cut -d: -f2)
  
  # Use nc (netcat) to check port
  if nc -z -w "$TIMEOUT" "$server" "$port"; then
    echo "✅ $server:$port is OPEN"
  else
    echo "❌ $server:$port is CLOSED"
  fi
done

DNS Resolution Audit

Goal: Ensure internal domains resolve to the correct IPs.

#!/bin/bash
# dns_audit.sh

DOMAINS=(
  "intranet.corp.com:10.0.1.5"
  "fileserver.corp.com:10.0.2.10"
)
DNS_SERVER="10.0.0.1"  # Internal DNS

for entry in "${DOMAINS[@]}"; do
  domain=$(echo "$entry" | cut -d: -f1)
  expected_ip=$(echo "$entry" | cut -d: -f2)
  
  resolved_ip=$(dig +short "@$DNS_SERVER" "$domain" A | head -1)
  
  if [ "$resolved_ip" = "$expected_ip" ]; then
    echo "✅ $domain resolves to $expected_ip (correct)"
  else
    echo "❌ $domain resolves to $resolved_ip (expected: $expected_ip)"
  fi
done

Firewall Rule Backup

Goal: Automatically back up iptables rules daily.

#!/bin/bash
# backup_firewall.sh (Add to crontab: 0 2 * * * root)

BACKUP_DIR="/var/backups/iptables"
MAX_BACKUPS=7  # Keep last 7 days of backups

# Create backup
mkdir -p "$BACKUP_DIR"
iptables-save > "$BACKUP_DIR/iptables_$(date +%Y%m%d).rules"

# Prune old backups
ls -tp "$BACKUP_DIR" | grep -v '/$' | tail -n +"$((MAX_BACKUPS + 1))" | xargs -I {} rm -- "$BACKUP_DIR/{}"

Best Practices for Network Shell Scripts

To ensure your scripts are reliable, secure, and maintainable:

1. Error Handling

Use set -euo pipefail to exit on errors, undefined variables, or failed pipeline commands:

#!/bin/bash
set -euo pipefail  # Exit on error, undefined var, or pipe failure

2. Input Validation

Check for required arguments or valid inputs:

if [ $# -ne 1 ]; then
  echo "Usage: $0 <host>"
  exit 1
fi
HOST="$1"

3. Avoid Hardcoded Secrets

Never embed passwords/API keys. Use environment variables or secure vaults:

# Bad: sshpass -p "mypassword" ssh user@host
# Good: Use SSH keys or environment variables
SSH_USER="${SSH_USER:-admin}"  # Default to "admin" if unset

4. Logging

Log to files (not just stdout) for auditing:

LOG_FILE="/var/log/script.log"
echo "[$(date)] Action performed" >> "$LOG_FILE"

5. Portability

Use POSIX-compliant commands (e.g., ss instead of netstat on modern systems) and avoid Linux-specific tools unless necessary.

6. Testing

Test scripts in staging first. Use shellcheck (a linter) to catch bugs:

shellcheck my_script.sh  # Install with: sudo apt install shellcheck

7. Documentation

Add comments for complex logic and a usage message:

#!/bin/bash
# Purpose: Monitor DNS resolution for critical domains
# Usage: ./dns_audit.sh <domain_list.txt>
# Example: ./dns_audit.sh domains.txt

Conclusion

Shell scripting empowers network administrators to automate repetitive tasks, troubleshoot efficiently, and build custom tools tailored to their infrastructure. By mastering essential commands like ping, ss, iptables, and curl, combined with robust scripting practices (error handling, logging, security), you can transform how you manage networks—saving time and reducing errors.

Start small: automate one task (e.g., daily connectivity checks) and expand from there. With practice, shell scripting will become an indispensable part of your network administration toolkit.

References