🌐 Networking with Linux Shell Scripting

Master network management, monitoring, and troubleshooting with practical shell scripts

📚 Network Fundamentals

Understanding the foundation of network communication

OSI Model - The Foundation of Networking

Layer 7 - Application (HTTP, FTP, SSH, SMTP)
Layer 6 - Presentation (SSL/TLS, Encryption, Compression)
Layer 5 - Session (NetBIOS, RPC, SQL Sessions)
Layer 4 - Transport (TCP, UDP, Port Numbers)
Layer 3 - Network (IP, ICMP, Routing)
Layer 2 - Data Link (Ethernet, PPP, MAC Addresses)
Layer 1 - Physical (Cables, Hubs, Electrical Signals)

OSI Model in Practice

Each layer has specific responsibilities and interacts only with adjacent layers. Understanding this helps troubleshoot network issues systematically.

LayerNameFunctionLinux ToolsCommon Protocols
7ApplicationUser interface & servicescurl, wget, ssh, ftpHTTP, FTP, SSH, SMTP
6PresentationData formatting & encryptionopenssl, gpgSSL/TLS, JPEG, GIF
5SessionConnection managementnetstat, ssNetBIOS, RPC
4TransportReliable data deliveryss, netstat, ncTCP, UDP
3NetworkRouting & addressingip, route, tracerouteIP, ICMP, OSPF
2Data LinkFrame handling & MACip link, ethtool, arpEthernet, PPP
1PhysicalHardware & signalslshw, dmesg, iwconfigCables, Radio waves

🔗 Network Topologies

Visual understanding of different network architectures

Interactive Network Topologies

Star Topology

SWITCH
PC1
PC2
PC3
SRV
PRT
LAP

✓ Advantages: Easy installation, centralized management, fault isolation, scalable

✗ Disadvantages: Central hub single point of failure, requires more cable

🏢 Best Use: Modern office LANs, most common topology today

TopologyCostReliabilityScalabilityPerformanceBest Use Case
StarMediumGoodExcellentGoodOffice LANs
RingMediumFairLimitedPredictableLegacy systems
BusLowPoorLimitedDegradesSmall networks
MeshVery HighExcellentPoorExcellentCritical systems
TreeHighGoodExcellentGoodLarge organizations

🔧 Network Interface Management

Managing network interfaces with shell scripts

📋 Check Network Interfaces

#!/bin/bash
# Display all network interfaces
ip addr show

# Show only active interfaces
ip link show up

# Interface statistics
cat /proc/net/dev

# Wireless interfaces
iwconfig 2>/dev/null

⚙️ Configure Interface

#!/bin/bash
# Configure network interface
INTERFACE="eth0"
IP="192.168.1.100"
NETMASK="24"
GATEWAY="192.168.1.1"

# Set IP address
sudo ip addr add $IP/$NETMASK dev $INTERFACE

# Bring interface up
sudo ip link set $INTERFACE up

# Set default gateway
sudo ip route add default via $GATEWAY

echo "✅ Interface $INTERFACE configured"

Interface Management Best Practices

  • Always backup current configuration before changes
  • Test changes in non-production environments first
  • Use descriptive interface names when possible
  • Monitor interface statistics for performance issues

Advanced Interface Operations

🔍 Interface Details

#!/bin/bash
# Detailed interface information
INTERFACE="eth0"

echo "=== Interface: $INTERFACE ==="
ethtool $INTERFACE | grep -E "(Speed|Duplex|Link)"
ip addr show $INTERFACE
ip route show dev $INTERFACE

📊 Traffic Statistics

#!/bin/bash
# Interface traffic monitoring
INTERFACE="eth0"

while true; do
    clear
    echo "Traffic on $INTERFACE:"
    cat /proc/net/dev | grep $INTERFACE
    sleep 2
done

🔄 Interface Reset

#!/bin/bash
# Safely restart interface
INTERFACE="eth0"

echo "Restarting $INTERFACE..."
sudo ip link set $INTERFACE down
sleep 2
sudo ip link set $INTERFACE up
echo "✅ Interface restarted"

🔍 Network Connectivity Testing

Comprehensive network testing and troubleshooting

Testing Strategy

Follow a systematic approach: Physical → Data Link → Network → Transport → Application layers

🏓 Basic Connectivity (ICMP)

