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
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
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}
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
| Symptom | Cause | Fix |
|---|---|---|
| Permission denied on log files | Incorrect file ownership | sudo chown -R root:root /var/log/network-monitor |
| Email alerts not sending | Postfix not configured | sudo dpkg-reconfigure postfix and test with echo "test" | mail user@domain.com |
| Monitoring script fails silently | Missing dependencies | Verify all packages installed: dpkg -l | grep -E "fping|mailutils|bc" |
| Cron jobs not executing | Cron service stopped | sudo systemctl status cron && sudo systemctl start cron |
| False positive alerts | Threshold too sensitive | Increase FAIL_THRESHOLD in targets.conf |
| High CPU usage from monitoring | Check interval too frequent | Increase CHECK_INTERVAL in configuration |
| Log files growing too large | Log rotation not working | sudo logrotate -f /etc/logrotate.d/network-monitor |
| Network interface not detected | Interface naming differs | Check with ip link show and update script regex |
Next steps
Automated install script
Run this to automate the entire setup
#!/usr/bin/env bash
set -euo pipefail
# Network Interface ICMP Ping Monitor Installation Script
# Installs and configures continuous network monitoring with ping tests
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# Default configuration
DEFAULT_GATEWAY="${1:-192.168.1.1}"
ALERT_EMAIL="${2:-admin@$(hostname -d 2>/dev/null || echo 'example.com')}"
# Usage message
usage() {
echo "Usage: $0 [gateway_ip] [alert_email]"
echo "Example: $0 192.168.1.1 admin@company.com"
exit 1
}
# Logging functions
log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
# Cleanup function
cleanup() {
log_error "Installation failed. Cleaning up..."
rm -rf /opt/network-monitor /var/log/network-monitor 2>/dev/null || true
}
trap cleanup ERR
# Check if running as root
if [[ $EUID -ne 0 ]]; then
log_error "This script must be run as root or with sudo"
exit 1
fi
# Detect distribution and package manager
log_info "[1/8] Detecting system distribution..."
if [ -f /etc/os-release ]; then
. /etc/os-release
case "$ID" in
ubuntu|debian)
PKG_MGR="apt"
PKG_INSTALL="apt install -y"
PKG_UPDATE="apt update && apt upgrade -y"
MAIL_PKG="mailutils"
;;
almalinux|rocky|centos|rhel|ol)
PKG_MGR="dnf"
PKG_INSTALL="dnf install -y"
PKG_UPDATE="dnf update -y"
MAIL_PKG="mailx"
;;
fedora)
PKG_MGR="dnf"
PKG_INSTALL="dnf install -y"
PKG_UPDATE="dnf update -y"
MAIL_PKG="mailx"
;;
amzn)
PKG_MGR="yum"
PKG_INSTALL="yum install -y"
PKG_UPDATE="yum update -y"
MAIL_PKG="mailx"
;;
*)
log_error "Unsupported distribution: $ID"
exit 1
;;
esac
log_info "Detected: $PRETTY_NAME ($PKG_MGR)"
else
log_error "Cannot detect distribution (/etc/os-release not found)"
exit 1
fi
# Update system packages
log_info "[2/8] Updating system packages..."
$PKG_UPDATE
# Install monitoring tools
log_info "[3/8] Installing network monitoring tools..."
$PKG_INSTALL iputils-ping fping bc postfix $MAIL_PKG
# Handle hping3 availability
if ! $PKG_INSTALL hping3 2>/dev/null; then
log_warn "hping3 not available in repositories, continuing without it"
fi
# Create directory structure
log_info "[4/8] Creating monitoring directory structure..."
mkdir -p /opt/network-monitor/{scripts,logs,config}
mkdir -p /var/log/network-monitor
chown -R root:root /opt/network-monitor /var/log/network-monitor
chmod 755 /opt/network-monitor
chmod 755 /opt/network-monitor/{scripts,logs,config}
chmod 755 /var/log/network-monitor
# Create configuration file
log_info "[5/8] Creating monitoring configuration..."
cat > /opt/network-monitor/config/targets.conf << EOF
# Network monitoring targets configuration
# Format: TARGET_NAME:IP_ADDRESS:DESCRIPTION
DEFAULT_GATEWAY=$DEFAULT_GATEWAY:Local network gateway
DNS_PRIMARY:8.8.8.8:Google DNS primary
DNS_SECONDARY:1.1.1.1:Cloudflare DNS
INTERNET_CHECK:4.2.2.2:Level3 DNS
# Monitoring thresholds
PING_TIMEOUT=5
FAIL_THRESHOLD=3
CHECK_INTERVAL=60
ALERT_EMAIL=$ALERT_EMAIL
EOF
chmod 644 /opt/network-monitor/config/targets.conf
# Create main monitoring script
log_info "[6/8] Creating monitoring script..."
cat > /opt/network-monitor/scripts/ping-monitor.sh << 'EOF'
#!/bin/bash
# Network Interface Ping Monitor
CONFIG_FILE="/opt/network-monitor/config/targets.conf"
LOG_FILE="/var/log/network-monitor/ping-monitor.log"
STATE_DIR="/opt/network-monitor/logs"
# Load configuration
if [ -f "$CONFIG_FILE" ]; then
source "$CONFIG_FILE"
else
echo "Configuration file not found: $CONFIG_FILE"
exit 1
fi
# Function to log messages
log_message() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $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 '+%Y-%m-%d %H:%M:%S')"
echo "Message: $message"
echo ""
echo "Server: $(hostname)"
echo "IP Address: $(hostname -I | awk '{print $1}')"
} | mail -s "$subject" "$ALERT_EMAIL" 2>/dev/null || echo "Failed to send email alert"
}
# Function to test connectivity
test_connectivity() {
local name="$1"
local ip="$2"
local description="$3"
local state_file="$STATE_DIR/${name}.state"
if ping -c 3 -W "$PING_TIMEOUT" "$ip" >/dev/null 2>&1; then
echo "0" > "$state_file"
log_message "SUCCESS: $name ($ip) - $description"
if [ -f "$STATE_DIR/${name}.failed" ]; then
send_alert "$name" "RECOVERED" "$description connectivity restored"
rm -f "$STATE_DIR/${name}.failed"
fi
else
local failures=$(cat "$state_file" 2>/dev/null || echo "0")
failures=$((failures + 1))
echo "$failures" > "$state_file"
log_message "FAILED: $name ($ip) - $description (failure $failures/$FAIL_THRESHOLD)"
if [ "$failures" -ge "$FAIL_THRESHOLD" ] && [ ! -f "$STATE_DIR/${name}.failed" ]; then
touch "$STATE_DIR/${name}.failed"
send_alert "$name" "DOWN" "$description unreachable after $failures attempts"
fi
fi
}
# Main monitoring loop
while read -r line; do
[[ $line =~ ^#.*$ || -z $line ]] && continue
[[ $line =~ ^[A-Z_]+=.*$ ]] && continue
IFS=':' read -r name ip description <<< "$line"
test_connectivity "$name" "$ip" "$description"
done < "$CONFIG_FILE"
EOF
chmod 755 /opt/network-monitor/scripts/ping-monitor.sh
# Create systemd timer and service
log_info "[7/8] Setting up systemd service and timer..."
cat > /etc/systemd/system/network-monitor.service << EOF
[Unit]
Description=Network Interface Ping Monitor
After=network.target
[Service]
Type=oneshot
ExecStart=/opt/network-monitor/scripts/ping-monitor.sh
User=root
Group=root
EOF
cat > /etc/systemd/system/network-monitor.timer << EOF
[Unit]
Description=Network Monitor Timer
Requires=network-monitor.service
[Timer]
OnCalendar=*:*:00
Persistent=true
[Install]
WantedBy=timers.target
EOF
# Enable and start the timer
systemctl daemon-reload
systemctl enable network-monitor.timer
systemctl start network-monitor.timer
# Basic postfix configuration
log_info "[8/8] Configuring mail system..."
if [ "$ID" = "ubuntu" ] || [ "$ID" = "debian" ]; then
debconf-set-selections <<< "postfix postfix/mailname string $(hostname -f)"
debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Internet Site'"
fi
systemctl enable postfix
systemctl restart postfix
# Verification
log_info "Performing verification checks..."
if systemctl is-active --quiet network-monitor.timer; then
log_info "✓ Network monitor timer is active"
else
log_error "✗ Network monitor timer failed to start"
exit 1
fi
if [ -f /opt/network-monitor/scripts/ping-monitor.sh ]; then
log_info "✓ Monitoring script created successfully"
else
log_error "✗ Monitoring script not found"
exit 1
fi
# Run initial test
log_info "Running initial connectivity test..."
/opt/network-monitor/scripts/ping-monitor.sh
log_info "Installation completed successfully!"
log_info "Monitor logs: tail -f /var/log/network-monitor/ping-monitor.log"
log_info "Service status: systemctl status network-monitor.timer"
log_info "Configuration: /opt/network-monitor/config/targets.conf"
Review the script before running. Execute with: bash install.sh