Skip to content

Instantly share code, notes, and snippets.

@gffhcks
Created January 1, 2025 20:57
Show Gist options
  • Save gffhcks/c02d3a83f146006eb7b7b14d61fe5986 to your computer and use it in GitHub Desktop.
Save gffhcks/c02d3a83f146006eb7b7b14d61fe5986 to your computer and use it in GitHub Desktop.
Simple network monitor
import platform
import subprocess
import time
from datetime import datetime
def check_internet():
try:
# Use nslookup to perform a DNS lookup for google.com
result = subprocess.run(["nslookup", "-type=ns", "google.com", "8.8.8.8"], capture_output=True, text=True, timeout=5)
return result.returncode == 0
except subprocess.TimeoutExpired:
console_message("DNS lookup timed out")
return False
except subprocess.CalledProcessError as e:
console_message(f"Error during DNS lookup: {e}")
return False
except Exception as e:
console_message(f"Unexpected error during DNS lookup: {e}")
return False
def run_command(command):
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, universal_newlines=True)
return output.strip()
except subprocess.CalledProcessError as e:
return f"Error: {e.output.strip()}"
def troubleshoot():
os_name = platform.system().lower()
results = []
if os_name == "windows":
results.append(("IP Configuration", run_command(["ipconfig", "/all"])))
results.append(("Connection Test", run_command(["curl", "-I", "-s", "-m", "5", f"http://1.1.1.1"])))
results.append(("Trace Route", run_command(["tracert", "google.com"])))
elif os_name == "darwin": # macOS
results.append(("IP Configuration", run_command(["ifconfig"])))
results.append(("Connection Test", run_command(["curl", "-I", "--connect-timeout", "5", f"http://1.1.1.1"])))
results.append(("Trace Route", run_command(["traceroute", "google.com"])))
else:
results.append("Unsupported OS")
return results
def log_message(message, log_file):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_entry = f"{timestamp} - {message}"
print(log_entry)
with open(log_file, "a+") as f:
f.write(log_entry + "\n")
def console_message(message):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_entry = f"{timestamp} - {message}"
print(log_entry)
def main():
log_file = "network_monitor.log"
console_message("Network monitoring started. Press Ctrl+C to stop.")
last_status = True
while True:
current_status = check_internet()
if current_status != last_status:
if current_status:
log_message("Internet connection restored.", log_file)
else:
log_message("Internet connection lost. Running troubleshooting...", log_file)
troubleshooting_results = troubleshoot()
for title, result in troubleshooting_results:
log_message(f"{title}:\n{result}", log_file)
log_message("-" * 50, log_file)
last_status = current_status
time.sleep(5) # Check every 5 seconds
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
console_message("Monitoring stopped.")
@gffhcks
Copy link
Author

gffhcks commented Jan 1, 2025

Threw this together with help from an AI coding assistant when I needed to track intermittent failures on my home network. (Turned out the cable modem was overheating inside a cabinet.)

I'm sure there are better ways to do this, but it works. Feel free to add improvement suggestions in the comments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment