Untitled

 avatar
unknown
python
2 years ago
1.3 kB
6
Indexable
import asyncio
import subprocess
import ipaddress
import time
start_time = time.time()   

async def ping(ip):
    process = await asyncio.create_subprocess_shell(f"ping -n 1 {ip}",
                                                    stdout=subprocess.PIPE,
                                                    stderr=subprocess.PIPE)
    stdout, _ = await process.communicate()
    success = process.returncode == 0
    return success, stdout.decode()

async def ping_subnet(subnet):
    tasks = []
    for ip in subnet:
        tasks.append(asyncio.create_task(ping(str(ip))))
    results = await asyncio.gather(*tasks)
    for ip, (success, output) in zip(subnet, results):
        print(f"Ping to {ip} {'succeeded' if success else 'failed'}.")
        if success:
            latency = output.split('\n')[-2].split()[6]
            print(f"Latency to {ip} is {latency}")
        else:
            print(f"Error: {output.strip()}")
    print("TIME TOOK:"+str(time.time() - start_time))

subnet = input("Enter the subnet in CIDR notation (e.g. 192.168.0.0/24): ")
subnet = ipaddress.ip_network(subnet, strict=False)
addresses = list(subnet)
if subnet.prefixlen > 30:
    print("Invalid subnet prefix.")
else:
    asyncio.run(ping_subnet(addresses))
Editor is loading...