Giter Club home page Giter Club logo

netbox-python's Introduction

NetBox Python

Python API client library for NetBox.

Note: This is a preliminary release and still under development.

Release Build status Commit activity License

Project license

Pull Requests welcome code with love by netbox-community

Table of Contents

About

This is a thin python wrapper over the NetBox API.

Getting Started

To install run pip install netbox-python.

Alternatively, you can clone the repo and run python setup.py install.

Usage

The full documentation is at https://netbox-community.github.io/netbox-python/, but the following should be enough to get started using it.

To begin, import the NetBox client and instantiate it:

from netbox_python import NetBoxClient, Result
nb = NetBoxClient(
    base_url="http://127.0.0.1:8000/", token="1dc6fa5bfcef8390dd83a261c36ed8f1551b2d6b"
)

The first argument NetBoxClient takes is the NetBox URL. The 'token' argument is from NetBox.

Now using the client you can make calls to the api, for example:

# 1. List (paginated)
ret = nb.dcim.sites.list(limit=3)

# 2. Filtered List
ret = nb.dcim.sites.list(region_id="43")

# 3. All
ret = nb.dcim.sites.all()

# 4. Get
ret = nb.dcim.sites.get(24)

# 5. Create
ret = nb.dcim.sites.create(name="foo3", slug="foo3")

# 6. Bulk Create
data = [
    {"name": "foo4", "slug": "foo4"},
    {"name": "foo5", "slug": "foo5"},
    {"name": "foo6", "slug": "foo6"},
]
ret = nb.dcim.sites.create(data)

# 7. Update
ret = nb.dcim.sites.update(26, name="foo2-new", slug="foo2-new-slug")

# 8. Bulk Update
data = [
    {"id": 28, "name": "foo4-new", "slug": "foo4-new"},
    {"id": 29, "name": "foo5-new", "slug": "foo5-new"},
]
ret = nb.dcim.sites.update(data)

# 9. Delete
ret = nb.dcim.sites.delete(37)

# 10. Bulk Delete
data = [{"id": 25}, {"id": 27}]
ret = nb.dcim.sites.delete(data)

The methods on the api's correspond to the NetBox REST API, so ('circuits', 'core', 'dcim', 'extras', 'ipam', 'plugins', 'tenancy', 'users', 'virtualization', 'wireless')

circuits would have 'circuit_terminations', 'circuit_types', etc... off of it. Each of the endpoints has 'list', 'get', 'create', 'update' and 'delete' functions.

Roadmap

See the open issues for a list of proposed features (and known issues).

Support

Reach out to the maintainer at one of the following places:

Contributing

First off, thanks for taking the time to contribute! Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make will benefit everybody else and are greatly appreciated.

Please read our contribution guidelines, and thank you for being involved!

Authors & contributors

The original setup of this repository is by Arthur Hanson.

For a full list of all authors and contributors, see the contributors page.

License

This project is licensed under the Apache Software License 2.0.

See LICENSE for more information.

netbox-python's People

Contributors

arthanson avatar jaedanc avatar pobradovic08 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

netbox-python's Issues

bug: Add support for ipam available APIs

Bug Report

The following APIs need to be implemented:

   path(
        'asn-ranges/<int:pk>/available-asns/',
        views.AvailableASNsView.as_view(),
        name='asnrange-available-asns'
    ),
    path(
        'ip-ranges/<int:pk>/available-ips/',
        views.IPRangeAvailableIPAddressesView.as_view(),
        name='iprange-available-ips'
    ),
    path(
        'prefixes/<int:pk>/available-prefixes/',
        views.AvailablePrefixesView.as_view(),
        name='prefix-available-prefixes'
    ),
    path(
        'prefixes/<int:pk>/available-ips/',
        views.PrefixAvailableIPAddressesView.as_view(),
        name='prefix-available-ips'
    ),
    path(
        'vlan-groups/<int:pk>/available-vlans/',
        views.AvailableVLANsView.as_view(),
        name='vlangroup-available-vlans'
    ),

bug: Add support for VLAN group available vlans API call

NetBox Python version

v0.1.6

NetBox version

v3.6.6

Python version

3.11

Steps to Reproduce

Trying to call:

self.api.ipam.vlan_group.available_vlans.list(id=group_id, limit=1)

or

self.api.ipam.vlan_groups.available_vlans.list(id=group_id, limit=1)

Fails with AttributeError: 'ipam' object has no attribute 'vlan_group'. or AttributeError: '_vlan_groups' object has no attribute 'available_vlans'.

Expected Behavior

Like for ipam.asn_range.available_asns (which is a singular of asn_ranges) and ipam.ip_range.available_ips (singular of ip_ranges), I would expect to have ipam.vlan_group.available_vlans.

Observed Behavior

