Python IP 地址模块

Python IP Address Module

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

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

我已将其复制到 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

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

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

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

您当前安装的 Python(看起来像 3.6)

中的 ipaddress 模块很可能缺少 subnet_of 方法

如果您不想(或不能)升级 Python,您可以遵循 How to import a module given the full path?

中的概念

而不是通过以下方式导入:

import ipaddress

您可以使用以下方式选择不同的版本:

import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "./virtualenvs/dev/lib/python3.6/site-packages/ipaddress.py")
ipaddress = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ipaddress)

只需更改路径以反映正确的模块位置。