Configure network interface monitoring with ICMP ping and connectivity testing

Beginner 45 min Apr 03, 2026 136 views
Ubuntu 24.04 Ubuntu 22.04 Debian 12 AlmaLinux 9 Rocky Linux 9 Fedora 41

Set up automated network connectivity monitoring using ICMP ping tests with email alerts for interface failures. Create comprehensive network health checks and reporting for production systems.

Prerequisites

  • Root or sudo access
  • Basic understanding of networking concepts
  • Email server configured for alerts

What this solves

Network interface failures and connectivity issues can cause critical service outages without immediate detection. This tutorial shows you how to set up continuous ICMP ping monitoring to detect network interface problems, connectivity failures, and routing issues before they impact your users.

Step-by-step configuration

Update system packages

Start by updating your package manager to ensure you get the latest monitoring tools and dependencies.

sudo apt update && sudo apt upgrade -y
sudo dnf update -y

Install ping monitoring tools

Install the essential network monitoring utilities including advanced ping tools, mail utilities for alerts, and system monitoring packages.

sudo apt install -y iputils-ping fping hping3 mailutils postfix bc
sudo dnf install -y iputils fping hping3 mailx postfix bc

Configure mail system for alerts

Set up a basic mail configuration to send email alerts when connectivity issues are detected.

sudo dpkg-reconfigure postfix

Select "Internet Site" and enter your domain name. For production systems, configure with your actual SMTP relay.

Create monitoring directory structure

Set up organized directories for monitoring scripts, logs, and configuration files with proper permissions.

sudo mkdir -p /opt/network-monitor/{scripts,logs,config}
sudo mkdir -p /var/log/network-monitor
sudo chown root:root /opt/network-monitor
sudo chmod 755 /opt/network-monitor
sudo chmod 755 /opt/network-monitor/{scripts,logs,config}
Never use chmod 777. It gives every user on the system full access to your files. The 755 permissions allow the owner full access while giving others read and execute permissions only.

Create ping monitoring configuration

Define the targets and thresholds for your network monitoring. This configuration includes internal gateways, external DNS servers, and critical services.

# Network monitoring targets configuration

Format: TARGET_NAME:IP_ADDRESS:DESCRIPTION

DEFAULT_GATEWAY:192.168.1.1:Local network gateway DNS_PRIMARY:8.8.8.8:Google DNS primary DNS_SECONDARY:1.1.1.1:Cloudflare DNS INTERNET_CHECK:203.0.113.1:External connectivity test LOCAL_SERVER:192.168.1.100:Internal application server

Monitoring thresholds

PING_TIMEOUT=5 FAIL_THRESHOLD=3 CHECK_INTERVAL=60 ALERT_EMAIL=admin@example.com

Create the main monitoring script

Build a comprehensive monitoring script that performs ping tests, tracks failures, and sends alerts when thresholds are exceeded.

#!/bin/bash

Network Interface Ping Monitor

Monitors network connectivity and sends alerts on failures

CONFIG_FILE="/opt/network-monitor/config/targets.conf" LOG_FILE="/var/log/network-monitor/ping-monitor.log" STATE_DIR="/opt/network-monitor/logs" DATE=$(date '+%Y-%m-%d %H:%M:%S')

Load configuration

source "$CONFIG_FILE"

Function to log messages

log_message() { echo "[$DATE] $1" >> "$LOG_FILE" }

Function to send email alert

send_alert() { local target="$1" local status="$2" local message="$3" subject="Network Alert: $target $status" { echo "Network Monitoring Alert" echo "========================" echo "Target: $target" echo "Status: $status" echo "Time: $DATE" echo "Message: $message" echo "" echo "Server: $(hostname)" echo "IP Address: $(hostname -I | awk '{print $1}')" } | mail -s "$subject" "$ALERT_EMAIL" }

Function to test connectivity

