可执行系统:Linux

查询某个网段有哪些 空闲IP 与 繁忙IP

import ipaddress
import subprocess
import threading

idle = []
Busy = []
BLUE = '\033[94m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'

def check_ip(ip):
    result = subprocess.call(['ping', '-c', '1', '-W', '1', str(ip)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    if result == 0:
        Busy.append(ip)
    else:
        idle.append(ip)

def scan_network(network):
    ip_network = ipaddress.ip_network(network)
    threads = []
    
    for ip in ip_network.hosts():
        thread = threading.Thread(target=check_ip, args=(ip,))
        threads.append(thread)
        thread.start()
    
    for thread in threads:
        thread.join()

if __name__ == '__main__':
    network = input("请输入您要搜索的网段 (e.g., 10.10.1.0/24): ")
    showIdle = input("是否显示空闲IP (Y/n): ")
    showbusy = input("是否显示繁忙IP (Y/n): ")
    if showIdle.title() != 'N':
        showIdle = 'Y'
    if showbusy.title() != 'N':
        showbusy = 'Y'        
    try:
        scan_network(network)

        if showIdle.title() == 'Y' :
            print(f"{BLUE}空闲IP数量: {len(idle)}{ENDC}")
            for ip in idle:
                print(f"\t{ip}")
        if showbusy.title() == 'Y' :
            print(f"\n\n{YELLOW}繁忙IP数量: {len(Busy)}{ENDC}")
            for ip in Busy:
                print(f"\t{ip}")
    except Exception as e:
        print(f"{RED}Search segment error: {e}{ENDC}")