#!/bin/bash
# Comprehensive ping test
TARGETS=("8.8.8.8" "google.com" "192.168.1.1")

echo "🔍 Testing Connectivity..."
for target in "${TARGETS[@]}"; do
    if ping -c 3 -W 3 $target >/dev/null 2>&1; then
        latency=$(ping -c 3 $target | tail -1 | cut -d'/' -f5)
        echo "✅ $target: ${latency}ms"
    else
        echo "❌ $target: UNREACHABLE"
    fi
done

🔌 Port Connectivity (TCP/UDP)

#!/bin/bash
# Test specific ports
HOST="google.com"
PORTS=(80 443 22 53)

echo "🔍 Testing Ports on $HOST..."
for port in "${PORTS[@]}"; do
    if timeout 5 bash -c "echo >/dev/tcp/$HOST/$port" 2>/dev/null; then
        echo "✅ Port $port: OPEN"
    else
        echo "❌ Port $port: CLOSED/FILTERED"
    fi
done

Advanced Connectivity Tests

🧪 Comprehensive Network Test

#!/bin/bash
# Complete network health check
echo "🏥 Network Health Check"
echo "======================"

# 1. Interface status
echo "📡 Network Interfaces:"
ip link show | grep -E "^[0-9]+:" | while read line; do
    iface=$(echo $line | cut -d: -f2 | tr -d ' ')
    state=$(echo $line | grep -o "state [A-Z]*" | cut -d' ' -f2)
    echo "  $iface: $state"
done

# 2. Default gateway
echo "🚪 Default Gateway:"
GATEWAY=$(ip route | grep default | awk '{print $3}')
if ping -c 1 $GATEWAY >/dev/null 2>&1; then
    echo "  ✅ $GATEWAY reachable"
else
    echo "  ❌ $GATEWAY unreachable"
fi

# 3. DNS resolution
echo "🔍 DNS Resolution:"
if nslookup google.com >/dev/null 2>&1; then
    echo "  ✅ DNS working"
else
    echo "  ❌ DNS failed"
fi

# 4. Internet connectivity
echo "🌐 Internet Connectivity:"
if curl -s --max-time 5 http://google.com >/dev/null; then
    echo "  ✅ Internet accessible"
else
    echo "  ❌ Internet not accessible"
fi

Troubleshooting Tips

  • Start with physical layer (cables, LEDs)
  • Check interface status and IP configuration
  • Test local network connectivity first
  • Verify DNS resolution separately
  • Use traceroute to identify where packets are dropped

🗺️ Routing Management

Understanding and managing network traffic routing

📋 View Routing Information

#!/bin/bash
# Display routing table
echo "🗺️ Current Routing Table:"
ip route show

echo "🚪 Default Gateway:"
ip route show default

echo "📏 Routing Rules:"
ip rule show

echo "🏃 Route Cache:"
ip route show cache

➕ Add Custom Routes

#!/bin/bash
# Add custom routes
NETWORK="10.0.0.0/8"
GATEWAY="192.168.1.1"
INTERFACE="eth0"

# Add network route
sudo ip route add $NETWORK via $GATEWAY dev $INTERFACE

# Add host route
sudo ip route add 8.8.8.8 via $GATEWAY

echo "✅ Custom routes added"
echo "Current routes:"
ip route show

Advanced Routing Operations

🔄 Dynamic Routing Management

#!/bin/bash
# Advanced routing script
echo "🔧 Advanced Routing Management"

# Function to add route with validation
add_route() {
    local network=$1
    local gateway=$2
    local interface=$3
    
    if ip route add $network via $gateway dev $interface 2>/dev/null; then
        echo "✅ Route added: $network via $gateway"
    else
        echo "❌ Failed to add route: $network"
    fi
}

# Function to remove route
remove_route() {
    local network=$1
    
    if ip route del $network 2>/dev/null; then
        echo "✅ Route removed: $network"
    else
        echo "❌ Route not found: $network"
    fi
}

# Function to test route
test_route() {
    local destination=$1
    echo "🧪 Testing route to $destination:"
    traceroute -n -m 5 $destination | head -6
}

# Example usage
add_route "192.168.100.0/24" "192.168.1.1" "eth0"
test_route "192.168.100.1"

Routing Best Practices

  • Use specific routes before general ones
  • Monitor routing table size in large networks
  • Implement route redundancy for critical paths
  • Document custom routing decisions
  • Test routes before implementing in production

