python中的MAC地址生成器

python中的MAC地址生成器

本文介绍了python中的MAC地址生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了创建批量虚拟机,我需要在 Python 中创建一个随机 MAC 地址生成器.我不知道如何生成随机 MAC 地址.

For purpose of creating bulk virtual machines, I need to create a random MAC address generator in Python. I don't know how to generate random MAC addresses.

以下程序是否正确?

import random

# The first line is defined for specified vendor
mac = [ 0x00, 0x24, 0x81,
    random.randint(0x00, 0x7f),
    random.randint(0x00, 0xff),
    random.randint(0x00, 0xff) ]

print ':'.join(map(lambda x: "%02x" % x, mac))

推荐答案

对于任何想要生成自己的 MAC 地址的人(一个很好的例子是 VM NIC),您可能只想要这个:

For anyone wanting to generate their own MAC addresses (a good example is for VM NICs), you probably just want this:

"02:00:00:%02x:%02x:%02x" % (random.randint(0, 255),
                             random.randint(0, 255),
                             random.randint(0, 255))

或者,如果您想在 unix'y shell 中执行此操作,这适用于许多:

Or, if you want to do this in a unix'y shell, this works on many:

printf '02:00:00:%02X:%02X:%02X\n' $((RANDOM%256)) $((RANDOM%256)) $((RANDOM%256))

这为您提供了一个在您的环境中使用的 100% 安全的单播 MAC 地址,并且不会践踏任何人的注册 MAC 地址空间.

This gives you a unicast MAC address that is 100% safe to use in your environment, and isn't trampling on anyone's registered MAC address space.

更多细节...

顶部字节 (0x02) 的底部两位为您提供本地管理的单播地址,如果您正在使用 stackoverflow 了解如何生成此地址,这可能是您想要的.:)

The bottom two bits of the top byte (0x02) give you a locally administered unicast address, which is probably what you want if you are hitting stackoverflow for how to generate this. :)

如果 MAC 地址不是本地管理,则意味着它应该是全球唯一的".这个类别的MAC地址是在IEEE集中注册的,你应该有一个IEEE发给你的唯一的OUI(Organizationally Unique Identifier).请参阅链接,了解 OUI 值的全球注册表.这个 OUI 值最终出现在前 3 个字节中(或者实际上只是前 22 位).

If the MAC address is not locally administered, it means it is supposed to be "globally unique". MAC addresses in this category are centrally registered with the IEEE, and you should have a unique OUI (Organizationally Unique Identifier) issued to you by the IEEE. See this link for the global registry of OUI values. This OUI value ends up in the first 3 bytes (or just the top 22 bits, really).

MAC 地址并没有那么复杂,所以您可能也应该看看定义.维基百科有不错的.

MAC addresses aren't that complicated, so you should probably also just have a look at the definition. Wikipedia has a good one.

这篇关于python中的MAC地址生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 03:03