Files
Homelab/proxmox/network_check.sh

65 lines
2.1 KiB
Bash

#!/bin/bash
# A script to check for internet connectivity and reset the USB network adapter or reboot if the connection is down.
# The IP address of your local gateway (router).
GATEWAY_IP="192.168.1.1"
# The IP address to ping to check for an external internet connection.
PING_IP="8.8.8.8"
# The number of pings to send.
PING_COUNT=1
# The USB bus and device number of the network adapter.
# Use 'lsusb' to find these values for your specific device.
USB_BUS="002"
USB_DEV="003"
# The path to the USB device.
USB_DEVICE_PATH="/dev/bus/usb/$USB_BUS/$USB_DEV"
# Log file
LOG_FILE="/var/log/network_check.log"
# Function to log messages
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}
# Check if the script is running as root.
if [ "$(id -u)" -ne 0 ]; then
log "This script must be run as root."
exit 1
fi
# 1. Check for local network connectivity by pinging the gateway.
if ! ping -c "$PING_COUNT" "$GATEWAY_IP" > /dev/null 2>&1; then
log "Local network connection is down (cannot ping gateway $GATEWAY_IP). This indicates a problem with the host's network adapter."
log "Attempting to reset the USB adapter."
# Attempt to reset the USB device.
if [ -e "$USB_DEVICE_PATH" ]; then
/usr/bin/usbreset "$USB_DEVICE_PATH"
sleep 10 # Wait for the device to reinitialize.
# Check the connection again.
if ! ping -c "$PING_COUNT" "$GATEWAY_IP" > /dev/null 2>&1; then
log "USB reset failed to restore the local connection. Rebooting the system."
/sbin/reboot
else
log "USB reset successful. Local network connection is back up."
fi
else
log "USB device not found at $USB_DEVICE_PATH. Rebooting the system."
/sbin/reboot
fi
else
# 2. If the local network is up, check for external internet connectivity.
if ! ping -c "$PING_COUNT" "$PING_IP" > /dev/null 2>&1; then
log "Local network is up, but internet connection is down (cannot ping $PING_IP). This is likely a router or ISP issue. No action taken."
else
log "Network connection is up."
fi
fi