📊 Network Monitoring

Real-time network performance monitoring and analysis

📈 Real-time Monitoring

#!/bin/bash
# Network monitoring dashboard
echo "📊 Network Monitoring Dashboard"
echo "==============================="

while true; do
    clear
    echo "🕐 $(date)"
    echo
    
    # Interface status
    echo "📡 Active Interfaces:"
    ip link show up | grep -E "^[0-9]+:" | head -5
    echo
    
    # Network connections
    echo "🔗 Network Connections:"
    ss -s
    echo
    
    # Top bandwidth usage
    echo "📊 Network Usage:"
    cat /proc/net/dev | grep -v lo | head -3
    
    sleep 5
done

🚨 Alert System

#!/bin/bash
# Network monitoring with alerts
ALERT_EMAIL="admin@company.com"
PING_TARGET="8.8.8.8"
BANDWIDTH_THRESHOLD=80

check_connectivity() {
    if ! ping -c 3 $PING_TARGET >/dev/null 2>&1; then
        echo "🚨 ALERT: Internet connectivity lost!"
        # Send email alert (requires mail setup)
        # echo "Connectivity lost" | mail -s "Network Alert" $ALERT_EMAIL
        return 1
    fi
    return 0
}

check_bandwidth() {
    # Simplified bandwidth check
    local usage=$(cat /proc/loadavg | cut -d' ' -f1 | cut -d'.' -f1)
    if [ $usage -gt $BANDWIDTH_THRESHOLD ]; then
        echo "🚨 ALERT: High bandwidth usage: ${usage}%"
        return 1
    fi
    return 0
}

# Main monitoring loop
while true; do
    check_connectivity
    check_bandwidth
    sleep 30
done

Performance Metrics

📋 Comprehensive Network Report

#!/bin/bash
# Generate network performance report
generate_report() {
    local report_file="network_report_$(date +%Y%m%d_%H%M%S).txt"
    
    echo "📋 Network Performance Report" > $report_file
    echo "Generated: $(date)" >> $report_file
    echo "=================================" >> $report_file
    echo >> $report_file
    
    # System info
    echo "🖥️  System Information:" >> $report_file
    echo "Hostname: $(hostname)" >> $report_file
    echo "Uptime: $(uptime)" >> $report_file
    echo >> $report_file
    
    # Interface information
    echo "📡 Network Interfaces:" >> $report_file
    ip addr show >> $report_file
    echo >> $report_file
    
    # Routing table
    echo "🗺️  Routing Table:" >> $report_file
    ip route show >> $report_file
    echo >> $report_file
    
    # Active connections
    echo "🔗 Active Connections:" >> $report_file
    ss -tuln >> $report_file
    echo >> $report_file
    
    # Network statistics
    echo "📊 Network Statistics:" >> $report_file
    cat /proc/net/dev >> $report_file
    
    echo "✅ Report generated: $report_file"
}

generate_report

🔒 Network Security

Implementing network security measures and monitoring

Security First

Always test security scripts in isolated environments. Never run unknown scripts with elevated privileges.

🛡️ Firewall Management

#!/bin/bash
# Firewall status and management
check_firewall() {
    echo "🛡️ Firewall Status Check"
    echo "========================"
    
    # Check UFW (Ubuntu/Debian)
    if command -v ufw &>/dev/null; then
        echo "UFW Status:"
        sudo ufw status verbose
    # Check firewalld (CentOS/RHEL)
    elif command -v firewall-cmd &>/dev/null; then
        echo "Firewalld Status:"
        sudo firewall-cmd --state
        sudo firewall-cmd --list-all
    # Check iptables (Generic)
    else
        echo "IPTables Rules:"
        sudo iptables -L -n
    fi
}

# Basic firewall setup
setup_basic_firewall() {
    echo "⚙️ Setting up basic firewall..."
    
    if command -v ufw &>/dev/null; then
        sudo ufw default deny incoming
        sudo ufw default allow outgoing
        sudo ufw allow ssh
        sudo ufw allow 80/tcp
        sudo ufw allow 443/tcp
        sudo ufw --force enable
        echo "✅ UFW configured"
    fi
}

check_firewall

🕵️ Security Scanning