test_connectivity() { local name="$1" local ip="$2" local description="$3" local state_file="$STATE_DIR/${name}.state" # Perform ping test if ping -c 3 -W "$PING_TIMEOUT" "$ip" >/dev/null 2>&1; then # Success - reset failure counter echo "0" > "$state_file" log_message "SUCCESS: $name ($ip) - $description" # Check if this is recovery from failure if [ -f "$STATE_DIR/${name}.failed" ]; then send_alert "$name" "RECOVERED" "Connectivity to $ip ($description) has been restored" rm -f "$STATE_DIR/${name}.failed" log_message "RECOVERY: $name ($ip) connectivity restored" fi else # Failure - increment counter local fail_count=0 if [ -f "$state_file" ]; then fail_count=$(cat "$state_file") fi fail_count=$((fail_count + 1)) echo "$fail_count" > "$state_file" log_message "FAILURE: $name ($ip) - $description (attempt $fail_count)" # Send alert if threshold exceeded and not already alerted if [ "$fail_count" -ge "$FAIL_THRESHOLD" ] && [ ! -f "$STATE_DIR/${name}.failed" ]; then send_alert "$name" "FAILED" "Connectivity to $ip ($description) failed after $fail_count attempts" touch "$STATE_DIR/${name}.failed" log_message "ALERT: $name ($ip) threshold exceeded, alert sent" fi fi }

Function to test network interfaces

test_interfaces() { log_message "Starting interface connectivity tests" # Read targets from config file while IFS=':' read -r name ip description; do # Skip comments and empty lines [[ "$name" =~ ^#.*$ ]] && continue [[ -z "$name" ]] && continue # Skip configuration variables [[ "$name" =~ ^[A-Z_]+=.*$ ]] && continue test_connectivity "$name" "$ip" "$description" sleep 1 done < "$CONFIG_FILE" log_message "Interface connectivity tests completed" }

Function to generate health report

generate_report() { local report_file="/var/log/network-monitor/daily-report-$(date +%Y%m%d).log" { echo "Network Health Report - $(date)" echo "======================================" echo "" echo "Current Interface Status:" ip -br addr show | grep -E "^(eth|ens|enp)" | while read iface state addr; do echo " $iface: $state ($addr)" done echo "" echo "Routing Table:" ip route show | head -10 echo "" echo "Current Connectivity Status:" while IFS=':' read -r name ip description; do [[ "$name" =~ ^#.*$ ]] && continue [[ -z "$name" ]] && continue [[ "$name" =~ ^[A-Z_]+=.*$ ]] && continue if ping -c 1 -W 2 "$ip" >/dev/null 2>&1; then echo " ✓ $name ($ip): OK" else echo " ✗ $name ($ip): FAILED" fi done < "$CONFIG_FILE" echo "" echo "Recent Failures (last 24 hours):" grep "FAILURE\|ALERT" "$LOG_FILE" | tail -20 } > "$report_file" log_message "Daily health report generated: $report_file" }

Main execution

case "${1:-monitor}" in "monitor") test_interfaces ;; "report") generate_report ;; "test") echo "Testing connectivity to all targets..." test_interfaces echo "Test completed. Check $LOG_FILE for results." ;; *) echo "Usage: $0 [monitor|report|test]" echo " monitor: Run connectivity tests (default)" echo " report: Generate daily health report" echo " test: Run tests with console output" exit 1 ;; esac

Set script permissions

Configure proper permissions for the monitoring script to ensure it can execute but remains secure.

sudo chmod 755 /opt/network-monitor/scripts/ping-monitor.sh
sudo chown root:root /opt/network-monitor/scripts/ping-monitor.sh

Create advanced ping monitoring script

Build a secondary script that provides detailed network interface analysis and performance metrics.

#!/bin/bash

Network Interface Analyzer

Provides detailed interface statistics and performance metrics

LOG_FILE="/var/log/network-monitor/interface-analysis.log" DATE=$(date '+%Y-%m-%d %H:%M:%S')

Function to analyze interface performance

analyze_interface() { local interface="$1" echo "Interface Analysis: $interface" >> "$LOG_FILE" echo "============================" >> "$LOG_FILE" echo "Timestamp: $DATE" >> "$LOG_FILE" # Interface status echo "Status: $(cat /sys/class/net/$interface/operstate 2>/dev/null || echo 'unknown')" >> "$LOG_FILE" # Get interface statistics if [ -d "/sys/class/net/$interface/statistics" ]; then echo "RX Packets: $(cat /sys/class/net/$interface/statistics/rx_packets)" >> "$LOG_FILE" echo "TX Packets: $(cat /sys/class/net/$interface/statistics/tx_packets)" >> "$LOG_FILE" echo "RX Bytes: $(cat /sys/class/net/$interface/statistics/rx_bytes)" >> "$LOG_FILE" echo "TX Bytes: $(cat /sys/class/net/$interface/statistics/tx_bytes)" >> "$LOG_FILE" echo "RX Errors: $(cat /sys/class/net/$interface/statistics/rx_errors)" >> "$LOG_FILE" echo "TX Errors: $(cat /sys/class/net/$interface/statistics/tx_errors)" >> "$LOG_FILE" echo "RX Dropped: $(cat /sys/class/net/$interface/statistics/rx_dropped)" >> "$LOG_FILE" echo "TX Dropped: $(cat /sys/class/net/$interface/statistics/tx_dropped)" >> "$LOG_FILE" fi # Ping test to gateway with detailed statistics local gateway=$(ip route | grep "^default.*$interface" | awk '{print $3}' | head -1) if [ -n "$gateway" ]; then echo "Gateway: $gateway" >> "$LOG_FILE" ping_result=$(ping -c 10 -i 0.2 "$gateway" 2>&1) echo "Gateway Ping Results:" >> "$LOG_FILE" echo "$ping_result" | grep -E "(packets transmitted|rtt)" >> "$LOG_FILE" fi echo "" >> "$LOG_FILE" }

Main execution

echo "[$DATE] Starting interface analysis" >> "$LOG_FILE"

Analyze all active network interfaces

for interface in $(ip -br link show | grep -E "^(eth|ens|enp)" | awk '{print $1}'); do analyze_interface "$interface" done echo "[$DATE] Interface analysis completed" >> "$LOG_FILE"

Set permissions for analyzer script

Configure secure permissions for the interface analyzer script.

sudo chmod 755 /opt/network-monitor/scripts/interface-analyzer.sh
sudo chown root:root /opt/network-monitor/scripts/interface-analyzer.sh

Configure log rotation

Set up log rotation to prevent monitoring logs from consuming excessive disk space.

/var/log/network-monitor/*.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 644 root root
    postrotate
        /bin/systemctl reload rsyslog > /dev/null 2>&1 || true
    endscript
}

Set up automated monitoring with cron

Configure cron jobs to run continuous monitoring, generate reports, and perform interface analysis. This ensures comprehensive network monitoring around the clock.

sudo crontab -e

Add the following cron entries:

# Network connectivity monitoring every minute
    * /opt/network-monitor/scripts/ping-monitor.sh monitor

Interface analysis every 5 minutes

/5 * /opt/network-monitor/scripts/interface-analyzer.sh

Daily health report at 6 AM

0 6 * /opt/network-monitor/scripts/ping-monitor.sh report

Weekly summary report (Sundays at 7 AM)

0 7 0 /opt/network-monitor/scripts/weekly-summary.sh

Create weekly summary script

Build a comprehensive weekly reporting script that analyzes trends and provides insights into network performance.

#!/bin/bash

Weekly Network Summary Report

Generates comprehensive weekly analysis

REPORT_FILE="/var/log/network-monitor/weekly-summary-$(date +%Y%m%d).log" CONFIG_FILE="/opt/network-monitor/config/targets.conf" LOG_FILE="/var/log/network-monitor/ping-monitor.log"

Load configuration

source "$CONFIG_FILE" { echo "Weekly Network Summary Report" echo "Generated: $(date)" echo "======================================" echo "" # Summary statistics echo "Summary Statistics (Last 7 Days):" echo "----------------------------------" total_checks=$(grep -c "SUCCESS\|FAILURE" "$LOG_FILE" | tail -1) failures=$(grep -c "FAILURE" "$LOG_FILE" | tail -1) success_rate=$(echo "scale=2; ($total_checks - $failures) / $total_checks * 100" | bc) echo "Total connectivity checks: $total_checks" echo "Failures detected: $failures" echo "Success rate: ${success_rate}%" echo "" # Target-specific analysis echo "Per-Target Analysis:" echo "-------------------" while IFS=':' read -r name ip description; do [[ "$name" =~ ^#.*$ ]] && continue [[ -z "$name" ]] && continue [[ "$name" =~ ^[A-Z_]+=.*$ ]] && continue target_failures=$(grep "$name.*FAILURE" "$LOG_FILE" | wc -l) target_total=$(grep "$name.SUCCESS\|$name.FAILURE" "$LOG_FILE" | wc -l) if [ "$target_total" -gt 0 ]; then target_success_rate=$(echo "scale=2; ($target_total - $target_failures) / $target_total * 100" | bc) echo "$name ($ip): ${target_success_rate}% success rate ($target_failures failures)" fi done < "$CONFIG_FILE" echo "" echo "Critical Events This Week:" echo "-------------------------" grep "ALERT\|RECOVERY" "$LOG_FILE" | tail -20 echo "" echo "Interface Statistics:" echo "-------------------" for interface in $(ip -br link show | grep -E "^(eth|ens|enp)" | awk '{print $1}'); do if [ -d "/sys/class/net/$interface" ]; then state=$(cat "/sys/class/net/$interface/operstate" 2>/dev/null || echo "unknown") rx_errors=$(cat "/sys/class/net/$interface/statistics/rx_errors" 2>/dev/null || echo "0") tx_errors=$(cat "/sys/class/net/$interface/statistics/tx_errors" 2>/dev/null || echo "0") echo "$interface: $state (RX errors: $rx_errors, TX errors: $tx_errors)" fi done } > "$REPORT_FILE"

Email the weekly report

if [ -n "$ALERT_EMAIL" ]; then mail -s "Weekly Network Summary - $(hostname)" "$ALERT_EMAIL" < "$REPORT_FILE" fi echo "Weekly summary generated: $REPORT_FILE"

Set permissions for weekly summary script

Configure proper permissions for the weekly summary script.

sudo chmod 755 /opt/network-monitor/scripts/weekly-summary.sh
sudo chown root:root /opt/network-monitor/scripts/weekly-summary.sh

Create systemd service for monitoring

For more reliable monitoring, create a systemd service that can be managed and monitored by the system.

[Unit]
Description=Network Interface Ping Monitor
After=network.target

[Service]
Type=simple
ExecStart=/opt/network-monitor/scripts/ping-monitor.sh monitor
ExecReload=/bin/kill -HUP $MAINPID
Restart=always
RestartSec=60
User=root
Group=root

Security settings

PrivateTmp=true ProtectSystem=strict ReadWritePaths=/var/log/network-monitor /opt/network-monitor/logs [Install] WantedBy=multi-user.target

Enable and start the monitoring service

Enable the systemd service to ensure monitoring starts automatically on boot.

sudo systemctl daemon-reload
sudo systemctl enable network-monitor.service
sudo systemctl start network-monitor.service
sudo systemctl status network-monitor.service

Verify your setup

Confirm that your network monitoring system is working correctly with these verification commands.

# Check monitoring service status
sudo systemctl status network-monitor.service

View recent monitoring logs

sudo tail -f /var/log/network-monitor/ping-monitor.log

Test manual monitoring

sudo /opt/network-monitor/scripts/ping-monitor.sh test

Generate test report

sudo /opt/network-monitor/scripts/ping-monitor.sh report

Check cron jobs are scheduled

sudo crontab -l

Verify log rotation is configured

ls -la /etc/logrotate.d/network-monitor

Test email functionality

echo "Test network monitoring email" | mail -s "Test Subject" admin@example.com

You should see active monitoring logs being generated and the systemd service running without errors. The cron jobs should be scheduled and log files should be created in the monitoring directory.

Advanced configuration options

Custom ping parameters

Modify the monitoring script to use custom ping parameters for specific network environments.

# Advanced ping monitoring configuration

Custom ping parameters for different target types

GATEWAY_PING_OPTS="-c 5 -i 0.5 -W 3" EXTERNAL_PING_OPTS="-c 3 -i 1.0 -W 5" INTERNAL_PING_OPTS="-c 3 -i 0.2 -W 2"

Quality thresholds

LATENCY_WARNING=100 # milliseconds LATENCY_CRITICAL=500 # milliseconds PACKET_LOSS_WARNING=5 # percentage PACKET_LOSS_CRITICAL=25 # percentage

Enhanced monitoring features

ENABLE_MTU_DISCOVERY=true ENABLE_TRACE_ROUTE=false ENABLE_BANDWIDTH_TEST=false

Integration with existing monitoring

Connect your ping monitoring with existing monitoring systems like Netdata or Nagios. You can also extend the monitoring to work with SNMP monitoring systems for comprehensive network visibility.

Common issues

SymptomCauseFix
Permission denied on log filesIncorrect file ownershipsudo chown -R root:root /var/log/network-monitor
Email alerts not sendingPostfix not configuredsudo dpkg-reconfigure postfix and test with echo "test" | mail user@domain.com
Monitoring script fails silentlyMissing dependenciesVerify all packages installed: dpkg -l | grep -E "fping|mailutils|bc"
Cron jobs not executingCron service stoppedsudo systemctl status cron && sudo systemctl start cron
False positive alertsThreshold too sensitiveIncrease FAIL_THRESHOLD in targets.conf
High CPU usage from monitoringCheck interval too frequentIncrease CHECK_INTERVAL in configuration
Log files growing too largeLog rotation not workingsudo logrotate -f /etc/logrotate.d/network-monitor
Network interface not detectedInterface naming differsCheck with ip link show and update script regex

Next steps

Automated install script

Run this to automate the entire setup

#ping monitoring #network connectivity #interface monitoring #network health check #icmp monitoring

Need help?

Don't want to manage this yourself?

We handle infrastructure for businesses that depend on uptime. From initial setup to ongoing operations.

Talk to an engineer