Python LibreNMS crawler for Serial Numbers

I created a python script to crawl LibreNMS for all serial numbers in the inventory of all devices.
Sharing it in case someone hase a similar usecase.

# -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 13:41:25 2020
Crawl libreNMS inventory to receive list of all devices with serial number.
"""

import csv
import requests

#edit base_url below
base_url = 'http://librenms.me/api/v0/'
#edit auth-token below
auth_token = 'INSERT Auth-Token here'
header = { 'x-auth-token' : auth_token }
file_path = 'LibreNMSInventory.csv'

#General GET helper function, pass sub-url to append to base URL for request
def GET(url):
    return requests.get('{0}{1}'.format(base_url,url), headers = header)
                        
#GET call to get all devices registered in libreNMS
#Return dictionary of all deviceIDs + hostname
def getDeviceDict():
    
    device_list = GET('devices/').json()['devices']
    device_dict = {}
    for device in device_list:
        device_dict[device['device_id']] = device['hostname']
    
    
    return device_dict


def inventoryList(deviceID, hostname, physical_id = None):
    if physical_id == None:
        postString =""
    else:
        postString="?entPhysicalContainedIn={}".format(physical_id)
        
    inventory = GET('inventory/{0}{1}'.format(deviceID,postString)).json()['inventory']
    
    for device in inventory:

        entPhysicalClass = device['entPhysicalClass']
        entPhysicalName = device['entPhysicalName']
        entPhysicalDescr = device['entPhysicalDescr']
        entPhysicalModelName = device['entPhysicalModelName']
        entPhysicalSerialNum = device['entPhysicalSerialNum']
        if device['entPhysicalSerialNum'] != '':
            csv_row = [hostname, entPhysicalClass, entPhysicalName, entPhysicalDescr, entPhysicalModelName, entPhysicalSerialNum]
            print(csv_row)
            with open(file_path,'a', newline='') as file:
                writer = csv.writer(file)
                writer.writerow(csv_row)
#            print('{0},{1},{2},{3},{4},{5}'.format(hostname,entPhysicalClass,entPhysicalName,entPhysicalDescr,entPhysicalModelName,entPhysicalSerialNum))
            
        inventoryList(deviceID,hostname,device['entPhysicalIndex'])
    
    
    
def main():
    
    device_dict = getDeviceDict()
    with open(file_path,'w+', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['Hostname','Class','Name','Description','Model Name','Serial'])
        
    for deviceID, hostname in device_dict.items():
        inventoryList(deviceID,hostname)

main()
3 Likes

Tried, it works. Great! Thanks

It should be work with python3 ? I have try it, but got error.
Thanks