Skip to content

Instantly share code, notes, and snippets.

@collinschaafsma
Created October 9, 2024 19:26
Show Gist options
  • Save collinschaafsma/3537127dc5d989a484525a5ef697bb00 to your computer and use it in GitHub Desktop.
Save collinschaafsma/3537127dc5d989a484525a5ef697bb00 to your computer and use it in GitHub Desktop.
import subprocess
import time
import logging
from datetime import datetime
# Set up logging
logging.basicConfig(filename='network_log.txt', level=logging.INFO,
format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
# File to store outages
OUTAGE_FILE = 'network_outages.txt'
def check_network():
try:
# Ping Google's DNS server
subprocess.check_output(
["ping", "-c", "1", "8.8.8.8"], stderr=subprocess.STDOUT, universal_newlines=True)
return True
except subprocess.CalledProcessError:
return False
def write_outage(message):
with open(OUTAGE_FILE, 'a') as f:
f.write(f"{datetime.now()} - {message}\n")
def monitor_network():
previous_state = True
outage_start = None
while True:
current_state = check_network()
if previous_state and not current_state:
# Connection lost
outage_start = datetime.now()
message = "Network connection lost"
logging.info(message)
write_outage(message)
print(f"{outage_start} - {message}")
elif not previous_state and current_state:
# Connection restored
outage_end = datetime.now()
duration = outage_end - outage_start
message = f"Network connection restored. Outage duration: {duration}"
logging.info(message)
write_outage(message)
print(f"{outage_end} - {message}")
previous_state = current_state
time.sleep(1) # Wait for 1 seconds before checking again
if __name__ == "__main__":
print("Network monitoring started. Press Ctrl+C to stop.")
print(f"Outages will be logged to {OUTAGE_FILE}")
try:
monitor_network()
except KeyboardInterrupt:
print("\nMonitoring stopped.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment