从Python中的多个对象随机生成

时间:2017-09-05 08:55:46

标签: python

如何使下面的脚本从列出的每个子网生成1个IPv6地址?

#!/usr/bin/env python3
"""
Generate a random IPv6 address for each of the specified subnets
"""

from random import seed, getrandbits
from ipaddress import IPv6Network, IPv6Address

subnet = u'2001:db8:100::/64'
subnet = u'2001:e85:100::/64'
subnet = u'2001:45a:100::/64'

seed()
network = IPv6Network(subnet)
address = IPv6Address(network.network_address + getrandbits(network.max_prefixlen - network.prefixlen))

print(address)

我可能希望能够列出许多不同的IPv6子网。

2 个答案:

答案 0 :(得分:1)

def generate(subnet):
    network = IPv6Network(subnet)
    address = IPv6Address(network.network_address + getrandbits(network.max_prefixlen - network.prefixlen))
    return address

print(generate(u'2001:db8:100::/64'))
print(generate(u'2001:e85:100::/64'))
print(generate(u'2001:45a:100::/64'))

答案 1 :(得分:0)

谢谢Alex。

#!/usr/bin/env python3
"""
Generate a random IPv6 address for each of the specified subnets
"""

from random import seed, getrandbits
from ipaddress import IPv6Network, IPv6Address

subnet = u'2001:db8:100::/64'
subnet = u'2001:e85:100::/64'
subnet = u'2001:45a:100::/64'

def generate(subnet):
    network = IPv6Network(subnet)
    address = IPv6Address(network.network_address + getrandbits(network.max_prefixlen - network.prefixlen))
    return address

print(generate(u'2001:db8:100::/64'))
print(generate(u'2001:e85:100::/64'))
print(generate(u'2001:45a:100::/64'))