通过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
相关推荐
今天也要加油丫4 分钟前
`re.compile(r“(<.*?>)“)` 如何有效地从给定字符串中提取出所有符合 `<...>` 格式的引用
python
tekin1 小时前
macos macport软件包管理工具 sudo port install xxx 安装的软件的路径 与 brew install xxx 软件安装路径总结
macos·brew·port·macport·port install·port软件包安装路径·brew软件包安装路径
农民小飞侠1 小时前
python AutoGen接入开源模型xLAM-7b-fc-r,测试function calling的功能
开发语言·python
战神刘玉栋1 小时前
《程序猿之设计模式实战 · 观察者模式》
python·观察者模式·设计模式
敲代码不忘补水1 小时前
Python 项目实践:简单的计算器
开发语言·python·json·项目实践
运维Z叔2 小时前
云安全 | AWS S3存储桶安全设计缺陷分析
android·网络·网络协议·tcp/ip·安全·云计算·aws
鸽芷咕2 小时前
【Python报错已解决】ModuleNotFoundError: No module named ‘paddle‘
开发语言·python·机器学习·bug·paddle
子午3 小时前
动物识别系统Python+卷积神经网络算法+TensorFlow+人工智能+图像识别+计算机毕业设计项目
人工智能·python·cnn
风等雨归期3 小时前
【python】【绘制小程序】动态爱心绘制
开发语言·python·小程序
Adolf_19933 小时前
Flask-JWT-Extended登录验证, 不用自定义
后端·python·flask