UltraDebug

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: A C D R G Y M Z X S P
公益项目,接受捐赠
查看: 2525|回复: 0
收起左侧

[Python] Python一键扫描局域网在线IP和对应Mac地址

[复制链接]
English

主题

0

回帖

UD

新手上路

UID
34
积分
34
注册时间
2022-4-4
最后登录
1970-1-1
2022-8-13 22:52:58 | 显示全部楼层 |阅读模式
使用多线程扫描局域网在线IP和对应Mac地址,新鲜出炉的代码,可以搭配其他局域网工具来使用。
二楼有个更简洁的2.0版本
Python一键扫描局域网在线IP和对应Mac地址 - English_UltraDebug 扫描IP和Mac地址.zip (978 Bytes, 下载次数: 0)
[Python] 纯文本查看 复制代码
import os
import re
import threading
 
ips = []

def local_ip_mac():  #本机IP和MAC
    output = os.popen('ipconfig /all')
    for i in output:
        if '物理地址.' in i:
            mac = i.split(':')[1].strip()
        if 'IPV4' in i.upper() and '(' in i:
            ip = i.split(':')[1].split('(')[0].strip()
    if ip and mac:
        return [ip, mac]
 
def ip_online(ip):  #判断IP是否在线
    cmd = f'ping -n 1 {ip}'
    output = os.popen(cmd)
    if any('TTL' in i.upper() for i in output):
        ips.append(ip)

def ip2mac(ip):  #通过IP查MAC
    loc_ip, mac = local_ip_mac()
    if ip == loc_ip:
        return mac
    cmd = f'arp -a {ip}'
    output = os.popen(cmd)
    outstr = ' '.join(list(output))
    if '未找到 ARP 项' not in outstr:  #排除本机
        macs = re.findall('(([A-Fa-f0-9]{2}-){5}[A-Fa-f0-9]{2})', outstr, re.S)
        for i in macs[0]:
            if len(i) == 17:
                return i
 
def speed_up(func, args_list):  #多线程
    thread_list = []
    for i in args_list:
        t = threading.Thread(target=func, args=(i, ))
        thread_list.append(t)
    for t in thread_list:
        t.start()
    t.join()
 
if __name__ == '__main__':
    print('扫描中,稍等片刻...')
    loc_ip, mac = local_ip_mac()
    ip_range = '.'.join(loc_ip.split('.')[:-1])  #通过本机IP拼接IP段
    ip_list = [f'{ip_range}.{i+1}' for i in range(255)]
    speed_up(ip_online, ip_list)  #多线程扫描
    res = [(i, ip2mac(i)) for i in sorted(ips)]
    print('扫描结果:', sorted(res))
SyntaxHighlighter Copyright 2004-2013 Alex Gorbatchev.
UltraDebug免责声明
✅以上内容均来自网友转发或原创,如存在侵权请发送到站方邮件9003554@qq.com处理。
✅The above content is forwarded or original by netizens. If there is infringement, please send the email to the destination 9003554@qq.com handle.
回复 打印

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|Archiver|站点地图|UltraDebug ( 滇ICP备2022002049号-2 滇公网安备 53032102000034号)

GMT+8, 2025-6-21 01:30 , Processed in 0.029033 second(s), 9 queries , Redis On.

Powered by Discuz X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表