Windows10Deployment/ipxe-set-hostname-from-serial.py

40 lines
1.1 KiB
Python
Executable File

#!/usr/bin/env python3
import os
import requests
SNIPEIT_TOKEN = "SET_ME"
def get_hostname_from_snipeit(serial: str):
r = requests.get(
"https://inventory.claremontmakerspace.org/api/v1/hardware/byserial/" + serial,
headers = {"Authorization": "Bearer " + SNIPEIT_TOKEN}
)
data = r.json()
if len(data["rows"]) == 1:
name = data["rows"][0]["name"]
if name:
return name
else:
asset_tag = data["rows"][0]["asset_tag"]
id = data["rows"][0]["id"]
raise Exception(f"No name set for asset {id}, tag {asset_tag}")
elif len(data["rows"]) < 1:
raise Exception("No asset found")
else:
raise Exception("Multiple assets with this serial number found")
print("Content-type: text/plain\n")
print("#!ipxe")
try:
hostname = get_hostname_from_snipeit(os.environ["QUERY_STRING"])
if hostname:
print("set hostname " + hostname)
print("echo Set hostname=${hostname}")
except Exception as e:
print("echo Failed to set hostname from serial ${serial}, exiting in 5 seconds...")
print(f"echo Error: {e}")