Python 扫描局域网存活设备

TanHaX
2024-03-20 / 0 评论 / 29 阅读 / 正在检测是否收录...
大无语了临近考试还在这里本末倒置的瞎搞!

写这个没有什么技术含量的小工具,望各位大佬多担待一下。最近朋友的出租屋的网络出现多个DHCP服务器, 路由器有时候动态获取错误地址,所以使用 Python 编写了这个简单小工具以便了解局域网中哪些 IP 地址正在被使用和其主机名和MAC地址等信息(获取主机名和MAC还有点问题)。

目前计划这个扫描工具实现以下功能:

import ipaddress
import socket
import subprocess


def scan_local_network(subnet=None):
    if subnet is None:
        local_ip = socket.gethostbyname(socket.gethostname())
        subnet = ipaddress.ip_network(local_ip+'/24', strict=False)

    live_hosts = []
    total_hosts = sum(1 for _ in subnet.hosts())
    scanned_hosts = 0

    for host in subnet.hosts():
        scanned_hosts += 1
        host = str(host)
        ping_process = subprocess.Popen(['ping', '-n', '1', '-w', '100', host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        ping_output, _ = ping_process.communicate()

        if "TTL=" in ping_output.decode('gbk'):
            live_hosts.append((host, ping_output.decode('gbk')))

        print(f"扫描进度:{scanned_hosts}/{total_hosts}", end='\r')

    return live_hosts

def parse_ping_output(output):
    result = {
        "hostname": "",
        "mac_address": "",
        "status": "Offline"
    }

    # 提取主机名
    for line in output.splitlines():
        if line.startswith("Reply from"):
            hostname = line.split(" ")[2]
            result["hostname"] = hostname.replace(":", "")
            break

    # 提取 MAC 地址
    for line in output.splitlines():
        if line.startswith("MAC Address"):
            mac_address = line.split(":")[1].strip()
            result["mac_address"] = mac_address
            break

    # 判断端口状态
    if "unreachable" not in output:
        result["status"] = "Online"

    return result

def main():
    # ASCII
    ascii_art = """

        .--,       .--,
       ( (  \.---./  ) )
        '.__/o   o\__.'
           {=  ^  =}
            >  -  <
           /       \\
          //       \\\\
         //|   .   |\\\\
         "'\       /'"_.-~^`'-.
            \  _  /--'         `
          ___)( )(___
         (((__) (__))) 
            
    .............................................
    ping值稳定测精准     TanHaX     网络通畅似流云舒。
    """
    print(ascii_art)

    print("欢迎使用局域网IP扫描工具!")
    subnet = input("请输入要扫描的网段(例如 192.168.1.0/24),或 按回车键默认使用本地网段:")
    
    if subnet:
        try:
            subnet = ipaddress.ip_network(subnet, strict=False)
            live_hosts = scan_local_network(subnet)
        except ValueError:
            print("输入的网段格式不正确!")
    else:
        live_hosts = scan_local_network()

    if live_hosts:
        print("\n以下IP地址在使用中:")
        for host, output in live_hosts:
            parsed_data = parse_ping_output(output)
            print(f"[IP] {host}  [Hostname] {parsed_data['hostname']}  [MAC] {parsed_data['mac_address']} [Status] {parsed_data['status']}")
        print("扫描完成!")
    else:
        print("未发现任何活跃的主机。")

if __name__ == "__main__":
    main()
    


成功实现这个小老鼠

pFWT7gH.png

1

打赏

评论 (0)

取消