用Python提取MAC地址

MAC地址也称为物理地址,是分配给计算机NIC(网络接口卡)的唯一标识符。NIC帮助计算机与网络中的其他计算机连接。MAC地址对于所有NIC都是唯一的。

null

MAC地址的使用:

  • 在IP地址经常变化的地方很有用。帮助网络管理员。获取有关网络流量的信息。
  • 帮助我们配置哪些计算机可以连接到我们的计算机。通过这种方式,我们可以过滤潜在的垃圾邮件/病毒攻击。
  • 有助于从世界各地的其他计算机中唯一地识别计算机。

MAC-Address

本文旨在使用Python提取计算机的MAC地址。

方法1:使用mac模块 为了获得设备的物理地址,我们使用Python的getmac模块。

>>>from getmac import get_mac_address as gma
>>>print(gma())
'3c:7e:94:8f:d0:34'

方法2:使用uuid。getnode()

getnode()可用于提取计算机的MAC地址。此函数在中定义 乌伊德 单元 下面给出的演示代码显示了如何使用uuid1()函数为给定主机生成由其MAC地址标识的UUID。

# Python Program to compute
# MAC address of host
# using UUID module
import uuid
# printing the value of unique MAC
# address using uuid and getnode() function
print ( hex (uuid.getnode()))


输出:

0x163e990bdb

缺点:

  • 明显的缺点是输出不是格式化的。

方法3:使用getnode()+format() [为了更好地格式化]

# Python 3 code to print MAC
# in formatted way.
import uuid
# joins elements of getnode() after each 2 digits.
print ( "The MAC address in formatted way is : " , end = "")
print ( ':' .join([ '{:02x}' . format ((uuid.getnode() >> ele) & 0xff )
for ele in range ( 0 , 8 * 6 , 8 )][:: - 1 ]))


输出:

The MAC address in formatted way is : 00:16:3e:99:0b:db

缺点:

  • 这段代码似乎很复杂。

方法4:使用getnode()+findall()+re() [用于降低复杂性]

# Python 3 code to print MAC
# in formatted way and easier
# to understand
import re, uuid
# joins elements of getnode() after each 2 digits.
# using regex expression
print ( "The MAC address in formatted and less complex way is : " , end = "")
print ( ':' .join(re.findall( '..' , '%012x' % uuid.getnode())))


输出:

The MAC address in formatted and less complex way is : 00:16:3e:99:0b:db

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享