forked from brngates98/Intune2snipe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
369 lines (316 loc) · 13.4 KB
/
app.py
File metadata and controls
369 lines (316 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
from dotenv import load_dotenv
import os
import re
import sys
import json
import argparse
import time
import requests
from msal import ConfidentialClientApplication
load_dotenv()
# ─── CONFIG ────────────────────────────────────────────────────────────────────
TENANT_ID = os.getenv("AZURE_TENANT_ID", "your-tenant-id")
CLIENT_ID = os.getenv("AZURE_CLIENT_ID", "your-client-id")
CLIENT_SECRET = os.getenv("AZURE_CLIENT_SECRET", "your-client-secret")
AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}"
SCOPE = ["https://graph.microsoft.com/.default"]
# Snipe-IT base URL must end in "/api/v1"
SNIPEIT_URL = os.getenv("SNIPEIT_URL", "https://your-snipeit-url/api/v1")
SNIPEIT_API_TOKEN = os.getenv("SNIPEIT_API_TOKEN", "your-snipeit-api-token")
# Default asset status label name (must match an existing Snipe-IT status label)
DEFAULT_STATUS_NAME = os.getenv("SNIPEIT_DEFAULT_STATUS", "Ready to Deploy")
# ────────────────────────────────────────────────────────────────────────────────
# MSAL client setup for Graph API
auth_app = ConfidentialClientApplication(
client_id=CLIENT_ID, client_credential=CLIENT_SECRET, authority=AUTHORITY
)
token = auth_app.acquire_token_for_client(scopes=SCOPE)
if "access_token" not in token:
raise RuntimeError("Failed to acquire Graph access token")
headers_graph = {"Authorization": f"Bearer {token['access_token']}"}
headers_snipeit = {
"Authorization": f"Bearer {SNIPEIT_API_TOKEN}",
"Accept": "application/json",
"Content-Type": "application/json",
}
# Regex to strip Android-Enterprise GUID prefixes from UPNs
GUID_PREFIX = re.compile(r"^[0-9a-f]{32}")
def normalize_upn(upn_raw):
if not upn_raw:
return None
m = GUID_PREFIX.match(upn_raw)
return upn_raw[m.end() :] if m else upn_raw
# ─── SNIPE-IT LOOKUPS & CREATORS ─────────────────────────────────────────────
def get_or_create_category(name):
if not name:
return None
r = requests.get(f"{SNIPEIT_URL}/categories?search={name}", headers=headers_snipeit)
if r.status_code == 429: # Too many requests
print("Sleeping for 35s")
time.sleep(35)
get_or_create_category(name)
rows = r.json().get("rows", [])
if rows:
return rows[0]["id"]
payload = {"name": name, "category_type": "asset"}
c = requests.post(
f"{SNIPEIT_URL}/categories", headers=headers_snipeit, json=payload
)
if c.status_code in (200, 201) and c.json().get("payload"):
return c.json()["payload"]["id"]
print(f"[WARN] Could not create category '{name}': {c.status_code} {c.text}")
return None
def get_or_create_manufacturer(name):
if not name:
return None
r = requests.get(
f"{SNIPEIT_URL}/manufacturers?search={name}", headers=headers_snipeit
)
if r.status_code == 429: # Too many requests
print("Sleeping for 35s")
time.sleep(35)
get_or_create_manufacturer(name)
rows = r.json().get("rows", [])
if rows:
return rows[0]["id"]
payload = {"name": name}
c = requests.post(
f"{SNIPEIT_URL}/manufacturers", headers=headers_snipeit, json=payload
)
if c.status_code in (200, 201) and c.json().get("payload"):
return c.json()["payload"]["id"]
print(f"[WARN] Could not create manufacturer '{name}': {c.status_code} {c.text}")
return None
def get_or_create_model(model_number, manufacturer_id, category_id):
if not model_number:
return None
r = requests.get(
f"{SNIPEIT_URL}/models?search={model_number}", headers=headers_snipeit
)
if r.status_code == 429: # Too many requests
print("Sleeping for 35s")
time.sleep(35)
get_or_create_model(model_number, manufacturer_id, category_id)
rows = r.json().get("rows", [])
for row in rows:
if row.get("model_number") == model_number or row.get("name") == model_number:
return row["id"]
payload = {
"name": model_number,
"model_number": model_number,
"manufacturer_id": manufacturer_id,
"category_id": category_id,
}
c = requests.post(f"{SNIPEIT_URL}/models", headers=headers_snipeit, json=payload)
if c.status_code in (200, 201) and c.json().get("payload"):
return c.json()["payload"]["id"]
print(f"[WARN] Could not create model '{model_number}': {c.status_code} {c.text}")
return None
def get_status_id(name):
try:
r = requests.get(f"{SNIPEIT_URL}/statuslabels", headers=headers_snipeit)
if r.status_code == 429: # Too many requests
print("Sleeping for 35s")
time.sleep(35)
get_status_id(name)
except requests.exceptions.HTTPError as e:
print(f"[ERROR] Unable to fetch status labels: {e}")
return None
rows = r.json().get("rows", [])
for sl in rows:
if sl.get("name") == name:
return sl.get("id")
print(
f"[ERROR] Status label '{name}' not found. Available: {[sl.get('name') for sl in rows]}"
)
return None
def get_snipeit_user_id(upn):
if not upn:
return None
r = requests.get(f"{SNIPEIT_URL}/users?username={upn}", headers=headers_snipeit)
if r.status_code == 429: # Too many requests
print("Sleeping for 35s")
time.sleep(35)
get_snipeit_user_id(upn)
rows = r.json().get("rows", [])
return rows[0]["id"] if rows else None
# ────────────────────────────────────────────────────────────────────────────────
def fetch_managed_devices(platform):
"""
Fetch Intune managed devices, optionally filtering by operatingSystem.
"""
url = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices"
devices = []
while url:
r = requests.get(url, headers=headers_graph)
if r.status_code == 403:
raise RuntimeError("403 Forbidden fetching devices: check permissions")
r.raise_for_status()
data = r.json()
for dev in data.get("value", []):
if not dev.get("serialNumber"):
continue # Skip devices without a serial number
os_val = dev.get("operatingSystem", "").lower()
if platform == "all":
devices.append(dev)
elif platform == "windows" and os_val.startswith("windows"):
devices.append(dev)
elif platform == "android" and "android" in os_val:
devices.append(dev)
elif platform == "ios" and "ios" in os_val:
devices.append(dev)
elif platform == "macos" and "mac" in os_val:
devices.append(dev)
url = data.get("@odata.nextLink")
return devices
def get_or_create_device(device, status_id):
url = f'{SNIPEIT_URL}/hardware?filter={{"serial":"{device.get("serialNumber")}"}}'
r = requests.get(url, headers=headers_snipeit)
resp = r.json()
if r.status_code == 200 and resp.get("rows"):
d = resp["rows"][0]
if assigned_to := d.get("assigned_to"):
assigned_to_id = assigned_to.get("id")
else:
assigned_to_id = None
return d["id"], assigned_to_id
man_name = device.get("manufacturer")
mod_number = device.get("model")
category_name = get_category_name(device)
category_id = get_or_create_category(category_name)
man_id = get_or_create_manufacturer(man_name)
mod_id = get_or_create_model(mod_number, man_id, category_id) if man_id else None
if mod_id is None:
print(f"[WARN] Skipping '{device.get('deviceName')}': model_id unavailable")
return
payload = {
"name": device.get("deviceName"),
"serial": device.get("serialNumber"),
"manufacturer_id": man_id,
"model_id": mod_id,
"status_id": status_id,
"notes": f"Imported from Intune: {man_name} {mod_number}",
"imei": device.get("imei"),
"phone_number": device.get("phoneNumber"),
}
r = requests.post(f"{SNIPEIT_URL}/hardware", headers=headers_snipeit, json=payload)
resp = r.json()
if r.status_code not in (200, 201) or resp.get("status") != "success":
print(
f"[ERROR] Failed to create '{device.get('deviceName')}': {r.status_code} {r.text}"
)
return None, None
else:
asset_id = resp["payload"]["id"]
print(f"Imported: {device.get('deviceName')} → asset ID {asset_id}")
return asset_id, None
def checkout_device(asset_id, device, assigned_to):
raw_upn = device.get("userPrincipalName")
upn = normalize_upn(raw_upn)
snipe_user_id = get_snipeit_user_id(upn)
if snipe_user_id:
if assigned_to and assigned_to == snipe_user_id:
# The device is already checked out to the correct user, no action needed
return
elif assigned_to and assigned_to != snipe_user_id:
# The device is checked out to a different user, we need to check it in first
ci = requests.post(
f"{SNIPEIT_URL}/hardware/{asset_id}/checkin",
headers=headers_snipeit,
json={"note": "Checked in automatically by script to change assigned user."},
)
if ci.status_code not in (200, 201) or ci.json().get("status") != "success":
print(
f"[ERROR] Checkin failed for asset {asset_id}, serial: {device.get('serialNumber')} "
f"before reassigning to user {snipe_user_id}: {ci.status_code} {ci.text}"
)
return
co = requests.post(
f"{SNIPEIT_URL}/hardware/{asset_id}/checkout",
headers=headers_snipeit,
json={
"checkout_to_type": "user",
"assigned_user": snipe_user_id,
"note": "Assignment made automatically, via script from Intune.",
},
)
if co.status_code in (200, 201) and co.json().get("status") == "success":
print(f"Checked out asset {asset_id} to user_id {snipe_user_id}")
else:
print(
f"[ERROR] Checkout failed for asset {asset_id}: {co.status_code} {co.text}"
)
else:
# We are gonna try to checkout to a location
location_id = None
intune_category = device.get("deviceCategoryDisplayName")
if intune_category == "Head Quarter":
location_id = 1
elif intune_category == "Warehouse":
location_id = 2
elif intune_category == "Manufacturing":
location_id = 3
else:
print(
f"[WARN] Asset {device.get('deviceName')}, serial: {device.get('serialNumber')} "
f"cannot be checked out. It doesn't have "
f"user and location '{intune_category}' not found in Snipe-IT"
)
if location_id:
co = requests.post(
f"{SNIPEIT_URL}/hardware/{asset_id}/checkout",
headers=headers_snipeit,
json={
"checkout_to_type": "location",
"assigned_location": location_id,
"note": "Assignment made automatically, via script from Intune.",
},
)
if co.status_code in (200, 201) and co.json().get("status") == "success":
print(f"Checked out asset {asset_id} to location_id {location_id}")
else:
device_serial = device.get("serialNumber")
print(
f"[ERROR] Checkout to location failed for asset {asset_id}, "
f"serial: {device_serial}: {co.status_code} {co.text}"
)
def send_to_snipeit(device, status_id, dry_run=False):
asset_id, assigned_to = get_or_create_device(device, status_id)
if not asset_id:
return
checkout_device(asset_id, device, assigned_to)
def get_category_name(device):
category = "Laptops"
splitted_name = device["deviceName"].split("_")
if len(splitted_name) > 1:
device_type = splitted_name[0].upper()
if device_type == "PDA":
category = "PDAs"
elif device_type == "TABLET":
category = "Tablets"
return category
def main(dry_run, platform):
devices = fetch_managed_devices(platform)
print(f"Found {len(devices)} Intune devices for platform '{platform}'")
status_id = get_status_id(DEFAULT_STATUS_NAME)
if status_id is None:
sys.exit(1)
for d in devices:
send_to_snipeit(
d, status_id=status_id, dry_run=dry_run
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Sync Intune → Snipe-IT")
parser.add_argument(
"--dry-run",
action="store_true",
help="Print actions without writing to Snipe-IT",
)
parser.add_argument(
"--platform",
choices=["windows", "android", "ios", "macos", "all"],
default="all",
help="Filter devices by OS",
)
args = parser.parse_args()
main(dry_run=args.dry_run, platform=args.platform)