Update check_mdns.py

This commit is contained in:
gru
2025-05-23 10:37:04 +02:00
parent 37698e935a
commit 88a8244cb8

View File

@ -121,6 +121,49 @@ def export_services(services, format):
writer.writerow([name, info['type'], info['ip'], info['port'], info['hostname']]) writer.writerow([name, info['type'], info['ip'], info['port'], info['hostname']])
print("Eksportowano do mdns_services.csv") print("Eksportowano do mdns_services.csv")
def print_scan_report(services, script_path, interface=None, test_mode=None):
print("\n📡 Wykryte urządzenia mDNS:\n")
for name, info in services.items():
proto_clean = info['type'].split('.')[0].strip('_')
if test_mode in ['all', proto_clean]:
from http.client import HTTPConnection
try:
conn = HTTPConnection(info['ip'], info['port'], timeout=5)
conn.request("GET", "/")
resp = conn.getresponse()
test_status = "OK" if resp.status == 200 else f"Błąd {resp.status}"
except Exception as e:
test_status = "NIE"
else:
test_status = "-"
print(f" - {name} [protokoł: {proto_clean}, IP: {info['ip']}, port: {info['port']}, host: {info['hostname']}, test: {test_status}, szczegóły: {info['properties'] if info['properties'] else 'brak'}]")
print("\n🔧 Propozycje komend do użycia z Nagiosem:\n")
for name, info in services.items():
safe_device = name.split('.')[0].replace('"', '\\"')
cmd = f"{script_path} --device \"{safe_device}\""
if interface:
cmd += f" --interface {interface}"
if test_mode:
cmd += f" --test {test_mode}"
print(f" {cmd}")
def should_test(proto, test_mode):
return test_mode == 'all' or test_mode == proto
def get_test_status(info, test_mode):
proto_clean = info['type'].split('.')[0].strip('_')
if should_test(proto_clean, test_mode):
try:
conn = http.client.HTTPConnection(info['ip'], info['port'], timeout=5)
conn.request("GET", "/")
response = conn.getresponse()
return "OK" if response.status == 200 else f"Błąd {response.status}"
except Exception:
return "NIE"
return "-"
def main(): def main():
parser = argparse.ArgumentParser(description="Skrypt Nagios do wykrywania urządzeń mDNS (Bonjour, IPP, AirPrint) z testem działania, eksportem, regexami, filtrowaniem i pełnym podglądem usług.") parser = argparse.ArgumentParser(description="Skrypt Nagios do wykrywania urządzeń mDNS (Bonjour, IPP, AirPrint) z testem działania, eksportem, regexami, filtrowaniem i pełnym podglądem usług.")
parser.add_argument("--device", help="Fragment lub regex nazwy urządzenia do wykrycia (np. 'printer|tv')") parser.add_argument("--device", help="Fragment lub regex nazwy urządzenia do wykrycia (np. 'printer|tv')")
@ -139,18 +182,12 @@ def main():
print("Tryb serwisowy nie został jeszcze zaimplementowany.") print("Tryb serwisowy nie został jeszcze zaimplementowany.")
sys.exit(3) sys.exit(3)
def should_test(proto):
if args.test == 'all': return proto in ['ipp', 'http']
return args.test == proto
if args.scan: if args.scan:
try: try:
services = scan_mdns_services(args.timeout, args.interface, args.filter_type) services = scan_mdns_services(args.timeout, args.interface, args.filter_type)
if services: if services:
for name, info in services.items(): script_path = os.path.realpath(__file__)
proto_clean = info['type'].split('.')[0].strip('_') print_scan_report(services, script_path, args.interface, args.test)
test_status = "OK" if should_test(proto_clean) and test_service(info['ip'], info['port']) else "NIE" if args.test and should_test(proto_clean) else "-"
print(f" - {name} [protokoł: {proto_clean}, IP: {info['ip']}, port: {info['port']}, test: {test_status}]")
if args.export: if args.export:
export_services(services, args.export) export_services(services, args.export)
sys.exit(0) sys.exit(0)
@ -175,11 +212,14 @@ def main():
if matches: if matches:
print(f"OK: Urządzenie pasujące do '{args.device}' znalezione w mDNS:") print(f"OK: Urządzenie pasujące do '{args.device}' znalezione w mDNS:")
all_ok = True
for name, info in matches.items(): for name, info in matches.items():
proto_clean = info['type'].split('.')[0].strip('_') proto_clean = info['type'].split('.')[0].strip('_')
test_status = "OK" if should_test(proto_clean) and test_service(info['ip'], info['port']) else "NIE" if args.test and should_test(proto_clean) else "-" test_status = get_test_status(info, args.test)
if args.test and should_test(proto_clean, args.test) and test_status != "OK":
all_ok = False
print(f" - {name} [protokoł: {proto_clean}, IP: {info['ip']}, port: {info['port']}, host: {info['hostname']}, test: {test_status}, szczegóły: {info['properties'] if info['properties'] else 'brak'}]") print(f" - {name} [protokoł: {proto_clean}, IP: {info['ip']}, port: {info['port']}, host: {info['hostname']}, test: {test_status}, szczegóły: {info['properties'] if info['properties'] else 'brak'}]")
sys.exit(0) sys.exit(0 if all_ok else 2)
elif services: elif services:
print(f"WARNING: Nie znaleziono pasujących urządzeń do '{args.device}'. Wykryto inne:") print(f"WARNING: Nie znaleziono pasujących urządzeń do '{args.device}'. Wykryto inne:")
for name, info in services.items(): for name, info in services.items():