-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScan-Network.py
More file actions
2583 lines (2161 loc) · 104 KB
/
Scan-Network.py
File metadata and controls
2583 lines (2161 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
####################################################################################################
#
# extra Python modules to be installed, if not already
#
# pip install "netifaces>=0.11.0"
# pip install "pyyaml>=6.0.2"
# pip install "dnspython>=2.7.0"
# pip install "requests>=2.32.3"
# pip install "scapy>=2.6.1"
# pip install "zeroconf>=0.147.0"
#
####################################################################################################
#
# install https://npcap.com/#download
#
####################################################################################################
#
# want to make it an executable for Windows?
#
# pyinstaller --onefile "Scan-Network.py" --exclude-module pkg_resources
#
####################################################################################################
####################################################################################################
### Imports
####################################################################################################
# base imports
import os
import platform
import sys
import getopt
import smtplib
import ssl
import socket
import struct
import time
import ipaddress
import select
import re
import subprocess
# import json
import threading
from datetime import datetime
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import encoders
from queue import Queue
from dataclasses import dataclass
from typing import List, Dict
from collections import defaultdict
# third party imports
import yaml
# import dns.resolver
import psutil
import netifaces
# from requests import get
from scapy.all import *
from zeroconf import (
IPVersion,
ServiceBrowser,
ServiceStateChange,
Zeroconf
)
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
####################################################################################################
### Dataclasses
####################################################################################################
@dataclass
class Device:
ip: str
host: str
port: int
props: List[str]
weight: int
priority: int
text: bytes
@dataclass
class Service:
name: str
devices: List[Device]
#---------------------------------------------------------------------------------------------------
####################################################################################################
### Global variablesDataclasses
####################################################################################################
#---------------------------------------------------------------------------------------------------
# general
VERSION = "4.00"
DEBUG = False
COMPUTERNAME = os.getenv('COMPUTERNAME')
strScriptName = os.path.basename(sys.argv[0])
strScriptPath = os.path.dirname(os.path.realpath(sys.argv[0]))
strScriptBase = os.path.splitext(strScriptName)[0]
YAMLfile = os.path.join(strScriptPath, strScriptBase + '.yaml')
SPACES = " " * 120
BOOLEAN_MAP = {True: "Yes", False: "No"}
#---------------------------------------------------------------------------------------------------
# reporting related
screen_enabled = False
logfile_enabled = False
LOGfile = ""
#---------------------------------------------------------------------------------------------------
# Ping related
ping_count = 3
ping_length = 256
ping_timeout = 300
ScanDict = {}
ScanList = ""
NETfile = ""
TXTfile = ""
ScanHost_cntr = 0
#---------------------------------------------------------------------------------------------------
# ARP related
arpscan_enabled = True
arp_timeout = 1
arpalive = []
# list of dictionaries of IP and mac address of devices responding to arp requests Eg:
"""
[
...
{'ip': '192.168.001.004', 'mac: 'd8:44:89:27:a7:ee'},
{'ip': '192.168.001.005', 'mac: 'ac:84:c6:1a:6b:74'},
{'ip': '192.168.001.006', 'mac: 'ac:84:c6:27:ee:2a'},
...
]
"""
#---------------------------------------------------------------------------------------------------
# IP related
netscan_enabled = True
listscan_enabled = True
IP_NET = ""
IP_MASK = ""
IP_START = ""
IP_END = ""
host_ip = "" # ip address of host running this script
host_mac = "" # mac address of host running this script
host_net = False # host runnin this script in the network to scan?
ipalive = [] # list of dictionaries containing ip, host, mac and ports
"""
[
{'ip': '192.168.001.001', 'hostname': '', 'mac': '', 'ports': [9, 22, 53, 80, 139, 515, 8000]},
{'ip': '192.168.001.002', 'hostname': '', 'mac': '', 'ports': []},
{'ip': '192.168.001.003', 'hostname': '', 'mac': '', 'ports': []},
{'ip': '192.168.001.004', 'hostname': '', 'mac': '', 'ports': [80, 443]},
...
]
"""
ipal = [] # simple list of ip addresses alive
ipna = [] # simple list of ip addresses not alive
#---------------------------------------------------------------------------------------------------
# Port scan related
port_advisory = True
port_timeout = 2 # Socket timeout in seconds
port_threads = []
portthread_count = 20 # Number of threads to use for scanning
netportscan_enabled = False
netportdesc_enabled = False # add desciption
netport_start = 1
netport_end = 1024
netports_open = [] # list of open ports for specific IP during a full net scan
"""
[21, 80, 443]
"""
listportscan_enabled = False
listportdesc_enabled = False
listportscan_info = False
listport_start = 1
listport_end = 1024
list_count = 0
list_cntr = 0
port_queue = Queue() # queue to hold the ports to be scanned
thread_lock = threading.Lock() # Thread-safe lock for printing/adding to open_ports list
PortsDict = {} # dictionary with ports listed in YAML file
"""
{ ... 146: 'ISO-IP0', 147: 'ISO-IP', '148': 'Jargon', ....}
"""
ports_open = [] # list of ports open found during a port scan
"""
[21, 80, 443]
"""
ports_list = [] # list of ports listed in Scanlist Eg: [0, 21, 8009]
ports_mdns = {} # dictionary which will list mdns ports for a n ip address
"""
[
...
"192.168.001.061": [8009],
"192.168.001.017": [0, 21],
"192.168.001.050": [0],
...
}
"""
#---------------------------------------------------------------------------------------------------
#mDNS scan related
mDNSscan_enabled = False
mDNS_timeout = 180
mDNS_timeend = 0
mDNSfile = ""
mDNS_listed = {} # dictionary of dictionaries of listed services
"""
{
...
'_afpovertcp._tcp.local.': Service(
name='AFPOVERTCP',
devices=[]
),
'_googlecast._tcp.local.': Service(
name='CHROMECAST',
devices=[
Device(
ip='192.168.001.061',
host='ChromeCast-Bedroom.home',
port=8009,
props=[
'path: /',
'version: 1.11.2',
'api: 0.1',
'id: edc78a56-'
],
weight=0,
priority=0,
text="some text"
)
]
),
'_device-info._tcp.local.': Service(
name='DEVICE INFO',
devices=[
Device(
ip='192.168.001.017',
host='storage2.home',
port=0,
props=[]
weight=0,
priority=0,
text="some text"
),
Device(
ip='192.168.001.049',
host='volumio-living.home',
port=0,
props=[],
weight=0,
priority=0,
text="some text"
)
]
),
....
}
"""
mDNS_unlisted = {} # dictionary of dictionaries of unlisted mDNS services
"""
same format az mDNS_listed
"""
mDNS_count = 0
mDNS_cntr = 0
#---------------------------------------------------------------------------------------------------
# SMTP related
smtp_enabled = False
smtpserver = "smtpserver"
smtpport = 587
smtptls = True
smtpCA = False
smtplogin = ""
smtppass = ""
From = ""
To = ""
#---------------------------------------------------------------------------------------------------
#syslog related
syslog_enabled = False
syslogserver = ""
syslogport = 0
FACILITY = {
'kern': 0, 'user': 1, 'mail': 2, 'daemon': 3,
'auth': 4, 'syslog': 5, 'lpr': 6, 'news': 7,
'uucp': 8, 'cron': 9, 'authpriv': 10, 'ftp': 11,
'local0': 16, 'local1': 17, 'local2': 18, 'local3': 19,
'local4': 20, 'local5': 21, 'local6': 22, 'local7': 23,
}
LEVEL = {
'emerg': 0, 'alert': 1, 'crit': 2, 'err': 3,
'warning': 4, 'notice': 5, 'info': 6, 'debug': 7
}
#---------------------------------------------------------------------------------------------------
# Create a secure SSL context
sslcontext = ssl.create_default_context()
if smtptls:
try:
ssl._create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't verify HTTPS certificates by default
pass
####################################################################################################
### Classes
####################################################################################################
#---------------------------------------------------------------------------------------------------
# Class for ping
#---------------------------------------------------------------------------------------------------
ICMP_ECHO_REQUEST = 8
class Pinger():
""" Pings to a host -- the Pythonic way"""
def __init__(self, target_host, count=5, size=65, timeout=300, debug=False):
self.target_host = target_host
self.count = count
self.timeout = timeout / 1000 # convert to seconds - select uses seconds
self.size = size
self.debug = debug
def do_checksum(self, source_string):
"""Verify the packet integrity"""
if not isinstance(source_string, (bytes, str)):
raise TypeError("source_string must be bytes or str")
if not source_string:
return 0
pchecksum = 0
max_count = (len(source_string) // 2) * 2
count = 0
while count < max_count:
val = source_string[count + 1] * 256 + source_string[count]
pchecksum += val
pchecksum &= 0xffffffff
count += 2
if max_count < len(source_string):
last_byte = source_string[-1]
pchecksum += last_byte if isinstance(source_string, bytes) else ord(last_byte)
pchecksum &= 0xffffffff
pchecksum = (pchecksum >> 16) + (pchecksum & 0xffff)
pchecksum += (pchecksum >> 16)
answer = ~pchecksum & 0xffff
answer = (answer >> 8) | ((answer << 8) & 0xff00)
return answer
def receive_pong(self, sock, ID, timeout):
"""
Receive ping from the socket.
"""
time_remaining = timeout
while True:
start_time = time.time()
readable = select.select([sock], [], [], time_remaining)
time_spent = time.time() - start_time
if readable[0] == []: # Timeout
return
time_received = time.time()
recv_packet, addr = sock.recvfrom(1024)
icmp_header = recv_packet[20:28]
ptype, pcode, pchecksum, packet_ID, sequence = struct.unpack("bbHHh", icmp_header)
if packet_ID == ID:
bytes_In_double = struct.calcsize("d")
time_sent = struct.unpack("d", recv_packet[28:28 + bytes_In_double])[0]
return time_received - time_sent
time_remaining = time_remaining - time_spent
if time_remaining <= 0:
return
def send_ping(self, sock, ID):
"""
Send ping to the target host
"""
target_addr = socket.gethostbyname(self.target_host)
my_checksum = 0
# Create a dummy heder with a 0 checksum.
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)
bytes_In_double = struct.calcsize("d")
data = (192 - bytes_In_double) * "Q"
data = struct.pack("d", time.time()) + bytes(data.encode('utf-8'))
# Get the checksum on the data and the dummy header.
my_checksum = self.do_checksum(header + data)
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1)
ppacket = header + data
sock.sendto(ppacket, (target_addr, 1))
def ping_once(self):
"""
Returns the delay (in seconds) or none on timeout.
"""
icmp = socket.getprotobyname("icmp")
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except OSError as se:
if se.errno == 1:
raise PermissionError("ICMP messages can only be sent from root user processes.") from se
raise
except Exception as ee:
if self.debug:
print(f"Unexpected exception: {ee}")
raise
my_ID = os.getpid() & 0xFFFF
self.send_ping(sock, my_ID)
delay = self.receive_pong(sock, my_ID, self.timeout)
sock.close()
return delay
def ping(self):
"""
Run the ping process
"""
tmax=0
tmin=0
lost=0
ttot=0
for _ in range(self.count):
try:
delay = self.ping_once()
except socket.gaierror as se:
if self.debug:
print(f"Ping failed. (socket error: {se[1]})")
break
if delay is None:
# print("Ping failed. (timeout within %ssec.)" % self.timeout)
if self.debug:
print("Request timed out.")
delay = int(self.timeout * 1000)
lost = lost+1
else:
delay = int(delay * 1000)
if self.debug:
print(f"Reply from {self.target_host}",end = '')
print(f" time={delay:0.0f}ms")
tmax = max(tmax, delay)
tmin = min(tmin, delay)
ttot = ttot + delay
# convert lost to %
lost = int((lost/self.count)*100)
# calc average time
tavg = int(ttot/self.count)
return tmin, tmax, tavg, lost
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
# Class for mDNS listener
#---------------------------------------------------------------------------------------------------
class MyListener:
def __init__(self, zeroconf_instance, listed_services=None):
self.zeroconf = zeroconf_instance
self.all_services = listed_services
self.unlisted_services: Dict[str, Service] = {}
self.known_services = {key: value.name for key, value in listed_services.items()}
def add_service(self, _zeroconf, stype, name):
# normalize type
norm_type = stype.lower()
if not norm_type.endswith('.'):
norm_type += '.'
# Special case: discover service types
if stype == "_services._dns-sd._udp.local.":
ServiceBrowser(self.zeroconf, name, self)
return
info = self.zeroconf.get_service_info(stype, name)
if not info:
return
ip_address = socket.inet_ntoa(info.addresses[0]) if info.addresses else 'N/A'
host_name = info.server if info.server else 'N/A'
port = info.port
props = [
f"{key.decode('utf-8')}: {value.decode('utf-8') if value else ''}"
for key, value in info.properties.items()
if key and value
]
weight = info.weight if info.weight else 0
prio = info.priority if info.priority else 0
tmp = info.text.decode('utf-8', errors='replace') if info.text else ''
txt = re.sub(r'[^\x20-\x7E]', ' ', tmp)
device = Device(
ip = reformat_ip(ip_address, True),
host = host_name.split('.')[0].lower(),
port = port,
props = props,
weight = weight,
priority = prio,
text = txt
)
# Add to all_services
if norm_type not in self.all_services:
self.all_services[norm_type] = Service(name=norm_type.upper(), devices=[])
self.all_services[norm_type].devices.append(device)
# Add to unlisted_services if not in known_services
if norm_type not in self.known_services:
if norm_type not in self.unlisted_services:
self.unlisted_services[norm_type] = Service(name=norm_type.upper(), devices=[])
self.unlisted_services[norm_type].devices.append(device)
# needed methode but not used
def remove_service(self, _zeroconf, stype, name):
pass
# needed methode but not used
def update_service(self, _zeroconf, stype, name):
pass
#---------------------------------------------------------------------------------------------------
####################################################################################################
### Functions - callback
####################################################################################################
#---------------------------------------------------------------------------------------------------
def port_threadworker(ip, port):
"""
Callback function for the port threads
It gets a port from the queue and calls the scan_port function
"""
while not port_queue.empty():
port = port_queue.get()
scan_port(ip, port, True)
port_queue.task_done()
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
def mdns_on_service_state_change(_zeroconf: Zeroconf, service_type: str, name: str, state_change: ServiceStateChange):
"""
Callback function for the mDNS browser
It gets the information from the mDNS service being published
"""
ip = ""
host = ""
port = ""
if state_change is ServiceStateChange.Added:
# device = name.replace(service_type, "")[:-1]
info = _zeroconf.get_service_info(service_type, name)
if info:
# only get first IP address
for ip in info.parsed_scoped_addresses():
break
# check if IP address is IPV4
if is_ipv4(ip):
try:
socket.inet_aton(ip)
try:
host, _, _ = socket.gethostbyaddr(ip)
except:
host = "<not in DNS>"
except socket.error:
ip = " "
else:
ip = f"<{ip[0:14]}>"
ip_15 = reformat_ip(ip, True)
port = info.port
props = []
if info.properties:
for key, value in info.properties.items():
strkey = key.decode("utf-8")
if strkey != "" and 'board' not in strkey:
if value is not None:
strvalue = value.decode("utf-8")
else:
strvalue = "None"
line = f"{strkey}: {strvalue}"
if line not in props:
props.append(line)
weight = info.weight if info.weight else 0
prio = info.priority if info.priority else 0
tmp = info.text.decode('utf-8', errors='replace') if info.text else ''
txt = re.sub(r'[^\x20-\x7E]', ' ', tmp)
new_device = Device(ip_15, host, port, props, weight, prio, txt)
mDNS_listed[service_type].devices.append(new_device)
#---------------------------------------------------------------------------------------------------
####################################################################################################
### Functions
####################################################################################################
#---------------------------------------------------------------------------------------------------
def getargs(argv):
"""
Function to get and test command line arguments
"""
global YAMLfile, DEBUG
global ScanList, IP_NET, IP_MASK
global NETfile
try:
opts, args = getopt.getopt(argv,"DY:P:N:M:")
except getopt.GetoptError:
print(strScriptBase + " host [-D] [ -Y YAML-filename ] [ -P ScanList-filename ] -N net_to_scan [-M mask ]")
sys.exit(1)
for opt, arg in opts:
if opt == '-D':
DEBUG = True
elif opt in ("-Y"):
YAMLfile = arg
YAMLfile = os.path.join(strScriptPath, YAMLfile)
if os.path.exists(YAMLfile):
pass
else:
print(f"Error: {YAMLfile} not found")
sys.exit(2)
elif opt in ("-P"):
ScanList = arg
ScanList = os.path.join(strScriptPath, ScanList)
if os.path.exists(ScanList):
loadScanDict()
else:
print(f"Error: {ScanList} not found")
sys.exit(2)
elif opt in ("-N"):
IP_NET = arg
NETfile = os.path.join(strScriptPath, strScriptBase + f"_{IP_NET}.net")
elif opt in ("-M"):
IP_MASK = arg
if IP_NET == "":
print("Error: -N <net_to_scan> is a mandatory option.")
print("Eg: -N 192.168.1")
sys.exit(3)
if IP_MASK == "":
IP_MASK = "255.255.255.0"
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
def loadScanDict():
"""
Function to load all line entries from a list to scan into a dictionary
IP address gets formatted in 111.111.111.111 format
"""
with open(ScanList, "r", encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if len(line) > 0:
if line[0] != '#':
if line.count(";") != -1:
parts = line.split(";")
hostname = parts[0].strip()
ip = parts[1].strip()
ip_15 = reformat_ip(ip, True)
ScanDict[ip_15] = hostname
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
def port_scanning_advisory():
advisory = """
################################################################################
This application includes port scanning that can help you diagnose
your network for issues, discover services, and improve security.
However, this comes with responsibility.
Before you scan for ports, please keep these best practices in mind:
Scan Only What You Own or Have Permission:
Always ensure you have explicit authorization before scanning any network.
Unauthorized scans can be seen as hostile activity and may violate laws.
Respect Network Stability:
Aggressive or frequent scans can overload systems or trigger alarms.
Use scanning features thoughtfully.
Avoid scanning production environments without proper planning.
Stay Compliant:
Port scanning may be restricted by local regulations or organizational terms.
Make sure your usage aligns with all applicable rules.
Be Transparent:
If you're scanning within a shared or corporate environment
notify relevant stakeholders.
Transparency builds trust and avoids unnecessary confusion or concern.
Use It as a Tool, Not a Weapon:
Port scanning is a valuable diagnostic and security resource
but misuse can lead to serious consequences.
Use it to strengthen systems, not probe them without cause.
################################################################################
"""
print(advisory)
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
def is_service_running(service_name):
"""
Function to check is a service is running
OS sensitive
"""
os_type = platform.system().lower()
ret = False
try:
if os_type == "windows":
result = subprocess.run(["sc", "query", service_name], capture_output=True, text=True, check=True)
if "RUNNING" in result.stdout:
ret = True
if os_type == "linux":
result = subprocess.run(["systemctl", "is-active", service_name], capture_output=True, text=True, check=True)
if "active" in result.stdout:
ret = True
if os_type == "darwin": # macOS
result = subprocess.run(["launchctl", "list"], capture_output=True, text=True, check=True)
if service_name in result.stdout:
ret = True
return ret
except:
return ret
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
def flush_ipcache():
"""
Function to flush IP cache
OS sesnsitive
"""
os_type = platform.system().lower()
try:
if os_type == "windows":
subprocess.run(["ipconfig", "/flushdns >nul"], shell=True, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
elif os_type == "linux":
# Try systemd-resolved first
result = subprocess.run(["systemctl", "is-active", "systemd-resolved"], capture_output=True, text=True, check=False)
if "active" in result.stdout:
subprocess.run(["sudo", "systemd-resolve", "--flush-caches"], check=True)
else:
# Fallback to dnsmasq
subprocess.run(["sudo", "service", "dnsmasq", "restart"], check=True)
elif os_type == "darwin": # macOS
subprocess.run(["sudo", "killall", "-HUP", "mDNSResponder"], check=True)
else:
print(f"Unsupported OS: {os_type}")
sys.exit(4)
except subprocess.CalledProcessError:
pass
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
def get_mac_address_and_hostname(ip_address):
"""
Function to get Hostname and MAC address from a IP address
Windows only
"""
mac_address = None
hostname = None
if platform.system().lower() == "windows":
cmd = "arp -a"
else:
cmd = "arp"
try:
with subprocess.Popen([cmd, ip_address], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as process:
stdout, stderr = process.communicate()
output = stdout.decode()
lines = output.splitlines()
for line in lines:
if ip_address in line:
parts = line.split()
if len(parts) >= 2:
# Windows uses hyphens, convert to colons
mac_address = parts[1].replace("-", ":")
break
try:
hostname = socket.gethostbyaddr(ip_address)[0]
except socket.herror:
hostname = None
except:
return None, None
return mac_address, hostname
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
def sendmail(From, To, Subject, Body, Attach = ""):
"""
General function to send mails
Windows only
"""
msg = MIMEMultipart()
msg['From'] = From
msg['To'] = To
msg['Subject'] = Subject
msg.attach(MIMEText(Body, 'plain'))
if Attach != "":
with open(Attach, "rb", encoding="utf-8") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename= {Attach}")
msg.attach(part)
server = smtplib.SMTP(smtpserver, smtpport)
try:
if smtptls and not smtpCA:
server.starttls() # Secure the connection
elif smtptls and smtpCA:
server.starttls(sslcontext) # Secure the connection
if smtplogin is not None:
if smtplogin != "":
server.login(smtplogin, smtppass)
text = msg.as_string()
server.sendmail(From, To, text)
except:
pass
finally:
server.quit()
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
def syslog(message, level=LEVEL['notice'], facility=FACILITY['user'], host='localhost', port=514, proto=0, hostname = "myhost", appname = "myapp"):
"""
Send syslog UDP packet to given host and port.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
dt = datetime.now()
if proto == 0:
dts = dt.strftime("%b %d %H:%M:%S")
data = f"<{level + facility*8}>{dts} {hostname} {appname}: {message}"
else:
dts = dt.strftime("%Y-%m-%dT%H:%M:%S.000Z")
version = 1
data = f"<{level + facility*8}>{version} {dts} {hostname} {appname} - - - \xEF\xBB\xBF{message}"
sock.sendto(str.encode(data), (host, port))
sock.close()
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
def print_services(services: Dict[str, Service]):
"""
helper to print mDNS dictionaries in a readable format
"""
for service_type, service in list(services.items()):
print(f"\nService Type: {service_type}")
print(f" Friendly Name: {service.name}")
print(f" Devices ({len(service.devices)}):")
for device in service.devices:
print(f" IP: {device.ip}")
print(f" Host: {device.host}")
print(f" Port: {device.port}")
if device.props:
print(" Properties:")
for prop in device.props:
print(f" - {prop}")
else:
print(" Properties: None")
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
def services_count(service_dict):
"""
Counts the number of services that have at least one device with an IP address,
and the number of unique IP addresses across all services.
"""
unique_ips = set()
services_with_ips = 0
for service in service_dict.values():
service_has_ip = False
for device in service.devices:
if device.ip:
unique_ips.add(device.ip)
service_has_ip = True
if service_has_ip:
services_with_ips += 1
return services_with_ips, len(unique_ips)
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
def ignore_extra(props, extra):
# Extract the text portion
try:
text_part = extra.split("text:")[1].strip()
except IndexError:
return True
# Check each key-value pair
for item in props:
if ':' not in item:
# skip malformed entries
continue
key, value = item.split(':', 1)
key = key.strip()
value = value.strip()
if f"{key}={value}" in text_part:
return True
# Check weight and priority
if "weight: 0" in extra and "priority: 0" in extra:
return True
return False
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
def is_empty_extra(extra):