Calls fail with above mentioned errors (AttributeError: 'ipam' object has no attribute 'vlan_group'. or AttributeError: '_vlan_groups' object has no attribute 'available_vlans'). In /api/ipam.py there are definitions for ASN and IP ranges:

class ipam:
    def __init__(self, client):
        ...
        self.asn_ranges = self._asn_ranges(client)
        self.asn_range = asn_range(client)
        ...
class ipam:
    def __init__(self, client):
        ...
        self.ip_ranges = self._ip_ranges(client)
        self.ip_range = ip_range(client)
        ...

but there are no self.vlan_group defined for vlan_groups although there is an import:

from netbox_python.api.vlan_group import vlan_group

And vlan_group.py file already exists.

bug: nb.ipam.prefixes.update not working as expected

Bug Report

NetBox Python version:
0.1.6

Current behavior:
no update happens

When I use nb.ipam.prefixes.update, no update happens
Expected behavior:
I would expect the http patch data to update and the server to respond with the updated data.

I excpect the server to respond with the changed data
Steps to reproduce:
Below code, is a simple example of just trying to update a description

Related code:

In the below code I am just trying to change the description. It doesn't update using the netbox-python module

when I re-write it to use the requests module it does update as expected

#!/usr/bin/env python3
import json
import requests
from netbox_python import NetBoxClient, Result
nb = NetBoxClient(
base_url="https://netbox.domain.com/", token="<YOUR_TOKEN_HERE>"
)

def update_prefix():
prefix_id = 682
data = {"id": 682, "prefix": "192.168.71.0/25", "description": "LAB Management", "site": {"id": 279}, "tenant": {"id": 2}, "vlan": {"id": 637}}
ret = nb.ipam.prefixes.update(prefix_id, json=data)
print(f"status code: {ret.response.status_code}")
print("netbox-python module prefixes update:")
print(json.dumps(ret.data, indent=2))

url = "https://netbox.domain.com/api/ipam/prefixes/{}/".format(prefix_id)
headers = {
    "Authorization": "Token <YOUR_TOKEN_HERE>",
    "Content-Type": "application/json"
    }
data = {"id": 682, "prefix": "192.168.71.0/25", "description": "LAB Management", "site": {"id": 279}, "tenant": {"id": 2}, "vlan": {"id": 637}}
ret = requests.patch(url, json=data, headers=headers)
print(f"status code: {ret.status_code}")
print("requests module prefixes update:")
print(json.dumps(ret.json(), indent=2))

if name == "main":
update_prefix()


output below:
status code: 200
netbox-python module prefixes update:
{
"id": 682,
"url": "http://netbox.domain.com/api/ipam/prefixes/682/",
"family": {
"value": 4,
"label": "IPv4"
},
"prefix": "192.168.71.0/25",
"site": {
"id": 279,
"url": "http://netbox.domain.com/api/dcim/sites/279/",
"name": "LAB",
"slug": "lab"
},
"vrf": null,
"tenant": {
"id": 2,
"url": "http://netbox.domain.com/api/tenancy/tenants/2/",
"name": "SCA",
"slug": "sca"
},
"vlan": {
"id": 637,
"url": "http://netbox.domain.com/api/ipam/vlans/637/",
"vid": 100,
"name": "Management",
"display_name": "Management (100)"
},
"status": {
"value": "active",
"label": "Active"
},
"role": null,
"is_pool": false,
"description": "BAD BAD BAD Description",
"tags": [],
"custom_fields": {
"ActiveDirectorySite": false
},
"created": "2023-09-26",
"last_updated": "2023-09-26T13:10:43.854351Z"
}
status code: 200
requests module prefixes update:
{
"id": 682,
"url": "http://netbox.domain.com/api/ipam/prefixes/682/",
"family": {
"value": 4,
"label": "IPv4"
},
"prefix": "192.168.71.0/25",
"site": {
"id": 279,
"url": "http://netbox.domain.com/api/dcim/sites/279/",
"name": "LAB",
"slug": "lab"
},
"vrf": null,
"tenant": {
"id": 2,
"url": "http://netbox.domain.com/api/tenancy/tenants/2/",
"name": "SCA",
"slug": "sca"
},
"vlan": {
"id": 637,
"url": "http://netbox.domain.com/api/ipam/vlans/637/",
"vid": 100,
"name": "Management",
"display_name": "Management (100)"
},
"status": {
"value": "active",
"label": "Active"
},
"role": null,
"is_pool": false,
"description": "LAB Management",
"tags": [],
"custom_fields": {
"ActiveDirectorySite": false
},
"created": "2023-09-26",
"last_updated": "2023-09-26T13:10:44.357695Z"
}

insert short code snippets here

Other information:

Extends the netbox client constructor to allow kwargs

NetBox Python version

v0.1.6

NetBox version

v3.6.4

Feature type

