pynetbox usage
- User
pynetbox usage
- Assistant
pynetbox usage
pynetbox is a Python library designed to interact with the NetBox API. NetBox is an infrastructure resource modeling (IRM) tool used for managing and documenting computer networks.
With pynetbox, you can automate tasks such as querying devices, managing IP addresses, creating and updating data in NetBox via its REST API, all using Python.
You can install pynetbox via pip:
pip install pynetbox
Here's a basic example to get you started with pynetbox:
import pynetbox
# Connect to the NetBox instance
nb = pynetbox.api(
'http://netbox.example.com', # URL of NetBox
token='your_api_token_here' # Your API Token for authentication
)
# Example: List all devices
devices = nb.dcim.devices.all()
for device in devices:
print(f"Device Name: {device.name} - Device Role: {device.device_role.name}")
devices = nb.dcim.devices.all()
for device in devices:
print(device.name)
device = nb.dcim.devices.get(name='your-device-name')
print(device.serial)
new_device = nb.dcim.devices.create(
name='switch01',
device_role=1, # Usually you need to supply the ID of existing objects
device_type=2,
site=1,
status='active'
)
print(new_device)
Note: For creating or updating objects, you often have to supply existing related object IDs.
device = nb.dcim.devices.get(name='switch01')
device.update({'status': 'decommissioned'})
ips = nb.ipam.ip_addresses.all()
for ip in ips:
print(ip.address)
API Token: You can generate an API token in NetBox under your user profile.
Models: pynetbox provides access to all NetBox models grouped by apps, e.g.:
nb.dcim (Devices, Racks, Sites)nb.ipam (IP Addresses, Prefixes)nb.virtualization (Virtual Machines)You can create, update, delete, and retrieve objects as long as your API token permissions allow these operations.
roles = nb.dcim.device_roles.filter(name='Router')
if roles:
role_id = roles[0].id
routers = nb.dcim.devices.filter(device_role=role_id)
for r in routers:
print(r.name)
else:
print("No device role named 'Router' found")
If you have a particular use case or want to see sample code for a certain task using pynetbox, let me know!
Not yet included in a published release.