为什么用python获取mac地址会变动?

Python013

为什么用python获取mac地址会变动?,第1张

首先声明,我本人还没有研究出来问题的究竟。此处只是写下我本人的一点小心得,大家一起进步。

因为我发现,使用uuid库得到的mac地址,总有最后一位不对。所以,我就查看了python官方的uuid文档,找到了问题的关键是调用UUID()的时候,会调用getnode()函数以得到物理地址。

这个是getnode()函数的定义:

我把它摘出来,考到下面。

def getnode(*, getters=None):

"""Get the hardware address as a 48-bit positive integer.

The first time this runs, it may launch a separate program, which could

be quite slow.  If all attempts to obtain the hardware address fail, we

choose a random 48-bit number with its eighth bit set to 1 as recommended

in RFC 4122.

"""

global _node

if _node is not None:

return _node

if sys.platform == 'win32':

getters = _NODE_GETTERS_WIN32

else:

getters = _NODE_GETTERS_UNIX

for getter in getters + [_random_getnode]:

try:

_node = getter()

except:

continue

if (_node is not None) and (0 <= _node <(1 <<48)):

return _node

assert False, '_random_getnode() returned invalid value: {}'.format(_node)

我正在试图通过研究这个问题来试图研究。但同样,我觉得我们可以直接让python调用系统库,从而执行系统自带的命令:(类似于windows下cmd里面"ipconfig -all"命令,或者ubuntu下terminal中"ifconfig"命令)。实现物理地址。之后,根据“短时间内该机器的网卡不会出现过大的变动这个前提”,我们可以根据返回内容,切片出我们需要的部分即可。

这个需要安装一个模块scapy

代码如下:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

from scapy.all import srp,Ether,ARP,conf

ipscan='192.168.1.1/24'

try:

    ans,unans = srp(Ether(dst="FF:FF:FF:FF:FF:FF")/ARP(pdst=ipscan),timeout=2,verbose=False)

except Exception,e:

    print str(e)

else:

    for snd,rcv in ans:

        list_mac=rcv.sprintf("%Ether.src% - %ARP.psrc%")

        print list_mac