imagestack/tools/batch_print/print.py
2025-08-11 18:06:16 +02:00

124 lines
3.7 KiB
Python

import string
import argparse
import sys
import json
import os
import random
import requests
def check_mac_exists(mac,api_key):
url = f'https://computer.z31.it/api/v1/hardware?limit=5&search={mac}'
headers = {
'accept': 'application/json',
'authorization': f'Bearer {api_key}',
'content-type': 'application/x-www-form-urlencoded'
}
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"Error fetching data: HTTP {response.status_code}")
exit(1)
data = response.json()
# Extract asset_tag from all rows
asset_tags = [row.get('asset_tag', '') for row in data.get('rows', []) if row.get('asset_tag')]
if asset_tags:
return True
else:
return False
exit(0)
def generate_random_mac():
mac = [
0x02, # fixed first byte
random.randint(0x00, 0xFF),
random.randint(0x00, 0xFF),
random.randint(0x00, 0xFF),
random.randint(0x00, 0xFF),
random.randint(0x00, 0xFF),
]
return ":".join(f"{octet:02x}" for octet in mac)
def generate_random_serial(length=8):
"""Generate a random uppercase alphanumeric serial number."""
chars = string.ascii_uppercase + string.digits
return "DUMMY-" +"".join(random.choices(chars, k=length))
def main():
parser = argparse.ArgumentParser(
description="Validate a JSON file, print its contents, an amount, and generate a random private MAC address."
)
parser.add_argument(
"-j","--path",
type=str,
help="Path to JSON File containing Computer Info"
)
parser.add_argument(
"-i", "--amount",
type=int,
help="Number of Labels that should be printed (Can't be more than 50)"
)
args = parser.parse_args()
json_file = args.path
amount = args.amount
response = requests.get("http://10.200.4.12:8888/snipe_api")
response.raise_for_status() # raise error if request failed
api_key = response.text.strip() # or response.json() if JSON returned
if amount > 50:
print("Maximum amount can be 50.")
sys.exit(1)
# Check if file exists
if not os.path.isfile(json_file):
print(f"Error: File '{json_file}' does not exist.")
sys.exit(1)
# Validate JSON
try:
with open(json_file, "r") as f:
data = json.load(f)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON in file '{json_file}': {e}")
sys.exit(1)
# Display JSON and amount
# Generate and display MAC
generate_random_mac()
data['_snipeit_mac_address_1'] = generate_random_mac()
data["serial"] = generate_random_serial()
for i in range(1, args.amount + 1):
exists = True
while exists:
generate_random_mac()
mac = generate_random_mac()
exists = check_mac_exists(mac,api_key)
data['_snipeit_mac_address_1'] = generate_random_mac()
data["serial"] = generate_random_serial()
#Snipe IT
headers = {
"accept": "application/json",
"authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
asset =requests.post("https://computer.z31.it/api/v1/hardware",headers=headers,data=json.dumps(data))
tag =json.loads(asset.content)['payload']['asset_tag']
print_data = {
"id": tag,
"distribution": "Windows",
"version": "11",
"cpu": data["_snipeit_prozessor_5"],
"memory": data["_snipeit_arbeitsspeicher_6"],
"disk": data["_snipeit_festplatte_4"]
}
res = requests.post("http://10.200.4.12:8888/batch", data=json.dumps(print_data))
print(res.content)
if __name__ == "__main__":
main()