<< Click to Display Table of Contents >> Raynet One > 1.1 > User Guide > Technical overview > API Use case: device list initialization with REST API |
To initialize a big set of devices into the database, it is useful to use a device registry. If no dedicated device registry is available (for example Microsoft AD or CrowdStrike), the list of devices may come in the form of a text file. Put each hostname into a separate line. Meeting all the requirements, run the provided program.
•Python 3+
•Requests library (https://docs.python-requests.org/en/latest/)
•API key
•frontend URL
•site to add the device to
•list of devices to initialize the device registry with (devices.txt)
import requests
APIKEY = "PUT API KEY HERE"
FRONTEND = "PUT FRONTEND URL HERE"
HEADERS = { "ApiKey": APIKEY }
DEVICE_SITE_ID = "PUT THE SITE ID HERE"
def obtain_paged(EP):
P = {}
P["count"] = 1000
items = []
while True:
result = requests.get(EP, params=P, headers=HEADERS)
if result.ok == False:
break
objs = result.json()
if objs == None:
return
if len(objs) == 0:
return
items.extend(objs)
lastobj = objs[len(objs)-1]
P["LastId"] = lastobj["id"]
return items
def main():
devs = obtain_paged(FRONTEND + "/api/v1/Devices")
if devs == None:
print( "failed to fetch devices from the frontend (" + FRONTEND + ")" )
return
ddf = open("devices.txt", "r")
if ddf:
ndevs = ddf.read().splitlines()
ddf.close()
if ndevs == None:
print( "failed to fetch new device list for import" )
return
added_any_device = False
for ND in ndevs:
already_exists = False
for D in devs:
if "name" in D and D["name"] == ND:
already_exists = True
break
if already_exists:
print( "device " + ND + " already exists; import skipped" )
else:
postdata = {
"device": {
"name": ND,
"comment": "imported from API using devices.txt",
"corporateOwnership": False
},
"metadata": {
"siteId": DEVICE_SITE_ID
}
}
R = requests.post(FRONTEND + "/api/v1/Operations/device-import", headers=HEADERS, json=postdata)
if R.ok:
print( "added device " + ND )
added_any_device = True
else:
print( "failed to add device " + ND + " (" + str(R.status_code) + ")" )
if added_any_device == False:
print( "didn't add any device" )