通过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
相关推荐
RSTJ_16254 分钟前
PYTHON+AI LLM DAY SEVENTY
人工智能·python·深度学习
财经资讯数据_灵砚智能7 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年6月8日
大数据·人工智能·python·ai·信息可视化·自然语言处理·灵砚智能
m沐沐13 分钟前
数据集的六种填充方法——下(使用众数填充+使用逻辑回归填充+使用随机森林填充)
python·随机森林·机器学习·pycharm·逻辑回归
TonyLee01713 分钟前
AutoDL租卡记录
服务器·python
m沐沐15 分钟前
【机器学习】7 种分类模型实战(逻辑回归→随机森林→SVM→AdaBoost→朴素贝叶斯→XGBoost→神经网络)
人工智能·pytorch·python·随机森林·机器学习·分类·逻辑回归
yijianace20 分钟前
Python爬虫学习记录—— BooksToScrape分页爬取与图片下载
爬虫·python
小白学大数据21 分钟前
如何自动追踪 eBay 售价?Python 爬虫实战解析
开发语言·人工智能·爬虫·python
ziyue757528 分钟前
python进行磁盘文件迁移,不影响软件使用
开发语言·数据库·python
abcy07121330 分钟前
Python与Hadoop HDFS进行异步文件上传
python
爱和冰阔落35 分钟前
【Python基础】从变量到面向对象:打通 Python 入门核心语法
开发语言·python