【问题标题】:How to interact with NetBox API using python如何使用 python 与 NetBox API 交互
【发布时间】:2020-10-08 14:23:01
【问题描述】:

我正在尝试使用 CentOS 中的 python 与 NetBox 交互。我所做的是我用 docker 安装了 netbox,所以每次我从 centOS 运行“docker-compose up”时,我都可以在浏览器中访问 netbox api。我设法手动添加了一些新设备。所以我现在想做的是我想写一个python文件来获取我手动添加的这些信息。我的问题是我无法理解文档,并且从他们提供的那些简单示例中没有任何效果。

我唯一能做的就是通过导入 requests 包来检索以下 json 回复:

{u'dcim': u'http://ansible.mpl.nh:2435/api/dcim/', u'circuits': u'http://ansible.mpl.nh:2435/api/circuits/', u'ipam': u'http://ansible.mpl.nh:2435/api/ipam/', u'secrets': u'http://ansible.mpl.nh:2435/api/secrets/', u'tenancy': u'http://ansible.mpl.nh:2435/api/tenancy/', u'extras': u'http://ansible.mpl.nh:2435/api/extras/', u'virtualization': u'http://ansible.mpl.nh:2435/api/virtualization/', u'plugins': u'http://ansible.mpl.nh:2435/api/plugins/'}

所以我基本上做的就是这样:

rest_response = requests.get(url="http://ansible.../api/")

但这只是非常简单和基本的事情。如果我更改 url,我可以从每个 API 获得回复。如何实际与 NetBox 交互并检索例如我使用 python 在 API 中手动添加的设备?

【问题讨论】:

    标签: python api netbox


    【解决方案1】:

    我推荐使用 pynetbox 模块。

    例子:

    import pynetbox
    nb = pynetbox.api(url='https://netbox-url/', token='<API-token>')
    
    #fetch all devices
    nb_devicelist = nb.dcim.devices.all()
    
    # focus on 1 single device
    nb_device = nb_devicelist[1]
    print (nb_device)
    
    # do something with all devices in the list
    for nb_device in nb_devicelist:
        platform = str(nb_device.platform)
        pri_ip = str(nb_device.primary_ip)
        asset = nb_device.asset_tag
        print (nb_device,platform,pri_ip,asset)
    
    

    【讨论】:

      【解决方案2】:

      这是一个 helloworld 示例:

      import json, requests
      
      url = 'http://127.0.0.1:8000/api/dcim/devices/'
      params = { 'name': "junos-dev-ex4200" }
      headers = {'Authorization': "Token xyz123456789" }                    
      
      r = requests.get(url, params=params, headers=headers)                       
      
      print(json.dumps(r.json(), indent=4))
      

      详细的 API 文档可在 http://127.0.0.1:8000/api/docs/ 获得。 这里 127.0.0.1:8000 是你的 netbox 实例。

      【讨论】:

        【解决方案3】:

        试试官方的python客户端,它让API访问变得更容易,并且包含示例https://github.com/digitalocean/pynetbox

        【讨论】:

          猜你喜欢
          • 2020-10-05
          • 2012-05-12
          • 1970-01-01
          • 1970-01-01
          • 2020-01-23
          • 2015-09-22
          • 2017-07-24
          • 2011-03-21
          • 1970-01-01
          相关资源
          最近更新 更多