Change to existing functionality

Proposed functionality

Allow passing params from the netbox client to the rest client.

It is possible to configure the requests session in the rest client
https://github.com/netbox-community/netbox-python/blob/main/netbox_python/rest.py#L39

Unfortunately it is not possible to get any params there because the netbox client doesn't support kwargs
https://github.com/netbox-community/netbox-python/blob/main/netbox_python/netbox.py#L25

Use case

It would make it possible to configure the requests session e.g. set verify=false or other settings.

External dependencies

No response

Improve github templates

The github PR template is very verbose and needs to be cleaned up. Also the issue submission templates need to be streamlined.

importlib.metadata.PackageNotFoundError: No package metadata was found for 0.1.7

NetBox Python version

v0.1.7

NetBox version

v3.6.7

Python version

3.10

Steps to Reproduce

Install netbox-python==0.1.7, then try to import the module into python.

Expected Behavior

Like in v0.1.6, I expect it to import with no issue:

import netbox_python

Observed Behavior

I see this error:

>>> import netbox_python

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "/home/path/venv/lib/python3.10/site-packages/netbox_python/__init__.py", line 6, in <module>

__version__ = version("0.1.7")

File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 996, in version

return distribution(distribution_name).version

File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 969, in distribution

return Distribution.from_name(distribution_name)

File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 548, in from_name

raise PackageNotFoundError(name)

importlib.metadata.PackageNotFoundError: No package metadata was found for 0.1.7

netbox-python-0.1.7 wheel from pypi version detection is broken

NetBox Python version

0.1.7

NetBox version

3.6.6

Python version

3.11

Steps to Reproduce

$ python -m venv tmp
$ . tmp/bin/activate
$ pip install netbox-python==0.1.7
Collecting netbox-python==0.1.7
  Using cached netbox_python-0.1.7-py3-none-any.whl (17 kB)
Collecting requests<3.0,>=2.20.0
  Using cached requests-2.31.0-py3-none-any.whl (62 kB)
Collecting charset-normalizer<4,>=2
  Using cached charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (140 kB)
Collecting idna<4,>=2.5
  Using cached idna-3.6-py3-none-any.whl (61 kB)
Collecting urllib3<3,>=1.21.1
  Using cached urllib3-2.1.0-py3-none-any.whl (104 kB)
Collecting certifi>=2017.4.17
  Using cached certifi-2023.11.17-py3-none-any.whl (162 kB)
Installing collected packages: urllib3, idna, charset-normalizer, certifi, requests, netbox-python
Successfully installed certifi-2023.11.17 charset-normalizer-3.3.2 idna-3.6 netbox-python-0.1.7 requests-2.31.0 urllib3-2.1.0

$ python
Python 3.11.4 (main, Dec  7 2023, 15:43:41) [GCC 12.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import netbox_python
Traceback (most recent call last):
  File "/usr/lib/python3.11/importlib/metadata/__init__.py", line 563, in from_name
    return next(cls.discover(name=name))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/harm/tmp/lib/python3.11/site-packages/netbox_python/__init__.py", line 6, in <module>
    __version__ = version("0.1.7")
                  ^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/importlib/metadata/__init__.py", line 1008, in version
    return distribution(distribution_name).version
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/importlib/metadata/__init__.py", line 981, in distribution
    return Distribution.from_name(distribution_name)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/importlib/metadata/__init__.py", line 565, in from_name
    raise PackageNotFoundError(name)
importlib.metadata.PackageNotFoundError: No package metadata was found for 0.1.7
>>> from importlib.metadata import version
>>> version('netbox_python')
'0.1.7'

$ grep version /home/harm/tmp/lib/python3.11/site-packages/netbox_python/__init__.py
from importlib.metadata import version
__version__ = version("0.1.7")

Expected Behavior

The module import should not fail on version detection.

Observed Behavior

The release has replaced the dynamic version(__name__) with a hardcoded version("0.1.7")

bug: Spelling of endpoints

Bug Report

NetBox Python version:

v0.1.5

Current behavior:

Two endpoints are misspelled:

  • self.ip_addresss
  • self.prefixs

Expected behavior:

The correct spelling is:

  • self.prefixes
  • self.ip_addresses

How are certain API endpoints accessible through netbox-python

NetBox Python version

v0.1.6

NetBox version

v3.6.4

Python version

3.8

Steps to Reproduce

A circuit-termination has a paths endpoint.
https://netbox.sipgate.net/api/circuits/circuit-terminations/13/paths/

However I'm not able / don't know how to access it through netbox-python.

I can get
nb.circuits.circuit_terminations.get(13)
But not the paths for that circuit_terminations.

Expected Behavior

All endpoints should be accessible through the lib.

Observed Behavior

Unclear how or not possible to access circuit-terminations/13/paths/

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.