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

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

python 复制代码
'''
通过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
相关推荐
小白学大数据28 分钟前
基于文本检测的 Python 爬虫弹窗图片定位与拖动实现
开发语言·爬虫·python
老蒋新思维31 分钟前
创客匠人启示录:AI 时代知识变现的底层逻辑重构 —— 从峰会实践看创始人 IP 的破局之路
网络·人工智能·网络协议·tcp/ip·数据挖掘·创始人ip·创客匠人
努力的BigJiang1 小时前
ORB-SLAM2在ubuntu20.04中的复现记录(跑数据集+ROS)(ROS接口失败版)
python
码农爱学习1 小时前
使用wpa工具配网、udhcpc分配IP的过程分析
网络·网络协议·tcp/ip
老蒋新思维2 小时前
创客匠人深度洞察:创始人 IP 打造的非线性增长模型 —— 知识变现的下一个十年红利
大数据·网络·人工智能·tcp/ip·重构·数据挖掘·创客匠人
计算机学姐2 小时前
基于Python的商场停车管理系统【2026最新】
开发语言·vue.js·后端·python·mysql·django·flask
ujainu2 小时前
Flutter + HarmonyOS开发:轻松实现ArkTS页面跳转
人工智能·python·flutter
小猪快跑爱摄影2 小时前
【AutoCad 2025】【Python】零基础教程(一)——简单示例
开发语言·python
秋刀鱼 ..2 小时前
【IEEE出版】第五届高性能计算、大数据与通信工程国际学术会议(ICHBC 2025)
大数据·人工智能·python·机器人·制造·新人首发
测试19983 小时前
软件测试之压力测试
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·压力测试