python获取mac地址_使用Python从设备获取MAC地址

1586010002-jmsa.png

I'm looking for a way (with python) to obtain the layer II address from a device on my local network. Layer III addresses are known.

The goal is to build a script that will poll a databases of IP addresses on regular intervals ensuring that the mac addresses have not changed and if they have, email alerts to myself.

解决方案

To answer the question with Python depends on your platform. I don't have Windows handy, so the following solution works on the Linux box I wrote it on. A small change to the regular expression will make it work in OS X.

First, you must ping the target. That will place the target -- as long as it's within your netmask, which it sounds like in this situation it will be -- in your system's ARP cache. Observe:

13:40 jsmith@undertow% ping 97.107.138.15

PING 97.107.138.15 (97.107.138.15) 56(84) bytes of data.

64 bytes from 97.107.138.15: icmp_seq=1 ttl=64 time=1.25 ms

^C

13:40 jsmith@undertow% arp -n 97.107.138.15

Address HWtype HWaddress Flags Mask Iface

97.107.138.15 ether fe:fd:61:6b:8a:0f C eth0

Knowing that, you do a little subprocess magic -- otherwise you're writing ARP cache checking code yourself, and you don't want to do that:

>>> from subprocess import Popen, PIPE

>>> import re

>>> IP = "1.2.3.4"

>>> # do_ping(IP)

>>> # The time between ping and arp check must be small, as ARP may not cache long

>>> pid = Popen(["arp", "-n", IP], stdout=PIPE)

>>> s = pid.communicate()[0]

>>> mac = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", s).groups()[0]

>>> mac

"fe:fd:61:6b:8a:0f"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值