簡體   English   中英

Python IP 地址模塊

[英]Python IP Address Module

我希望我能在我的 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

ipaddress模塊是標准庫的一部分,所以我猜您正在導入該版本。

您還可以驗證您實際導入的是哪個模塊

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

您當前安裝的 Python 中的ipaddress模塊很可能缺少subnet_of方法(看起來像 3.6)

如果您不想(或不能)升級 Python,您可以遵循如何導入給定完整​​路徑的模塊中的概念

而不是通過導入:

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)

只需更改路徑以反映正確的模塊位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM