首页 > 解决方案 > Python IP 地址模块

问题描述

我希望我能在我的 python 模块安装方面获得一些帮助,特别是在 ipaddress 模块周围。这个问题快把我逼疯了...

简而言之,我在我的 Windows 机器上编写了一个使用 ipaddress 模块的 python3 脚本。这绝对没问题。

我已将它复制到我想在其上运行它的 Linux 机器(Ubuntu 18.04),但是当我运行它时,我收到以下错误:

File "/opt/netbox-2.6.7/netbox/reports/address-parents.py", line 82, in test_aci_endpoints
  if endpoint.subnet_of(summary):
AttributeError: 'IPv4Network' object has no attribute 'subnet_of'

当我查询模块时,我得到以下信息:

nbxla01lv:/opt/netbox/netbox$ pip3 show ipaddress
Name: ipaddress
Version: 1.0.23
Summary: IPv4/IPv6 manipulation library
Home-page: https://github.com/phihag/ipaddress
Author: Philipp Hagemeister
Author-email: phihag@phihag.de
License: Python Software Foundation License
Location: /home/andy/.local/lib/python3.6/site-packages
Requires: 

在查看该模块的主页时,这让我有点困惑,它似乎是 python 2.7 的 3.3+ ipaddress 模块的一个端口。无论如何,版本 1.0.23 是最新版本并包含函数“subnet_of”。

此外,如果我查看 /home/andy/.local/lib/python3.6/site-packages/ipaddress.py 中的实际代码本身,我可以在代码中看到实际功能:

nbxla01lv:/home/andy/.local/lib/python3.6/site-packages$ cat ipaddress.py | grep subnet_of
        if not other.subnet_of(self):
            if other.subnet_of(s1):
            elif other.subnet_of(s2):
    def _is_subnet_of(a, b):
    def subnet_of(self, other):
        return self._is_subnet_of(self, other)
        return self._is_subnet_of(other, self)

我确信这很简单,但任何帮助将不胜感激。

谢谢!

编辑 - 示例代码

# Query APIC for all endpoint IPs. 
endpointQuery = '/api/node/class/fvIp.json'
resp = requests.get(aciBaseURL + endpointQuery, cookies=cookie, verify=False).json()

ipAddressCount = int(resp["totalCount"])
aciIPs = []
counter = 0
summary = ipaddress.ip_network(inputSummary)

while counter < ipAddressCount:
    endpoint = ipaddress.ip_network(resp['imdata'][counter]["fvIp"]["attributes"]["addr"])
    if endpoint.subnet_of(summary):
        aciIPs.append(str(endpoint))
    counter+=1

标签: pythonmodulepipip-address

解决方案


ipaddress模块是标准库的一部分,所以我猜您正在导入该版本。

您还可以验证您实际导入的模块

>>> import ipaddress
>>> ipaddress.__file__
'/Users/rickard/.pyenv/versions/3.7.4/lib/python3.7/ipaddress.py'

您当前安装的 Python 中的模块很可能subnet_of缺少该方法(看起来像 3.6)ipaddress


推荐阅读