Skip to content

Instantly share code, notes, and snippets.

@st1vms
Last active August 5, 2024 12:19
Show Gist options
  • Save st1vms/65988c3cdda1f125df05538da45431e9 to your computer and use it in GitHub Desktop.
Save st1vms/65988c3cdda1f125df05538da45431e9 to your computer and use it in GitHub Desktop.
Network device discovery tool using ICMP (ping) requests.
#!/usr/bin/env python3
# requirements -> pip install ping3
import re
import multiprocessing
from multiprocessing import Lock, cpu_count, Manager
from ping3 import ping
__DEFAULT_NET_ADDR_PART = "192.168.1"
__N_PROCESSES = cpu_count() - 1
__GLOBAL_LOCK = Lock()
def __crawl(
out_list: list[str], net_addr_part: str, host_nums: list[int], verbose: bool
):
global __GLOBAL_LOCK
for hn in host_nums:
host = f"{net_addr_part}.{hn}"
response = ping(host, timeout=1, unit="ms")
if response is not None:
if response:
if verbose:
print(f"\nHost answered ping -> {host}")
with __GLOBAL_LOCK:
out_list.append(host)
continue
def ping_network(
netw_addr_part: str = __DEFAULT_NET_ADDR_PART, verbose: bool = False
) -> list[str]:
with Manager() as manager:
res = manager.list()
host_nums = list(range(1, 129))
batches = [
host_nums[i::__N_PROCESSES]
for i in range(__N_PROCESSES)
if host_nums[i::__N_PROCESSES]
]
processes = []
for b in batches:
p = multiprocessing.Process(
target=__crawl, args=(res, netw_addr_part, b, verbose)
)
p.start()
processes.append(p)
for p in processes:
p.join()
return sorted(list(res))
if __name__ == "__main__":
def __check_net_addr(s: str) -> bool:
network_pattern = r"^(\d{1,3}\.){2}\d{1,3}$"
return not not re.match(network_pattern, s)
net_addr = input(
f"\nInsert network address part (Default: {__DEFAULT_NET_ADDR_PART})\n>>"
).strip()
if not net_addr:
net_addr = __DEFAULT_NET_ADDR_PART
if __check_net_addr(net_addr):
ping_network(net_addr, verbose=True)
else:
print("Invalid network address part.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment