Created
April 1, 2024 16:32
-
-
Save recklessop/d93efa008f5b0a45046ffbee917c5bd8 to your computer and use it in GitHub Desktop.
script to watch for traceroute timeouts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import subprocess | |
import time | |
import re | |
from datetime import datetime | |
def parse_traceroute_output(output): | |
# Adjusted regex pattern to also capture timeout lines (e.g., '* * *') | |
pattern = re.compile(r"(\d+)\s+([\w\.\-]+|\*\s\*\s\*)\s*(?:\(([\d\.]+)\))?\s*([\d\.]+ ms)?") | |
hops = [] | |
for line in output.splitlines(): | |
match = pattern.search(line) | |
if match: | |
hop_num, host, ip, latency = match.groups() | |
if host.strip() == "* * *": | |
hops.append((hop_num, "timeout", "timeout", "timeout")) | |
else: | |
hops.append((hop_num, host, ip or "N/A", latency or "timeout")) | |
return hops | |
def log_traceroute(hops, log_file="traceroute_log.txt"): | |
with open(log_file, "a") as file: | |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
for hop in hops: | |
if hop[1] == "timeout": | |
file.write(f"{timestamp}, Hop {hop[0]}: Timeout\n") | |
else: | |
file.write(f"{timestamp}, Hop {hop[0]}: {hop[1]} ({hop[2]}) {hop[3]}\n") | |
def run_traceroute(target): | |
# Replace 'traceroute' with 'tracert' on Windows | |
command = ['traceroute', target] | |
try: | |
# Run the traceroute command | |
output = subprocess.check_output(command, text=True) | |
return output | |
except subprocess.CalledProcessError as e: | |
print(f"Error running traceroute: {e}") | |
return "" | |
def main(target, interval=60, duration=3600): | |
start_time = time.time() | |
while time.time() - start_time < duration: | |
output = run_traceroute(target) | |
hops = parse_traceroute_output(output) | |
log_traceroute(hops) | |
time.sleep(interval) | |
if __name__ == "__main__": | |
target = "1.1.1.1" # Set your target | |
main(target, interval=30) # Run every 5 minutes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment