获取局域网 Mac 地址

1、使用 ipconfig/all 命令,可以找到当前所处的网段。

import os, re

res = os.popen('ipconfig /all').read()
pattern = re.compile(r'((?:25[0-5]|2[0-4]\d|1?\d{1,2})\.){3}(?:25[0-5]|2[0-4]\d|1?\d{1,2})')
res =  pattern.search(res)
try:
    network_segment = res.group(0).rsplit('.',1)[0]
    print(network_segment)
except Exception as e:
    print(e)
# 或者
import os, re, pandas as pd

res_ip = os.popen('ipconfig /all').read().split('\n')
info = {item.split(':')[0].strip().strip('. '):item.split(':')[1].strip() for item in res_ip if ':' in item}

host_name = info['Host Name']
ipv4_address = info['IPv4 Address']
physical_address = info['Physical Address']
network_segment = info['IPv4 Address'].rsplit('.',1)[0]

2、逐个 ping 网段内的 IP ,这一步是为了建立 ARP 表。

os.popen(f'for /L %i IN (1,1,254) DO ping -w 1 -n 1 {network_segment}.%i')

3、使用 arp 命令可以查询所有的 Mac 地址

res_arps = os.popen('arp -a').read().split('\n')
res = [line.split('   ') for line in res_arps if line][1:]
res = [[x.strip() for x in y if x.strip()] for y in res]

df = pd.DataFrame(res[1:],columns=res[0])

完整代码

import time, os, re, pandas as pd, easygui as g

def get_segment():
    res_ip = os.popen('ipconfig /all').read().split('\n')
    info = {item.split(':')[0].strip().strip('. '):item.split(':')[1].strip() for item in res_ip if ':' in item}

#     host_name = info['Host Name']
#     ipv4_address = info['IPv4 Address']
#     physical_address = info['Physical Address']
    network_segment = info['IPv4 Address'].rsplit('.',1)[0]
    return network_segment

def get_mac(network_segment):
    os.popen(f'for /L %i IN (1,1,254) DO ping -w 1 -n 1 {network_segment}.%i')
    
    res_arps = os.popen('arp -a').read().split('\n')
    res = [line.split('   ') for line in res_arps if line][1:]
    res = [[x.strip() for x in y if x.strip()] for y in res]

    df = pd.DataFrame(res[1:],columns=res[0])
    return list(df['Physical Address'])

if __name__ == '__main__':
    boss_mac = '04-4f-**-**-47-5f' # 要监控的手机的 mac 地址
    network_segment = get_segment()
    sleep_time = 5
    
    while True:
        time.sleep(sleep_time)
        if boss_mac in get_mac(network_segment):            
            sleep_time = 300 # 如果 boss 来了,就隔5分钟扫描一次
            choice = g.msgbox(msg="The boss is here", title="OMG") # 提示报警
    
        else:
            sleep_time = 5
            g.msgbox(msg="Everything's fine!", title="OMG")