From Web Design to ERP — Your IT Partner

Python VPN Ping Monitor: Diagnose Packet Loss Patterns

The tell: A 60-minute Python ping monitor watching three VPN-connected IPs simultaneously logged 45 drop events that hit all three targets at exactly the same second — proof the problem was a shared upstream link, not three unrelated device issues.

"The VPN keeps disconnecting" is one of the least actionable bug reports in networking. Is it one site or all of them? Every few minutes or randomly? Under load or at idle? Without data, chasing this means guessing — and guessing wrong wastes a maintenance window on a fix that doesn't address the actual cause. A simple multi-target ping monitor, run for long enough to catch the pattern, answers all of these questions from data instead of speculation.

What the Monitor Tracks

Every ping to all targets: RTT, timeout, failure reason

Drop events: when an IP goes unreachable, for how long, how many pings lost

RTT spikes: latency above a threshold even when not dropping

Simultaneous drops: when two or more IPs drop within 10 seconds of each other — the key signal

Final report: per-IP stats, event timeline, correlation analysis, diagnosis

The Script

#!/usr/bin/env python3

"""

Multi-target VPN ping monitor with drop correlation analysis.

Monitors multiple IPs simultaneously and detects common upstream failures.

"""

import subprocess, threading, time, datetime, os, json, statistics, sys

TARGETS = {

"172.20.60.5": {"name": "Site-A-LAN", "ttl_expected": 63},

"172.20.70.5": {"name": "Site-B-LAN", "ttl_expected": 63},

"172.20.90.1": {"name": "Site-C", "ttl_expected": 61},

}

INTERVAL = 2 # seconds between pings per target

TIMEOUT = 2 # ping timeout in seconds

DURATION = 3600 # total monitoring duration (60 min)

RTT_SPIKE_THRESH = 200 # ms — log if RTT exceeds this

LOG_FILE = "/tmp/vpn_ping_log.jsonl"

REPORT_FILE = "/tmp/vpn_ping_report.txt"

DROP_LOG = []

lock = threading.Lock()

log_fh = open(LOG_FILE, "a")

def do_ping(ip):

"""Returns (rtt_ms, None) on success, (None, 'reason') on failure."""

try:

result = subprocess.run(

["ping", "-c", "1", "-W", str(TIMEOUT), "-q", ip],

capture_output=True, text=True, timeout=TIMEOUT + 1

)

if result.returncode == 0:

for line in result.stdout.splitlines():

if "rtt" in line or "round-trip" in line:

parts = line.split("=")[-1].strip().split("/")

return float(parts[1]), None

return None, "parse_error"

return None, "timeout"

except subprocess.TimeoutExpired:

return None, "timeout"

except Exception as e:

return None, str(e)

def monitor_target(ip, meta, stop_event, results):

name, state, drop_start, drop_count = meta["name"], "up", None, 0

rtt_history = []

while not stop_event.is_set():

t0 = time.time()

rtt, err = do_ping(ip)

now = datetime.datetime.now()

entry = {"t": now.isoformat(timespec="seconds"), "ip": ip, "rtt": rtt, "err": err}

with lock:

log_fh.write(json.dumps(entry) + "\n")

log_fh.flush()

if rtt is not None:

rtt_history.append(rtt)

if len(rtt_history) > 60:

rtt_history.pop(0)

if state == "down":

duration = (now - drop_start).total_seconds()

event = {"type": "drop", "ip": ip, "name": name,

"start": drop_start.strftime("%H:%M:%S"), "end": now.strftime("%H:%M:%S"),

"duration_s": round(duration, 1), "pings_lost": drop_count}

with lock:

DROP_LOG.append(event)

log_fh.write(json.dumps({"event": event}) + "\n")

print(f"{name} RECOVERED after {duration:.0f}s ({drop_count} lost)", flush=True)

state, drop_count, drop_start = "up", 0, None

else:

if state == "up":

state, drop_start = "down", now

print(f"{name} DOWN — {err}", flush=True)

drop_count += 1

elapsed = time.time() - t0

stop_event.wait(max(0, INTERVAL - elapsed))

results[ip] = {"rtt_history": rtt_history, "drop_log": [e for e in DROP_LOG if e.get("ip") == ip]}

