【问题标题】:How to split specified network into subnets using Python如何使用 Python 将指定的网络拆分为子网
【发布时间】:2017-10-28 01:29:56
【问题描述】:

我一直在研究这个问题,但找不到许可。

我有一个 Python 脚本,它应该有两个参数 - 网络/CIDR 和一个数字。该脚本应将指定的网络划分为多个部分、子网,并显示这些子网的参数,如网络地址、广播、主机数。

其实我目前的代码状态是here,在GitHub上。

我问的原因是 Stack Overflow 上还有其他主题,例如 thisthisthis。但是它们都有前缀。我的观点是,例如,./subnet-divider.py 200.100.33.65/26 3,所以我应该把它分成 3 个子网。或./subnet-divider.py 200.100.33.65/26 9。所以这是一个不同的观点,虽然与讨论的有点相似。

我绕过了两个模块 - ipaddressnetaddr。两者相似。有用于子网划分的生成器,但它们有 prefix、required 和 count 之类的参数,这很好。

In [22]: s.get_subnet(27, count=3)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-22-5864cbfc587d> in <module>()
----> 1 s.get_subnet(27, count=3)

/home/simple/Projects/subnet-divider/ip_splitter.py in get_subnet(self, prefix, count)
     14         """ . """

     15         for ip_network in self.get_available_ranges():
---> 16             subnets = list(ip_network.subnet(prefix, count=count))
     17             if not subnets:
     18                 continue

/usr/local/lib/python3.5/dist-packages/netaddr/ip/__init__.py in subnet(self, prefixlen, count, fmt)
   1269 
   1270         if not 1 <= count <= max_subnets:
-> 1271             raise ValueError('count outside of current IP subnet boundary!')
   1272 
   1273         base_subnet = self._module.int_to_str(self.first)

ValueError: count outside of current IP subnet boundary!

当然,这是正确的。

那么,我该如何划分?为了灵活地做到这一点,我不需要前缀,但脚本应该能够将传入网络划分到指定的子网中,最大可以分为 3、7、10 等。

谢谢。

【问题讨论】:

    标签: python network-programming divide subnet


    【解决方案1】:

    我想我自己解决了这个案子。只是为了分割。

    This message 提供帮助。所以,我们有一对 & 数字来划分。我们可以计算子网的前缀长度。

    代码在仓库中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2016-09-24
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多