通过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
相关推荐
秃了也弱了。6 小时前
python实现定时任务:schedule库、APScheduler库
开发语言·python
Dfreedom.6 小时前
从 model(x) 到__call__:解密深度学习框架的设计基石
人工智能·pytorch·python·深度学习·call
weixin_425023007 小时前
Spring Boot 配置文件优先级详解
spring boot·后端·python
better_liang7 小时前
每日Java面试场景题知识点之-TCP/IP协议栈与Socket编程
java·tcp/ip·计算机网络·网络编程·socket·面试题
小徐Chao努力8 小时前
【Langchain4j-Java AI开发】06-工具与函数调用
java·人工智能·python
无心水8 小时前
【神经风格迁移:全链路压测】33、全链路监控与性能优化最佳实践:Java+Python+AI系统稳定性保障的终极武器
java·python·性能优化
luoluoal8 小时前
基于python的小区监控图像拼接系统(源码+文档)
python·mysql·django·毕业设计·源码
BoBoZz199 小时前
MotionBlur 演示简单运动模糊
python·vtk·图形渲染·图形处理
十八度的天空9 小时前
第01节 Python的基础语法
开发语言·python
BoBoZz199 小时前
GradientBackground 比较不同类型的背景渐变着色模式与坐标转换
python·vtk·图形渲染·图形处理