def analyze_and_report():

events = [json.loads(l) for l in open(LOG_FILE) if l.strip()]

drops = [e["event"] for e in events if "event" in e and e["event"].get("type") == "drop"]

drop_times = {ip: [(d["start"], d["end"]) for d in drops if d["ip"] == ip] for ip in TARGETS}

all_ips = list(TARGETS.keys())

simultaneous = 0

for i, ip1 in enumerate(all_ips):

for ip2 in all_ips[i+1:]:

for s1, _ in drop_times.get(ip1, []):

for s2, _ in drop_times.get(ip2, []):

t1 = datetime.datetime.strptime(s1, "%H:%M:%S")

t2 = datetime.datetime.strptime(s2, "%H:%M:%S")

if abs((t1 - t2).total_seconds()) < 10:

simultaneous += 1

if simultaneous > 0:

print(f"⚠ {simultaneous} simultaneous drop events → COMMON UPSTREAM FAILURE")

else:

print("Drops appear INDEPENDENT per IP → individual device/route issue")

def main():

stop_event, results, threads = threading.Event(), {}, []

for ip, meta in TARGETS.items():

t = threading.Thread(target=monitor_target, args=(ip, meta, stop_event, results), daemon=True)

t.start(); threads.append(t); time.sleep(0.3)

try:

time.sleep(DURATION)

except KeyboardInterrupt:

pass

stop_event.set()

for t in threads: t.join(timeout=5)

log_fh.close()

analyze_and_report()

if __name__ == "__main__":

main()

Running It

nohup python3 vpn_monitor.py > /tmp/vpn_monitor_stdout.txt 2>&1 &

tail -f /tmp/vpn_monitor_stdout.txt

cat /tmp/vpn_ping_report.txt

Reading the Live Output

[09:22:15] Site-A-LAN DOWN — timeout

[09:22:15] Site-B-LAN DOWN — timeout

[09:22:15] Site-C DOWN — timeout

[09:22:29] Site-A-LAN RECOVERED after 14s (7 pings lost)

[09:22:29] Site-B-LAN RECOVERED after 14s (7 pings lost)

[09:22:31] Site-C RECOVERED after 16s (8 pings lost)

Three IPs down at exactly the same second, recovering within two seconds of each other. That's not three independent failures — that's one shared upstream link failing and recovering.

How to Interpret the Four Common Drop Patterns

PatternMeaningWhere to look

All targets drop at onceShared upstream failingThe common path — WireGuard tunnel, PPPoE link, gateway

One target drops, others stay upSpecific to that site/routeThe device at that IP, or its specific route

Periodic drops every ~3 minutesWireGuard re-key failureHandshake packets, firewall, CPU load during key exchange

RTT spikes just before a dropLink saturationBandwidth usage on the tunnel uplink, QoS config

What This Diagnosis Led To

In this case, the WireGuard interface stats on the router confirmed the theory the ping monitor pointed to:

/interface print stats where type=wg

# NAME RX-PACKET TX-PACKET RX-DROP TX-DROP

# wg-hub 7,150,771 26,790,145 0 45,878

45,878 TX-DROP events, correlating with the ping monitor's drop timestamps. That number pointed straight at an MTU mismatch — the full fix is covered in our MTU and packet-loss write-up. After the fix, the same monitor confirmed zero drops and jitter falling from 4.2ms to 0.3ms — the monitor isn't just for diagnosis, it's the before/after proof that a fix actually worked.

FAQ

Why 60 minutes and not just a few pings?

Intermittent problems, by definition, don't show up in a 10-second test. A full re-key cycle is 180 seconds by default, and link-saturation patterns often only appear during specific traffic windows — an hour gives enough samples to see a real pattern instead of noise.

Does this need root access to run?

No — ping is available without elevated privileges on most modern Linux systems, and the script uses only the Python standard library, no pip installs required.

What if drops are correlated for two targets but not the third?

That's meaningful too — it usually means two targets share one upstream path (e.g., a common WireGuard hop) while the third reaches the network by a genuinely different route, such as a separate tunnel or VPN technology entirely.

Chasing an intermittent VPN issue? We build the diagnostic tooling and read the results — before touching a single config. Talk to us.