通过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
相关推荐
geovindu5 分钟前
python: Generators Pattern
开发语言·python·设计模式·生成器模式
没有不重的名么6 分钟前
spyder使用教程
开发语言·python
Wonderful U7 分钟前
Python+Django实战|线上问卷与投票调研系统:自定义题型、问卷发布、链接分享、答卷收集、数据可视化、报表导出
python·信息可视化·django
Cloud_Shy61816 分钟前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 36 - 39)
开发语言·人工智能·笔记·python
zmzb010317 分钟前
Python课后习题训练记录Day128
开发语言·python
AIFQuant17 分钟前
全球行情自动更新、多品种展示、性能优化实战指南
python·性能优化·金融·node.js·restful
蜂蜜黄油呀土豆20 分钟前
ReWOO 与 Plan-and-Execute:解耦的规划
python·ai·大模型
去码头整点薯条ing22 分钟前
某红书笔记接口逆向【x-s参数】
javascript·爬虫·python
xxie12379424 分钟前
参数Parameter,形参Formal Parameter,实参Actual Argument
开发语言·python
love530love26 分钟前
Hermes-Agent 本地化部署与详细交互式配置实战指南 [LM Studio + QQ ]
人工智能·windows·python·aigc·agent·hermes·hermes-agent