Internet_Connectivity_Check/connectivity_ping.sh
2023-09-12 23:16:28 +01:00

54 lines
1.4 KiB
Bash
Executable File

#!/bin/bash
set -x
# Function to get the default gateway IP address
get_gateway_ip() {
gateway_ip=$(ip route | awk '/default/ {print $3}')
echo "$gateway_ip"
}
# Assign the gateway IP address automatically
gateway_ip=$(get_gateway_ip)
# Array of IP addresses to ping, including the gateway IP
ip_addresses=("9.9.9.9" "8.8.8.8" "1.1.1.1")
if [ -n "$gateway_ip" ]; then
ip_addresses+=("$gateway_ip")
fi
# CSV file to store ping results
csv_file="ping_data.csv"
# Check if the CSV file already exists
if [ ! -e "$csv_file" ]; then
# Create the CSV file with a header including a timestamp column
echo "Timestamp,IP Address,Status" > "$csv_file"
fi
# Function to ping an IP address and log the result to the CSV file
ping_ip() {
ip="$1"
result=$(ping -c 4 -i 0.2 -q "$ip" | tail -1)
if [ $? -eq 0 ]; then
if [ "$ip" == "$gateway_ip" ]; then
status="1" # Gateway IP is "1" for successful pings
else
status="2" # Other IP addresses are "2" for successful pings
fi
else
status="0" # Network is not reachable
fi
timestamp=$(date +"%Y-%m-%d %H:%M:%S")
echo "$timestamp,$ip,$status" >> "$csv_file"
}
# Loop through the IP addresses and ping them periodically
while true; do
for ip in "${ip_addresses[@]}"; do
ping_ip "$ip"
done
sleep 60 # Ping every 60 seconds, adjust as needed
done