pesping 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.4
2
+ Name: pesping
3
+ Version: 1.1.0
4
+ Summary: Concurrent IPv4 ICMP scanner and upgrade availability monitor
5
+ Author: jpesqueda
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/jpesqueda/pesping
8
+ Project-URL: Repository, https://github.com/jpesqueda/pesping
9
+ Project-URL: Documentation, https://github.com/jpesqueda/pesping/blob/main/README.es.md
10
+ Project-URL: Issues, https://github.com/jpesqueda/pesping/issues
11
+ Keywords: ping,icmp,network,monitor,network-automation,upgrade
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Environment :: Console
16
+ Classifier: Topic :: System :: Networking :: Monitoring
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: colorama>=0.4.6; platform_system == "Windows"
21
+ Dynamic: license-file
22
+
23
+ # pesping
24
+
25
+ **Concurrent IPv4 ICMP scanner and network upgrade monitor** · Version 1.1.0
26
+
27
+ [Español](README.es.md) · [Publishing guide / Guía de publicación](PUBLISHING.md)
28
+
29
+ pesping checks single hosts, files of hosts, IPv4 CIDR subnets, and inclusive IP ranges. Use a one-time scan to see reachable addresses or continuous monitoring to track device outages and recoveries during network maintenance.
30
+
31
+ ## Requirements
32
+ - Python 3.10 or newer.
33
+ - Windows, Linux, or macOS with the system `ping` command available.
34
+ - Optional `colorama` for colored terminal output (installed automatically on Windows).
35
+
36
+ ## Installation
37
+ After the package has been published to PyPI:
38
+ ```powershell
39
+ python -m pip install pesping
40
+ pesping --help
41
+ ```
42
+ From source before PyPI publication:
43
+ ```powershell
44
+ git clone https://github.com/jpesqueda/pesping.git
45
+ cd pesping
46
+ python -m pip install -e .
47
+ pesping --help
48
+ ```
49
+
50
+ ## Target options
51
+ Exactly one target source is required.
52
+
53
+ | Argument | Meaning | Example |
54
+ | --- | --- | --- |
55
+ | `-ho`, `--host` | One IP address or hostname | `-ho 192.0.2.10` |
56
+ | `-hf`, `--host_file` | UTF-8 host file | `-hf hosts.txt` |
57
+ | `-r`, `--range` | Inclusive range, full or short form | `-r 192.0.2.100-200` |
58
+ | `-s`, `--subnet` | IPv4 CIDR network | `-s 198.51.100.0/26` |
59
+
60
+ Both `-r 192.0.2.100-192.0.2.200` and `-r 192.0.2.100-200` select 101 IPs. To cross an octet boundary, use the full ending IP. CIDR enumeration excludes network/broadcast for ordinary subnets, while /31 and /32 follow Python's `ipaddress.hosts()` behavior.
61
+
62
+ ## Examples
63
+ ```powershell
64
+ pesping -ho 192.0.2.10
65
+ pesping -hf hosts.txt --show down
66
+ pesping -r 192.0.2.100-200 --show up
67
+ pesping -r 192.0.2.100-192.0.2.200
68
+ pesping -s 198.51.100.0/26 --workers 20
69
+ pesping -s 192.0.2.0/24 --monitor --only-changes
70
+ pesping -hf hosts.txt --monitor --interval 2 --fail-threshold 3 --recovery-threshold 2 --log upgrade.log --csv upgrade.csv
71
+ pesping -hf hosts.txt --stop-when-all-up --only-changes
72
+ ```
73
+
74
+ ## Host file format
75
+ ```text
76
+ # One target per line, or optional friendly-name,address
77
+ switch01.example.test,192.0.2.10
78
+ switch02.example.test,192.0.2.11
79
+ 192.0.2.12
80
+ ```
81
+ Blank lines and lines starting with `#` are ignored; duplicate addresses are skipped.
82
+
83
+ ## Monitoring behavior
84
+ A target changes to DOWN after `--fail-threshold` consecutive failed ICMP probes (default 3); it changes to UP after `--recovery-threshold` consecutive replies (default 2). `--only-changes` suppresses cycle totals while retaining events. `--wait-for-up` exits once all targets reach UP. `--stop-when-all-up` exits after a DOWN event was observed and every target has recovered. Use Ctrl+C to stop and print a summary.
85
+
86
+ `--show all|up|down` filters **one-time scan results only**. `--workers` controls concurrency (default 50), `--timeout` controls the probe timeout (default 1 second), `--interval` controls monitoring intervals (default 2 seconds), and `--max-hosts` limits scan size (default 4096). Run `pesping --help` for exact options.
87
+
88
+ ## Output
89
+ - Single scans show each selected target and a summary with total/reachable/unreachable counts.
90
+ - Monitoring logs state transitions, outage counts, accumulated downtime, and final per-device states.
91
+ - `--log FILE` stores timestamped text events; `--csv FILE` writes timestamp, event, host, address, status, outage count, and downtime.
92
+
93
+ ## Important limitations
94
+ A failed ICMP reply **does not prove** that a host is down: firewalls and rate limiting can block ping. An ICMP response **does not prove** that applications or routing protocols are healthy. Outages are estimates based on the monitoring process's probes, not precise device event times.
95
+
96
+ All addresses and hostnames shown here are fictional documentation examples from RFC 5737 and the reserved `.test` domain. Only scan systems you are authorized to test. Runtime logs/CSVs may contain actual host information and should be protected.
97
+
98
+ ## Development
99
+ ```powershell
100
+ python -m pip install -e . pytest build twine
101
+ python -m pytest -q
102
+ python -m build
103
+ python -m twine check dist/*
104
+ ```
105
+
106
+ License: MIT. Maintainer: [jpesqueda](https://github.com/jpesqueda).
@@ -0,0 +1,7 @@
1
+ pesping.py,sha256=vxlrv_y4tlIhdgfpmmDjIobh5db339bAk3RWr-mBdKM,23203
2
+ pesping-1.1.0.dist-info/licenses/LICENSE,sha256=io-D7bcDbDhHgM2MS5Lqc2nRnS6hQFv1Dz_3_iQUnW8,1066
3
+ pesping-1.1.0.dist-info/METADATA,sha256=1XB7rXJATu0gvb6NSSsPf1s8ep21Xhfdo9wVUkbcX3A,5005
4
+ pesping-1.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ pesping-1.1.0.dist-info/entry_points.txt,sha256=1unz9mX8I6gofRv8gQGoAAk8gXKHxCTJfk9w9CtRwtE,41
6
+ pesping-1.1.0.dist-info/top_level.txt,sha256=cN0YOSAePGcnpqJUtAAwbDZ4OyAOeRqd7mRTG9rT8Jg,8
7
+ pesping-1.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pesping = pesping:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jpesqueda
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pesping
pesping.py ADDED
@@ -0,0 +1,585 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """PESPING - Concurrent IPv4 scanner and ICMP upgrade monitor.
4
+
5
+ Version: 1.1.0
6
+ Python: 3.10+
7
+ Platforms: Windows, Linux, and macOS (system ping command required)
8
+
9
+ Overview:
10
+ Perform a single ICMP scan or continuously monitor hosts during network
11
+ maintenance. Targets may be supplied as one host, a host file, an inclusive
12
+ IPv4 range, or an IPv4 CIDR subnet. Network probes execute concurrently.
13
+
14
+ Dependencies:
15
+ Python standard library; optional `colorama` for terminal colors.
16
+ Install the optional dependency with: pip install colorama
17
+
18
+ Example commands (documentation-only addresses from RFC 5737):
19
+ python pesping.py -ho 192.0.2.10
20
+ python pesping.py -hf hosts.txt --monitor --only-changes
21
+ python pesping.py -r 192.0.2.100-192.0.2.200
22
+ python pesping.py -r 192.0.2.100-200 --show up
23
+ python pesping.py -s 192.0.2.0/24 --show down
24
+ python pesping.py -s 198.51.100.0/26 --monitor --workers 20
25
+
26
+ Example hosts.txt:
27
+ # Name,IP address (all fictional)
28
+ switch01.example.test,192.0.2.10
29
+ switch02.example.test,192.0.2.11
30
+
31
+ Operational notes:
32
+ * ICMP success means the target answered ping, not that applications or
33
+ routing protocols have recovered.
34
+ * ICMP failure does not prove that a device is offline; firewalls may
35
+ block or rate-limit echo requests.
36
+ * --max-hosts prevents accidental oversized scans by default.
37
+ * --show filters single-scan output, not continuous monitoring events.
38
+ * Monitoring timestamps and downtime are local process observations.
39
+ * Run scans only on systems and networks you are authorized to test.
40
+
41
+ Security and privacy:
42
+ All examples use reserved documentation IPv4 ranges (RFC 5737) and
43
+ fictional .test domain names. No production IPs or user credentials
44
+ are embedded in this file. Logs and CSVs contain actual target data
45
+ supplied at runtime; handle generated outputs accordingly.
46
+ """
47
+
48
+ import argparse
49
+ import concurrent.futures
50
+ import csv
51
+ import datetime as dt
52
+ import ipaddress
53
+ import math
54
+ import os
55
+ import platform
56
+ import subprocess
57
+ import sys
58
+ import time
59
+ from dataclasses import dataclass
60
+
61
+ __version__ = "1.1.0"
62
+
63
+ try:
64
+ from colorama import Fore, Style, init
65
+ init(autoreset=True)
66
+ GREEN, RED, CYAN, YELLOW, RESET = Fore.GREEN, Fore.RED, Fore.CYAN, Fore.YELLOW, Style.RESET_ALL
67
+ except ImportError:
68
+ GREEN = RED = CYAN = YELLOW = RESET = ""
69
+
70
+
71
+ @dataclass
72
+ # Persistent monitoring state for each host.
73
+ class DeviceState:
74
+ """Per-target state used for debounced UP/DOWN detection and downtime."""
75
+ state: str = "UNKNOWN"
76
+ fail_streak: int = 0
77
+ success_streak: int = 0
78
+ first_failure: float | None = None
79
+ first_recovery: float | None = None
80
+ down_since: float | None = None
81
+ outages: int = 0
82
+ total_downtime: float = 0.0
83
+
84
+
85
+ # ============================================================================
86
+ # TIME FORMATTING AND EXPORT HELPERS
87
+ # ============================================================================
88
+ def timestamp():
89
+ """Return the current local time formatted for a console event."""
90
+ return dt.datetime.now().strftime("%H:%M:%S")
91
+
92
+
93
+ def full_timestamp():
94
+ """Return the current local date and time for exported event records."""
95
+ return dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
96
+
97
+
98
+ def format_duration(seconds):
99
+ """Format a nonnegative elapsed duration as HH:MM:SS."""
100
+ h, rem = divmod(max(0, int(seconds)), 3600)
101
+ m, s = divmod(rem, 60)
102
+ return f"{h:02}:{m:02}:{s:02}"
103
+
104
+
105
+ def write_log(filename, message):
106
+ """Append a timestamped event to the optional plain-text log file."""
107
+ if filename:
108
+ with open(filename, "a", encoding="utf-8") as f:
109
+ f.write(f"[{full_timestamp()}] {message}\n")
110
+
111
+
112
+ def write_csv_event(filename, event, host, status, downtime=0, outages=0):
113
+ """Append one lifecycle event to CSV, writing column headers as needed."""
114
+ if not filename:
115
+ return
116
+
117
+ new_file = not os.path.exists(filename) or os.path.getsize(filename) == 0
118
+ fields = ["timestamp", "event", "host", "address", "status", "outages", "downtime_seconds", "downtime"]
119
+
120
+ with open(filename, "a", newline="", encoding="utf-8") as f:
121
+ writer = csv.DictWriter(f, fieldnames=fields)
122
+ if new_file:
123
+ writer.writeheader()
124
+ writer.writerow({
125
+ "timestamp": full_timestamp(),
126
+ "event": event,
127
+ "host": host["name"],
128
+ "address": host["address"],
129
+ "status": status,
130
+ "outages": outages,
131
+ "downtime_seconds": round(downtime, 2),
132
+ "downtime": format_duration(downtime),
133
+ })
134
+
135
+
136
+ # ============================================================================
137
+ # TARGET FILE AND IP EXPANSION
138
+ # ============================================================================
139
+ def load_hosts(filename):
140
+ """Load named or unnamed targets, skipping comments and duplicate addresses."""
141
+ hosts, seen = [], set()
142
+
143
+ try:
144
+ with open(filename, encoding="utf-8") as f:
145
+ for number, raw in enumerate(f, 1):
146
+ line = raw.strip()
147
+ if not line or line.startswith("#"):
148
+ continue
149
+
150
+ if "," in line:
151
+ name, address = [x.strip() for x in line.split(",", 1)]
152
+ else:
153
+ name = address = line
154
+
155
+ if not name or not address:
156
+ print(f"{YELLOW}WARNING:{RESET} Invalid line {number}: {line}")
157
+ continue
158
+ if address in seen:
159
+ continue
160
+
161
+ seen.add(address)
162
+ hosts.append({"name": name, "address": address})
163
+
164
+ except FileNotFoundError:
165
+ sys.exit(f"ERROR: Host file '{filename}' was not found.")
166
+ except OSError as exc:
167
+ sys.exit(f"ERROR: Unable to read '{filename}': {exc}")
168
+
169
+ if not hosts:
170
+ sys.exit("ERROR: No valid hosts were found.")
171
+
172
+ return hosts
173
+
174
+
175
+
176
+ def parse_range(spec):
177
+ """Expand inclusive IPv4 ranges.
178
+
179
+ Full endpoints may span subnet boundaries. A numeric-only end uses the
180
+ first three octets of the start address; descending ranges are rejected.
181
+ Returns integer addresses suitable for lazy iteration.
182
+ """
183
+ parts = spec.split("-")
184
+ if len(parts) != 2 or not all(parts):
185
+ raise ValueError("Range must be START-IP-END-IP or START-IP-LAST-OCTET")
186
+ start_text, end_text = (part.strip() for part in parts)
187
+ try:
188
+ start = ipaddress.IPv4Address(start_text)
189
+ if "." in end_text:
190
+ end = ipaddress.IPv4Address(end_text)
191
+ else:
192
+ if not end_text.isdecimal() or not 0 <= int(end_text) <= 255:
193
+ raise ValueError("Abbreviated range end must be an octet from 0 to 255")
194
+ end = ipaddress.IPv4Address(".".join(start_text.split(".")[:3]) + "." + str(int(end_text)))
195
+ except ipaddress.AddressValueError as exc:
196
+ raise ValueError(str(exc)) from exc
197
+ if int(end) < int(start):
198
+ raise ValueError("Range end must be greater than or equal to its start")
199
+ return int(start), int(end)
200
+
201
+
202
+ def load_targets(args, parser):
203
+ """Resolve CLI target selection into host dictionaries.
204
+
205
+ CIDR scans use network.hosts(), excluding network/broadcast on typical
206
+ subnets but retaining addresses on /31 and /32. IPv4 range boundaries
207
+ are inclusive. Enforce max-hosts before expansion where possible.
208
+ """
209
+ if args.host_file:
210
+ hosts = load_hosts(args.host_file)
211
+ elif args.host:
212
+ hosts = [{"name": args.host, "address": args.host}]
213
+ else:
214
+ try:
215
+ if args.subnet:
216
+ network = ipaddress.IPv4Network(args.subnet, strict=False)
217
+ count = network.num_addresses if network.prefixlen >= 31 else network.num_addresses - 2
218
+ if count > args.max_hosts:
219
+ parser.error(f"Subnet has {count:,} target IPs; --max-hosts is {args.max_hosts:,}. Increase --max-hosts intentionally to proceed.")
220
+ addresses = (str(ip) for ip in network.hosts())
221
+ else:
222
+ start, end = parse_range(args.range)
223
+ count = end - start + 1
224
+ if count > args.max_hosts:
225
+ parser.error(f"Range has {count:,} target IPs; --max-hosts is {args.max_hosts:,}.")
226
+ addresses = (str(ipaddress.IPv4Address(i)) for i in range(start, end + 1))
227
+ hosts = [{"name": address, "address": address} for address in addresses]
228
+ except (ValueError, ipaddress.NetmaskValueError) as exc:
229
+ parser.error(str(exc))
230
+ if len(hosts) > args.max_hosts:
231
+ parser.error(f"Host file has {len(hosts):,} targets; increase --max-hosts (currently {args.max_hosts:,}).")
232
+ return hosts
233
+
234
+
235
+ # ============================================================================
236
+ # CROSS-PLATFORM ICMP PROBING
237
+ # ============================================================================
238
+ def ping_host(host, timeout=1):
239
+ """Send one ICMP echo request using the host operating system ping command."""
240
+ address = host["address"]
241
+ system = platform.system().lower()
242
+
243
+ if system == "windows":
244
+ cmd = ["ping", "-n", "1", "-w", str(int(timeout * 1000)), address]
245
+ elif system == "darwin":
246
+ cmd = ["ping", "-c", "1", "-W", str(int(timeout * 1000)), address]
247
+ else:
248
+ cmd = ["ping", "-c", "1", "-W", str(max(1, math.ceil(timeout))), address]
249
+
250
+ try:
251
+ result = subprocess.run(
252
+ cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout + 1
253
+ )
254
+ return result.returncode == 0
255
+ except (subprocess.TimeoutExpired, OSError):
256
+ return False
257
+
258
+
259
+ def ping_all(hosts, timeout, workers):
260
+ """Probe targets concurrently and map each address to its response status."""
261
+ results = {}
262
+ max_workers = min(workers, max(1, len(hosts)))
263
+
264
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as pool:
265
+ futures = {pool.submit(ping_host, host, timeout): host for host in hosts}
266
+ for future in concurrent.futures.as_completed(futures):
267
+ host = futures[future]
268
+ try:
269
+ results[host["address"]] = future.result()
270
+ except Exception:
271
+ results[host["address"]] = False
272
+
273
+ return results
274
+
275
+
276
+ # ============================================================================
277
+ # STATE TRANSITIONS AND EVENT REPORTING
278
+ # ============================================================================
279
+ def emit_event(event, host, state, log_file=None, csv_file=None, downtime=0):
280
+ """Print a state transition and optionally persist it to text/CSV logs."""
281
+ name, address = host["name"], host["address"]
282
+
283
+ if event in ("UP", "INITIAL_UP"):
284
+ print(
285
+ f"[{timestamp()}] {GREEN}UP{RESET} {name:<30}"
286
+ + (f" downtime {YELLOW}{format_duration(downtime)}{RESET}" if event == "UP" else "")
287
+ )
288
+ status = "UP"
289
+ else:
290
+ print(f"[{timestamp()}] {RED}DOWN{RESET} {name}")
291
+ status = "DOWN"
292
+
293
+ log_msg = f"{event} {name} ({address})"
294
+ if event == "UP":
295
+ log_msg += f" downtime {format_duration(downtime)}"
296
+
297
+ write_log(log_file, log_msg)
298
+ write_csv_event(csv_file, event, host, status, downtime, state.outages)
299
+
300
+
301
+ def process_result(host, alive, state, fail_threshold, recovery_threshold, log_file, csv_file):
302
+ """Update hysteresis counters and state; return True on confirmed DOWN."""
303
+ now = time.time()
304
+
305
+ if alive:
306
+ state.fail_streak = 0
307
+ state.first_failure = None
308
+
309
+ if state.state in ("UNKNOWN", "DOWN"):
310
+ if state.success_streak == 0:
311
+ state.first_recovery = now
312
+ state.success_streak += 1
313
+
314
+ if state.success_streak >= recovery_threshold:
315
+ recovery_time = state.first_recovery or now
316
+
317
+ if state.state == "DOWN":
318
+ downtime = recovery_time - (state.down_since or recovery_time)
319
+ state.total_downtime += downtime
320
+ state.state = "UP"
321
+ state.success_streak = 0
322
+ state.first_recovery = None
323
+ state.down_since = None
324
+ emit_event("UP", host, state, log_file, csv_file, downtime)
325
+ else:
326
+ state.state = "UP"
327
+ state.success_streak = 0
328
+ state.first_recovery = None
329
+ emit_event("INITIAL_UP", host, state, log_file, csv_file)
330
+
331
+ else:
332
+ state.success_streak = 0
333
+ state.first_recovery = None
334
+
335
+ return False
336
+
337
+ state.success_streak = 0
338
+ state.first_recovery = None
339
+
340
+ if state.state in ("UNKNOWN", "UP"):
341
+ if state.fail_streak == 0:
342
+ state.first_failure = now
343
+ state.fail_streak += 1
344
+
345
+ if state.fail_streak >= fail_threshold:
346
+ was_up = state.state == "UP"
347
+ state.state = "DOWN"
348
+ state.down_since = state.first_failure or now
349
+ state.fail_streak = 0
350
+ state.first_failure = None
351
+ state.outages += 1
352
+ emit_event("DOWN" if was_up else "INITIAL_DOWN", host, state, log_file, csv_file)
353
+ return True
354
+
355
+ else:
356
+ state.fail_streak = 0
357
+ state.first_failure = None
358
+
359
+ return False
360
+
361
+
362
+ # ============================================================================
363
+ # MONITORING STATUS AND SUMMARY
364
+ # ============================================================================
365
+ def get_counts(states):
366
+ """Count UP, DOWN, and UNKNOWN host states for the current monitoring cycle."""
367
+ values = [s.state for s in states.values()]
368
+ return values.count("UP"), values.count("DOWN"), values.count("UNKNOWN")
369
+
370
+
371
+ def all_up(states):
372
+ """Return True only when every tracked target has reached UP state."""
373
+ return all(s.state == "UP" for s in states.values())
374
+
375
+
376
+ def show_summary(hosts, states, start_time):
377
+ """Print final host states, outage counts, downtime, and elapsed time."""
378
+ now = time.time()
379
+ print("\n" + "=" * 92)
380
+ print("UPGRADE MONITOR SUMMARY")
381
+ print("=" * 92)
382
+ print(f"{'DEVICE':<30}{'STATUS':<12}{'OUTAGES':<12}{'TOTAL DOWNTIME':<18}ADDRESS")
383
+ print("-" * 92)
384
+
385
+ longest_host, longest_time = None, -1
386
+ for host in hosts:
387
+ state = states[host["address"]]
388
+ total = state.total_downtime
389
+ if state.state == "DOWN" and state.down_since:
390
+ total += now - state.down_since
391
+
392
+ if total > longest_time:
393
+ longest_host, longest_time = host["name"], total
394
+
395
+ color = GREEN if state.state == "UP" else RED if state.state == "DOWN" else YELLOW
396
+ print(
397
+ f"{host['name']:<30}{color}{state.state:<12}{RESET}"
398
+ f"{state.outages:<12}{format_duration(total):<18}{host['address']}"
399
+ )
400
+
401
+ up, down, unknown = get_counts(states)
402
+ print("-" * 92)
403
+ print(f"Devices : {len(hosts)}")
404
+ print(f"UP : {GREEN}{up}{RESET}")
405
+ print(f"DOWN : {RED}{down}{RESET}")
406
+ if unknown:
407
+ print(f"UNKNOWN : {YELLOW}{unknown}{RESET}")
408
+ print(f"Monitoring time : {format_duration(now - start_time)}")
409
+ if longest_host:
410
+ print(f"Longest outage : {longest_host} - {format_duration(longest_time)}")
411
+ print("=" * 92)
412
+
413
+
414
+ # ============================================================================
415
+ # CONTINUOUS MONITORING LOOP
416
+ # ============================================================================
417
+ def monitor_hosts(args, hosts):
418
+ """Monitor targets until interrupted or an enabled exit condition is met."""
419
+ start_time = time.time()
420
+ states = {host["address"]: DeviceState() for host in hosts}
421
+ seen_down = False
422
+
423
+ print("\n" + "=" * 78)
424
+ print(f"{CYAN}PESPING Upgrade Monitor{RESET}")
425
+ print("=" * 78)
426
+ print(f"[{timestamp()}] Monitoring {len(hosts)} devices...")
427
+ print(f"Interval : {args.interval}s")
428
+ print(f"Timeout : {args.timeout}s")
429
+ print(f"Fail threshold : {args.fail_threshold}")
430
+ print(f"Recovery threshold : {args.recovery_threshold}")
431
+ if args.log:
432
+ print(f"Log : {args.log}")
433
+ if args.csv:
434
+ print(f"CSV : {args.csv}")
435
+ if args.only_changes:
436
+ print("Display : changes only")
437
+ print("\nPress Ctrl+C to stop.")
438
+ print("=" * 78 + "\n")
439
+
440
+ write_log(
441
+ args.log,
442
+ f"MONITOR START devices={len(hosts)} interval={args.interval} timeout={args.timeout} "
443
+ f"fail_threshold={args.fail_threshold} recovery_threshold={args.recovery_threshold}",
444
+ )
445
+
446
+ try:
447
+ while True:
448
+ cycle_start = time.time()
449
+ results = ping_all(hosts, args.timeout, args.workers)
450
+
451
+ for host in hosts:
452
+ state = states[host["address"]]
453
+ if process_result(
454
+ host, results.get(host["address"], False), state,
455
+ args.fail_threshold, args.recovery_threshold, args.log, args.csv
456
+ ):
457
+ seen_down = True
458
+
459
+ up, down, unknown = get_counts(states)
460
+
461
+ if not args.only_changes:
462
+ print(
463
+ f"[{timestamp()}] {GREEN}UP {up}{RESET} | "
464
+ f"{RED}DOWN {down}{RESET} | {YELLOW}PENDING {unknown}{RESET}"
465
+ )
466
+
467
+ if all_up(states):
468
+ if args.stop_when_all_up and seen_down:
469
+ print(f"\n{GREEN}ALL DEVICES RECOVERED{RESET}")
470
+ write_log(args.log, "ALL DEVICES RECOVERED")
471
+ break
472
+ if args.wait_for_up and not args.stop_when_all_up:
473
+ print(f"\n{GREEN}ALL DEVICES ARE UP{RESET}")
474
+ write_log(args.log, "ALL DEVICES ARE UP")
475
+ break
476
+
477
+ time.sleep(max(0, args.interval - (time.time() - cycle_start)))
478
+
479
+ except KeyboardInterrupt:
480
+ print(f"\n{YELLOW}Monitoring stopped by user.{RESET}")
481
+ write_log(args.log, "MONITOR STOPPED BY USER")
482
+ finally:
483
+ show_summary(hosts, states, start_time)
484
+ write_log(args.log, "MONITOR END")
485
+
486
+
487
+ # ============================================================================
488
+ # ONE-TIME SCAN MODE
489
+ # ============================================================================
490
+ def single_scan(args, hosts):
491
+ """Run one concurrent probe cycle, filter output, and print scan totals."""
492
+ start = time.monotonic()
493
+ results = ping_all(hosts, args.timeout, args.workers)
494
+ print()
495
+
496
+ for host in hosts:
497
+ alive = results.get(host["address"], False)
498
+ if args.show == "up" and not alive or args.show == "down" and alive:
499
+ continue
500
+ if alive:
501
+ print(f"{GREEN}UP{RESET} {host['name']:<30} {host['address']}")
502
+ else:
503
+ print(f"{RED}DOWN{RESET} {host['name']:<30} {host['address']}")
504
+
505
+ up = sum(bool(results.get(host["address"], False)) for host in hosts)
506
+ down = len(hosts) - up
507
+ print("\n" + "=" * 78)
508
+ print("PING SCAN SUMMARY")
509
+ print("=" * 78)
510
+ print(f"Total IPs : {len(hosts)}")
511
+ print(f"Reachable : {GREEN}{up}{RESET}")
512
+ print(f"Unreachable : {RED}{down}{RESET}")
513
+ print(f"Scan time : {format_duration(time.monotonic() - start)}")
514
+ print("=" * 78)
515
+
516
+
517
+ # ============================================================================
518
+ # COMMAND-LINE INTERFACE
519
+ # ============================================================================
520
+ def parse_args(argv=None):
521
+ """Parse CLI options and reject invalid thresholds and worker limits."""
522
+ parser = argparse.ArgumentParser(
523
+ description=f"PESPING v{__version__} - Concurrent ICMP monitor and IPv4 scanner",
524
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
525
+ epilog=(
526
+ "Examples:\n"
527
+ " python pesping.py -ho 192.0.2.10\n"
528
+ " python pesping.py -hf hosts.txt --monitor --only-changes\n"
529
+ " python pesping.py -r 192.0.2.100-192.0.2.200\n"
530
+ " python pesping.py -r 192.0.2.100-200 --show up\n"
531
+ " python pesping.py -s 192.0.2.0/24 --show down\n"
532
+ " python pesping.py -s 192.0.2.0/22 --monitor --workers 20\n"
533
+ ),
534
+ )
535
+ source = parser.add_mutually_exclusive_group(required=True)
536
+ source.add_argument("-hf", "--host_file", dest="host_file", metavar="FILE", help="File containing hosts or IPs")
537
+ source.add_argument("-ho", "--host", help="Single hostname or IP")
538
+ source.add_argument("-r", "--range", metavar="START-END", help="IPv4 range; full or abbreviated last octet")
539
+ source.add_argument("-s", "--subnet", metavar="CIDR", help="IPv4 subnet, e.g. 192.0.2.0/24")
540
+ parser.add_argument("--monitor", action="store_true", help="Enable continuous monitoring")
541
+ parser.add_argument("--interval", type=float, default=2, help="Seconds between cycles")
542
+ parser.add_argument("--timeout", type=float, default=1, help="ICMP timeout in seconds")
543
+ parser.add_argument("--fail-threshold", type=int, default=3, help="Failures required to declare DOWN")
544
+ parser.add_argument("--recovery-threshold", type=int, default=2, help="Replies required to declare UP")
545
+ parser.add_argument("--log", metavar="FILE", help="Save events to log file")
546
+ parser.add_argument("--csv", metavar="FILE", help="Save events to CSV")
547
+ parser.add_argument("--show", choices=("all", "up", "down"), default="all", help="Filter results for a single scan")
548
+ parser.add_argument("--only-changes", action="store_true", help="Show only state changes in monitor mode")
549
+ parser.add_argument("--wait-for-up", action="store_true", help="Exit when all devices are UP")
550
+ parser.add_argument("--stop-when-all-up", action="store_true", help="Exit after DOWN event and full recovery")
551
+ parser.add_argument("--workers", type=int, default=50, help="Maximum simultaneous ping workers")
552
+ parser.add_argument("--max-hosts", type=int, default=4096, help="Maximum target IPs (safety limit)")
553
+ args = parser.parse_args(argv)
554
+ if args.interval <= 0:
555
+ parser.error("--interval must be greater than 0")
556
+ if args.timeout <= 0:
557
+ parser.error("--timeout must be greater than 0")
558
+ if args.fail_threshold < 1:
559
+ parser.error("--fail-threshold must be >= 1")
560
+ if args.recovery_threshold < 1:
561
+ parser.error("--recovery-threshold must be >= 1")
562
+ if args.workers < 1:
563
+ parser.error("--workers must be >= 1")
564
+ if args.max_hosts < 1:
565
+ parser.error("--max-hosts must be >= 1")
566
+ if args.wait_for_up or args.stop_when_all_up:
567
+ args.monitor = True
568
+ return args, parser
569
+
570
+
571
+ # ============================================================================
572
+ # PROGRAM ENTRY POINT
573
+ # ============================================================================
574
+ def main():
575
+ """Select the input targets and dispatch to scan or monitoring mode."""
576
+ args, parser = parse_args()
577
+ hosts = load_targets(args, parser)
578
+ if args.monitor:
579
+ monitor_hosts(args, hosts)
580
+ else:
581
+ single_scan(args, hosts)
582
+
583
+
584
+ if __name__ == "__main__":
585
+ main()