#!/bin/bash
# Basic security assessment
security_scan() {
    echo "🕵️ Security Scan Report"
    echo "======================="
    
    # Check for open ports
    echo "🔍 Open Ports:"
    ss -tuln | grep LISTEN | head -10
    echo
    
    # Check for suspicious processes
    echo "🚨 Network Processes:"
    ps aux | grep -E "(nc|netcat|nmap)" | grep -v grep
    echo
    
    # Failed login attempts
    echo "🔐 Recent Failed Logins:"
    if [ -f /var/log/auth.log ]; then
        grep "Failed password" /var/log/auth.log | tail -5
    fi
    echo
    
    # Network connections
    echo "🔗 Established Connections:"
    ss -an | grep ESTABLISHED | head -10
}

# Port vulnerability check
check_vulnerable_ports() {
    local DANGEROUS_PORTS=(21 23 135 139 445 1433 3389)
    
    echo "⚠️ Checking for potentially dangerous open ports:"
    for port in "${DANGEROUS_PORTS[@]}"; do
        if ss -tuln | grep ":$port " >/dev/null; then
            echo "🚨 Port $port is open (potentially dangerous)"
        fi
    done
}

security_scan
check_vulnerable_ports

Network Access Control

👥 Access Monitoring

#!/bin/bash
# Monitor network access and connections
monitor_access() {
    echo "👥 Network Access Monitor"
    echo "========================"
    
    # Current SSH sessions
    echo "🔐 Active SSH Sessions:"
    who | grep pts
    echo
    
    # Recent connections
    echo "📊 Recent Connections Summary:"
    ss -an | awk '{print $1, $2}' | sort | uniq -c | sort -nr | head -10
    echo
    
    # Geographic analysis (if geoip available)
    echo "🌍 Connection Sources:"
    ss -an | grep ESTABLISHED | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -5
}

# Intrusion detection basics
simple_ids() {
    echo "🚨 Simple Intrusion Detection"
    echo "============================="
    
    # Check for port scanning
    netstat -an | grep -E ":80|:443|:22" | grep SYN_RECV | wc -l | \
    awk '{if($1>10) print "⚠️ Possible port scan detected: " $1 " SYN_RECV connections"}'
    
    # Check for brute force attempts
    if [ -f /var/log/auth.log ]; then
        failed_attempts=$(grep "Failed password" /var/log/auth.log | \
                         grep "$(date +%b\ %d)" | wc -l)
        if [ $failed_attempts -gt 10 ]; then
            echo "🚨 Possible brute force attack: $failed_attempts failed attempts today"
        fi
    fi
}

monitor_access
simple_ids

⚡ Network Performance Optimization

Optimizing network performance and troubleshooting bottlenecks

📊 Performance Assessment

#!/bin/bash
# Network performance analysis
performance_check() {
    echo "⚡ Network Performance Check"
    echo "==========================="
    
    # Interface speeds
    echo "📡 Interface Speeds:"
    for iface in $(ls /sys/class/net/ | grep -v lo); do
        if [ -f /sys/class/net/$iface/speed ]; then
            speed=$(cat /sys/class/net/$iface/speed 2>/dev/null)
            echo "  $iface: ${speed}Mbps"
        fi
    done
    echo
    
    # TCP settings
    echo "🔧 TCP Configuration:"
    echo "  Congestion Control: $(sysctl -n net.ipv4.tcp_congestion_control)"
    echo "  Window Scaling: $(sysctl -n net.ipv4.tcp_window_scaling)"
    echo "  Timestamps: $(sysctl -n net.ipv4.tcp_timestamps)"
    echo
    
    # Buffer sizes
    echo "📦 Buffer Sizes:"
    echo "  TCP Read: $(sysctl -n net.core.rmem_default) / $(sysctl -n net.core.rmem_max)"
    echo "  TCP Write: $(sysctl -n net.core.wmem_default) / $(sysctl -n net.core.wmem_max)"
}

performance_check

🚀 Performance Optimization

