• 通过python 获取当前局域网内存在的IP和MAC


    通过python 获取当前局域网内存在的ip

    '''
    通过ipconfig /all 命令获取局域网所在的网段
    通过arp -d *命令清空当前所有的arp映射表
    循环遍历当前网段所有可能的ip与其ping一遍建立arp映射表
    for /L %i IN (1,1,254) DO ping -w 1 -n 1 192.168.3.%i
    通过arp -a命令读取缓存的映射表获取所有与本机连接的设备的Mac地址。
    '''
    import os
    import re
    import time
    from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
    import psutil# 逻辑cpu个数
    count = psutil.cpu_count()
    print("cpu个数:",str(count))
    import pandas as pd
    def get_net_segment():
        with os.popen("arp -a") as res:
            for line in res:
                line = line.strip()
                if line.startswith("接口"):
                    net_segment = re.findall("(\d+\.\d+\.\d+)\.\d+", line)[0]
                    break
            return net_segment
    def ping_net_segment_all(net_segment):
        # for i in range(1, 255):
        #     os.system(f"ping -w 1 -n 1 {net_segment}.{i}")
        # 多线程并发 5个线程时耗时是30秒,8个线程是28秒
        with ThreadPoolExecutor(max_workers=4) as executor:
            for i in range(1, 255):
                executor.submit(os.popen, f"ping -w 1 -n 1 {net_segment}.{i}")
    def get_arp_ip_mac():
        header = None
        list1 = []
        #os.system('arp -a > temp11.txt')
        with os.popen("arp -a") as res:
            for line in res:
                line = line.strip()         
                if not line or line.startswith("接口"):
                    continue
                if header is None:                
                    header = re.split(" {2,}", line.strip())
                line1 = re.split(" {2,}", line.strip())
                list1.append(line1)
    
        df = pd.DataFrame(list1,columns=header)
        return df
    def ping_ip_list(ips, max_workers=4):
        print("正在扫描在线列表")
        with ThreadPoolExecutor(max_workers=max_workers) as executor:
            future_tasks = []
            for ip in ips:
                future_tasks.append(executor.submit(os.popen, f"ping -w 1 -n 1 {ip}"))
                wait(future_tasks, return_when=ALL_COMPLETED)
    if __name__ == '__main__':
        # 是否进行初始扫描
        init_search = True #False
        if init_search:
            print("正在扫描当前网段所有ip,预计耗时1分钟....")
            ping_net_segment_all(get_net_segment())
        last = None
        while 1:
            df = get_arp_ip_mac()
            df = df.loc[df.类型 == "动态", ["Internet 地址", "物理地址"]]
            if last is None:
                print("当前在线的设备:")
                print(df)
            else:
                online = df.loc[~df.物理地址.isin(last.物理地址)]
                if online.shape[0] > 0:
                    print("新上线设备:")
                    print(online)
                offline = last[~last.物理地址.isin(df.物理地址)]
                if offline.shape[0] > 0:
                    print("刚下线设备:")
                print(offline)
            time.sleep(5)
            ping_ip_list(df["Internet 地址"].values)
            last = df
    
    
    • 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
  • 相关阅读:
    C# 值类型调用ToString一定会装箱吗?
    计算机网络——第五章网络层笔记(4)
    python文本转语音
    Hive学习笔记:05Hive中常用分析函数使用解析
    深度学习基础
    c++ 原子变量-Memory fence
    STCH8高级PWM定时器输入捕获功能脉宽测量
    MySQL详细学习教程(建议收藏)
    Appium学习日记(一)——Appium工作原理及其主要组件
    Flutter学习笔记 —— 完成一个简单的新闻展示页
  • 原文地址:https://blog.csdn.net/jhui123456/article/details/132626787