Advertisement
G0nz0uk

librenmspython1

Jun 23rd, 2022
769
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import requests
  2.  
  3. librenms_base_url = "https://ims.global.com/api/v0"
  4. librenms_auth_token = '0898874f8564021825d03f8622abe4f9'
  5. influxdb_url = 'http://hob.global.com:8086'
  6. db_name = 'SwitchesDB'
  7. influxdb_username = 'switchuser'
  8. influxdb_password = 'jhedfafgfdg5M1s5V'
  9. measurement_name = 'up_port_count'
  10.  
  11.  
  12. def get_all_ports():
  13.     url = f"{librenms_base_url}/ports?columns=device_id,ifOperStatus"
  14.     headers = {'X-Auth-Token': librenms_auth_token}
  15.     response = requests.request("GET", url, headers=headers, verify=False)
  16.     return response.json()['ports']
  17.  
  18.  
  19. def get_all_devices():
  20.     url = f"{librenms_base_url}/devices"
  21.     headers = {'X-Auth-Token': librenms_auth_token}
  22.     response = requests.request("GET", url, headers=headers, verify=False)
  23.     return response.json()['devices']
  24.  
  25.  
  26. def post_to_influxdb(device_sysname, total_up_ports):
  27.     payload = (f'{measurement_name},device_name="{device_sysname}" '
  28.                f'total_up_ports={int(total_up_ports)}')
  29.  
  30.     headers = {'Content-Type': 'application/octet-stream'}
  31.  
  32.     response = requests.request("POST", f"{influxdb_url}/write?db={db_name}", headers=headers, data=payload, auth=(influxdb_username, influxdb_password))
  33.  
  34.     print(f'  Response code is: {response.status_code}')
  35.  
  36.  
  37. #Get all devices, and associate the device name with the device sysName
  38. device_id_to_sysname = {}
  39. all_devices = get_all_devices()
  40. for device in all_devices:
  41.     device_id_to_sysname[device['device_id']] = device['sysName']
  42.  
  43. #Get all ports with their device ID and up/down status
  44. all_ports = get_all_ports()
  45. device_up_port_count = {}
  46. for port in all_ports:
  47.     device_id = port['device_id']
  48.     port_status = port['ifOperStatus']
  49.  
  50.     if port_status == 'up':
  51.         device_up_port_count.setdefault(device_id, 0)
  52.         device_up_port_count[device_id] += 1
  53.  
  54. print(device_up_port_count)
  55.  
  56. #Post the data to influxDB
  57. for device_id in device_up_port_count.keys():
  58.     device_sysname = device_id_to_sysname[device_id]
  59.     post_to_influxdb(device_sysname, device_up_port_count[device_id])
Advertisement
RAW Paste Data Copied
Advertisement