#!/bin/bash
# Network performance tuning
optimize_network() {
    echo "🚀 Optimizing Network Performance"
    echo "================================="
    
    # Backup current settings
    sysctl -a | grep -E "net\.(core|ipv4)" > /tmp/network_backup.conf
    echo "📄 Settings backed up to /tmp/network_backup.conf"
    
    # Optimize TCP settings
    echo "🔧 Optimizing TCP settings..."
    
    # Increase buffer sizes
    sudo sysctl -w net.core.rmem_max=134217728
    sudo sysctl -w net.core.wmem_max=134217728
    sudo sysctl -w net.ipv4.tcp_rmem="4096 16384 134217728"
    sudo sysctl -w net.ipv4.tcp_wmem="4096 65536 134217728"
    
    # Enable TCP window scaling
    sudo sysctl -w net.ipv4.tcp_window_scaling=1
    
    # Use BBR congestion control (if available)
    if sysctl net.ipv4.tcp_available_congestion_control | grep -q bbr; then
        sudo sysctl -w net.ipv4.tcp_congestion_control=bbr
        echo "✅ BBR congestion control enabled"
    fi
    
    echo "✅ Network optimization applied"
    echo "🔄 Reboot recommended for all changes to take effect"
}

# Bandwidth testing
test_bandwidth() {
    echo "📊 Bandwidth Testing"
    echo "==================="
    
    # Download test
    echo "⬇️ Download Test:"
    curl -o /dev/null -s -w "Speed: %{speed_download} bytes/sec\n" \
         http://speedtest.wdc01.softlayer.com/downloads/test10.zip
}

optimize_network
test_bandwidth

Performance Optimization Tips

  • Monitor baseline performance before making changes
  • Test optimizations in non-production environments
  • Use modern congestion control algorithms (BBR, CUBIC)
  • Adjust buffer sizes based on bandwidth-delay product
  • Consider hardware offloading for high-throughput applications

Latency Optimization

⚡ Latency Testing & Optimization

#!/bin/bash
# Comprehensive latency testing
latency_test() {
    local DESTINATIONS=("8.8.8.8" "1.1.1.1" "google.com" "cloudflare.com")
    
    echo "⚡ Latency Analysis"
    echo "=================="
    
    for dest in "${DESTINATIONS[@]}"; do
        echo "🎯 Testing $dest:"
        
        # Basic ping test
        ping_result=$(ping -c 10 $dest 2>/dev/null | tail -1)
        if [ $? -eq 0 ]; then
            echo "  $(echo $ping_result | awk -F'/' '{printf "  Min: %.2fms  Avg: %.2fms  Max: %.2fms\n", $4, $5, $6}')"
        else
            echo "  ❌ Unreachable"
        fi
        
        # Traceroute analysis
        echo "  📍 Route (first 5 hops):"
        traceroute -n -m 5 $dest 2>/dev/null | tail -n +2 | head -5 | \
        awk '{printf "    Hop %s: %s (%sms)\n", $1, $2, $3}'
        echo
    done
}

# Network quality assessment
assess_quality() {
    echo "📊 Network Quality Assessment"
    echo "============================="
    
    # Packet loss test
    echo "📦 Packet Loss Test:"
    loss=$(ping -c 100 8.8.8.8 | grep "packet loss" | awk '{print $6}')
    echo "  Packet Loss: $loss"
    
    # Jitter measurement
    echo "📈 Jitter Measurement:"
    ping -c 20 8.8.8.8 | grep "time=" | awk -F'time=' '{print $2}' | \
    awk '{times[NR]=$1} END {
        sum=0; for(i=1;i<=NR;i++) sum+=times[i]; avg=sum/NR;
        sumsq=0; for(i=1;i<=NR;i++) sumsq+=(times[i]-avg)^2;
        printf "  Average: %.2fms  Jitter: %.2fms\n", avg, sqrt(sumsq/NR)
    }'
}

latency_test
assess_quality

📚 Quick Reference

Essential commands and troubleshooting guide

🔧 Essential Commands

# Interface management
ip addr show
ip link set eth0 up/down
ip route show

# Connectivity testing
ping -c 3 google.com
traceroute google.com
nslookup domain.com

# Port scanning
ss -tuln
netstat -an
nc -zv host port

🚨 Troubleshooting Steps

# 1. Check physical connection
ethtool eth0 | grep Link

# 2. Verify IP configuration
ip addr show eth0

# 3. Test local connectivity
ping 192.168.1.1

# 4. Check DNS resolution
nslookup google.com

# 5. Test internet access
curl -I http://google.com

📊 Monitoring Commands

# Real-time monitoring
watch -n 1 'ss -s'
iftop -i eth0
nethogs

# Log analysis
tail -f /var/log/syslog
journalctl -u networking

# Performance metrics
iperf3 -s/-c server
speedtest-cli