Search code examples
pythonnetbox

How to access NetBox data about Virtualization / Virtual Machines via Python


This is a Python script to create a CSV from NetBox data about Devices:

devices = nb.dcim.devices.all()
csv_file_path = 'netbox_devices.csv'

with open(csv_file_path, mode='w', newline='') as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow(['Name', 'Manufacturer', 'Model', 'Serial Number', 'Asset Tag'])
    for device in devices:
        csv_writer.writerow([device.name, device.device_type.manufacturer.name, device.device_type.model, device.serial, device.asset_tag])

How could I write a similar script to do the same, but to list Virtual Machines?

Replacing the first line with

vms = nb.virtualization.virtual-machines.all()

returns an error

NameError: name 'machines' is not defined


Solution

  • Just found the solution.

    The URL is https://mynetbox.example.org/virtualization/virtual-machines/ but via the API it is necessary to replace the dash with an underscore in the path:

    vms = nb.virtualization.virtual_machines.all()