Added Batch Print Script

This commit is contained in:
Jan 2025-08-11 17:57:34 +02:00
parent 8e9628c0a4
commit 74ec8e9c3f
4 changed files with 220 additions and 0 deletions

View file

@ -0,0 +1,15 @@
{
"status_id": "2",
"name": "HP-Tablet",
"model_id": "2",
"serial": "Null",
"_snipeit_mac_address_1": "Null",
"_snipeit_betriebssystem_2": "Windows 11",
"_snipeit_festplatte_4": "128",
"_snipeit_prozessor_5": "Intel Pentium 4410 1.5ghz",
"_snipeit_arbeitsspeicher_6": "4",
"_snipeit_optisches_laufwerk_7": "nein",
"_snipeit_display_8": "",
"_snipeit_akku_9": "",
"_snipeit_anydeskid_10": ""
}

124
tools/batch_print/print.py Normal file
View file

@ -0,0 +1,124 @@
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": "Intel Pentium 4410 1.5ghz",
"memory": "4",
"disk": "128"
}
res = requests.post("http://10.200.4.12:8888/batch", data=json.dumps(print_data))
print(res.content)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,48 @@
#!/bin/bash
# Function to generate a random locally administered (private) MAC address
generate_random_mac() {
# First byte: set locally administered bit (0x02) and unicast (0x00)
# Remaining bytes: random
printf '02:%02x:%02x:%02x:%02x:%02x\n' \
$((RANDOM % 256)) \
$((RANDOM % 256)) \
$((RANDOM % 256)) \
$((RANDOM % 256)) \
$((RANDOM % 256))
}
# Check if the right number of arguments are given
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <json_file_path> <amount>"
exit 1
fi
# Assign arguments to variables
json_file="$1"
amount="$2"
# Check if jq is installed
if ! command -v jq >/dev/null 2>&1; then
echo "Error: jq is required but not installed."
exit 1
fi
# Check if JSON file exists
if [ ! -f "$json_file" ]; then
echo "Error: File '$json_file' does not exist."
exit 1
fi
# Validate JSON file content
jq empty "$json_file" 2>/dev/null
if [ $? -ne 0 ]; then
echo "Error: Invalid JSON in file '$json_file'."
exit 1
fi
# If valid, display JSON and amount
echo "Valid JSON detected!"
echo "Amount: $amount"
mac=$(generate_random_mac)

33
tools/batch_print/test.py Normal file
View file

@ -0,0 +1,33 @@
import requests
def check_mac_in_hardware(mac):
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
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')]
print(asset_tags)
if asset_tags:
print("Mac already exists in Snipe IT")
else:
print("Does not exist")
exit(0)
check_mac_in_hardware("c8:f7:50:7f:ee:ce")