-
Notifications
You must be signed in to change notification settings - Fork 0
/
jamf_api_tool.py
executable file
·2268 lines (2076 loc) · 87.1 KB
/
jamf_api_tool.py
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
** Jamf API Tool: List, search and clean policies and computer objects
Credentials can be supplied from the command line as arguments, or inputted, or
from an existing PLIST containing values for
JSS_URL, API_USERNAME and API_PASSWORD,
for example an AutoPkg preferences file which has been configured for use with
JSSImporter: ~/Library/Preferences/com.github.autopkg
For usage, run jamf_api_tool.py --help
"""
import argparse
import csv
import getpass
import os
import pathlib
import sys
from datetime import datetime
from jamf_api_lib import api_connect, api_get, api_delete, curl, actions, smb_actions
class Bcolors:
"""Colours for print outs"""
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKCYAN = "\033[96m"
OKGREEN = "\033[92m"
WARNING = "\033[33m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
def send_slack_notification(
jamf_url,
slack_webhook,
api_xml_object,
chosen_api_obj_name,
api_obj_action,
status_code,
):
"""Send a Slack notification"""
slack_payload = str(
f"*API {api_xml_object} {api_obj_action} action*\n"
f"Name: *{chosen_api_obj_name}*\n"
f"Instance: {jamf_url}\n"
f"HTTP Response: {status_code}"
)
print(slack_payload)
data = {"username": jamf_url, "text": slack_payload}
url = slack_webhook
request_type = "POST"
curl.request(method=request_type, auth="", url=url, verbosity=1, data=data)
def handle_computers(jamf_url, token, args, slack_webhook, verbosity):
"""Function for handling computer lists"""
if args.search and args.all:
exit("syntax error: use either --search or --all, but not both")
if not args.all:
exit("syntax error: --computers requires --all as a minimum")
recent_computers = [] # we'll need this later
old_computers = []
warning = [] # stores full detailed computer info
compliant = []
if args.all:
# fill up computers
obj = api_get.get_api_obj_list(jamf_url, "computer", token, verbosity)
try:
computers = []
for x in obj:
computers.append(x["id"])
except IndexError:
computers = "404 computers not found"
print(f"{len(computers)} computers found on {jamf_url}")
for x in computers:
# load full computer info now
print(f"...loading info for computer {x}")
obj = api_get.get_api_obj_value_from_id(
jamf_url, "computer", x, "", token, verbosity
)
macos = "unknown"
name = "unknown"
dep = "unknown"
seen = "unknown"
now = "unknown"
difference = "unknown"
if obj:
# this is now computer object
try:
macos = obj["hardware"]["os_version"]
name = obj["general"]["name"]
dep = obj["general"]["management_status"]["enrolled_via_dep"]
seen = datetime.strptime(
obj["general"]["last_contact_time"], "%Y-%m-%d %H:%M:%S"
)
now = datetime.utcnow()
except IndexError:
pass
difference = (now - seen).days
try:
if (now - seen).days < 10 and not args.os: # if recent
recent_computers.append(
f"{x} {macos}\t"
+ f"name : {name}\n"
+ f"\t\tDEP : {dep}\n"
+ f"\t\tseen : {difference} days ago"
)
if (now - seen).days < 10 and args.os and (macos >= args.os):
compliant.append(
f"{x} {macos}\t"
+ f"name : {name}\n"
+ f"\t\tDEP : {dep}\n"
+ f"\t\tseen : {difference} days ago"
)
elif (now - seen).days < 10 and args.os and (macos < args.os):
warning.append(
f"{x} {macos}\t"
+ f"name : {name}\n"
+ f"\t\tDEP : {dep}\n"
+ f"\t\tseen : {difference} days ago"
)
if (now - seen).days > 10:
old_computers.append(
f"{x} {macos}\t"
+ f"name : {name}\n"
+ f"\t\tDEP : {dep}\n"
+ f"\t\tseen : {difference} days ago"
)
except IndexError:
print("checkin calc. error")
# recent_computers.remove(f"{macos} {name} dep:{dep} seen:{calc}")
# query is done
print(Bcolors.OKCYAN + "Loading complete...\n\nSummary:" + Bcolors.ENDC)
if args.os:
# summarise os
if compliant:
print(f"{len(compliant)} compliant and recent:")
for x in compliant:
print(Bcolors.OKGREEN + x + Bcolors.ENDC)
if warning:
print(f"{len(warning)} non-compliant:")
for x in warning:
print(Bcolors.WARNING + x + Bcolors.ENDC)
if old_computers:
print(f"{len(old_computers)} stale - OS version not considered:")
for x in old_computers:
print(Bcolors.FAIL + x + Bcolors.ENDC)
else:
# regular summary
print(f"{len(recent_computers)} last check-in within the past 10 days")
for x in recent_computers:
print(Bcolors.OKGREEN + x + Bcolors.ENDC)
print(f"{len(old_computers)} stale - last check-in more than 10 days")
for x in old_computers:
print(Bcolors.FAIL + x + Bcolors.ENDC)
if args.slack:
# end a slack api webhook with this number
score = len(recent_computers) / (len(old_computers) + len(recent_computers))
score = f"{score:.2%}"
slack_payload = str(
f":hospital: update health: {score} - {len(old_computers)} "
f"need to be fixed on {jamf_url}\n"
)
print(slack_payload)
data = {"text": slack_payload}
for x in old_computers:
print(Bcolors.WARNING + x + Bcolors.ENDC)
slack_payload += str(f"{x}\n")
data = {"text": slack_payload}
url = slack_webhook
request_type = "POST"
curl.request(request_type, url, token, verbosity, data)
def handle_policies(jamf_url, token, args, slack_webhook, verbosity):
"""Function for handling policies"""
# declare the csv data for export
csv_fields = [
"policy_id",
"policy_name",
"policy_enabled",
"policy_category",
"pkg",
"scope",
"exclusions",
]
csv_data = []
# create more specific output filename
csv_path = os.path.dirname(args.csv)
csv_file = os.path.basename(args.csv)
if args.all or args.disabled or args.unused:
if args.disabled:
csv_write = os.path.join(csv_path, "Policies", "Disabled", csv_file)
if args.unused:
csv_write = os.path.join(csv_path, "Policies", "Unused", csv_file)
else:
csv_write = os.path.join(csv_path, "Policies", "All", csv_file)
categories = api_get.get_uapi_obj_list(jamf_url, "category", token, verbosity)
if verbosity > 1:
print(f"Categories: {categories}")
if categories:
disabled_policies = {}
unused_policies = {}
for category in categories:
# loop all the categories
print(
Bcolors.OKCYAN
+ f"category {category['id']}\t{category['name']}"
+ Bcolors.ENDC
)
policies = api_get.get_policies_in_category(
jamf_url, category["id"], token, verbosity
)
if policies:
# loop through all the policies
for policy in policies:
groups = []
exclusion_groups = []
generic_info = api_get.get_api_obj_value_from_id(
jamf_url, "policy", policy["id"], "", token, verbosity
)
# get scope
if generic_info["scope"]["all_computers"]:
groups.append("All Computers")
unused = "false"
else:
g_count = len(generic_info["scope"]["computer_groups"])
for g in range(g_count):
groups.append(
generic_info["scope"]["computer_groups"][g][
"name"
] # noqa: E501
)
if len(groups) < 1:
unused = "true"
else:
unused = "false"
eg_count = len(
generic_info["scope"]["exclusions"][
"computer_groups"
] # noqa: E501
)
for eg in range(eg_count):
exclusion_groups.append(
generic_info["scope"]["exclusions"]["computer_groups"][
eg
][
"name"
] # noqa: E501
)
# get enabled status
if generic_info["general"]["enabled"] is True:
enabled = "true"
else:
enabled = "false"
# get packages
try:
pkg = generic_info["package_configuration"]["packages"][0][
"name"
] # noqa: E501
except IndexError:
pkg = "none"
# now show all the policies as each category loops
if enabled == "false":
disabled_policies[policy["id"]] = policy["name"]
if verbosity > 1:
print(
f"Number of disabled policies: {len(disabled_policies)}" # noqa: E501
)
if unused == "true":
unused_policies[policy["id"]] = policy["name"]
if verbosity > 1:
print(
f"Number of unused policies: {len(unused_policies)}" # noqa: E501
)
do_print = 1
if args.disabled and enabled == "true":
do_print = 0
if args.unused and unused == "false":
do_print = 0
if do_print == 1:
print(
Bcolors.WARNING
+ f" policy {policy['id']}"
+ f"\tname : {policy['name']}\n"
+ Bcolors.ENDC
+ f"\t\tenabled : {enabled}\n"
+ f"\t\tpkg : {pkg}\n"
+ f"\t\tscope : {groups}\n"
+ f"\t\texclusions : {exclusion_groups}"
)
csv_data.append(
{
"policy_id": policy["id"],
"policy_name": policy["name"],
"policy_category": category["name"],
"policy_enabled": enabled,
"pkg": pkg,
"scope": groups,
"exclusions": exclusion_groups,
}
)
pathlib.Path(os.path.dirname(csv_write)).mkdir(parents=True, exist_ok=True)
api_connect.write_csv_file(csv_write, csv_fields, csv_data)
print(
"\n"
+ Bcolors.OKGREEN
+ f"CSV file written to {csv_write}"
+ Bcolors.ENDC
)
id_list = ""
if (len(disabled_policies) > 0 or len(unused_policies) > 0) and args.delete:
if args.disabled:
policy_type = "disabled"
policies_to_act_on = disabled_policies
else:
policy_type = "unused"
policies_to_act_on = unused_policies
if actions.confirm(
prompt=(
f"\nDelete all {policy_type} policies?"
"\n(press n to go on to confirm individually)?"
),
default=False,
):
delete_all = True
else:
delete_all = False
# Enter the IDs of the policies you want to delete
if not delete_all:
for policy_id, policy_name in policies_to_act_on.items():
print(policy_id, ":", policy_name)
chosen_ids = input(
"Enter the IDs of the policies you want to delete, "
"or leave blank to go through all: "
)
id_list = chosen_ids.split()
# prompt to delete each policy in turn
for policy_id, policy_name in policies_to_act_on.items():
if delete_all or (
(policy_id in id_list or not id_list)
and actions.confirm(
prompt=(
Bcolors.OKBLUE
+ f"Delete [{policy_id}] {policy_name}?"
+ Bcolors.ENDC
),
default=False,
)
):
print(f"Deleting {policy_name}...")
status_code = api_delete.delete_api_object(
jamf_url, "policy", policy_id, token, verbosity
)
if args.slack:
send_slack_notification(
jamf_url,
slack_webhook,
"policy",
policy_name,
"delete",
status_code,
)
else:
print("something went wrong: no categories found.")
print(
"\n"
+ Bcolors.OKGREEN
+ f"All policies listed above... program complete for {jamf_url}"
+ Bcolors.ENDC
)
elif args.search:
query = args.search
csv_write = os.path.join(csv_path, "Policies", "Search", csv_file)
policies = api_get.get_api_obj_list(jamf_url, "policy", token, verbosity)
if policies:
# targets is the new list
targets = []
print(
f"Searching {len(policies)} policy/ies on {jamf_url}:\n"
"To delete policies, obtain a matching query, "
"then run with the "
"--delete argument"
)
for x in query:
for policy in policies:
# do the actual search
if x in policy["name"]:
targets.append(policy.copy())
if len(targets) > 0:
print("Policies found:")
for target in targets:
print(
Bcolors.WARNING
+ f"- policy {target['id']}"
+ f"\tname : {target['name']}"
+ Bcolors.ENDC
)
csv_data.append(
{
"policy_id": target["id"],
"policy_name": target["name"],
}
)
pathlib.Path(os.path.dirname(csv_write)).mkdir(
parents=True, exist_ok=True
)
api_connect.write_csv_file(csv_write, csv_fields, csv_data)
print(
"\n"
+ Bcolors.OKGREEN
+ f"CSV file written to {csv_write}"
+ Bcolors.ENDC
)
if args.delete:
api_delete.delete_api_object(
jamf_url, "policy", target["id"], token, verbosity
)
print(f"{len(targets)} total matches")
else:
for partial in query:
print(f"No match found: {partial}")
else:
sys.exit("ERROR: with --policies you must supply --search or --all.")
def handle_policies_from_csv_data(jamf_url, token, args, slack_webhook, verbosity):
"""Function for deleting policies based on IDs in a CSV"""
# import csv
# create more specific output filename
csv_path = os.path.dirname(args.csv)
csv_file = os.path.basename(args.csv)
csv_read = os.path.join(csv_path, "Policies", "To Delete", csv_file)
print("\nPolicies:\n")
# generate a list of IDs from the csv
# with open(csv_read, "r", encoding="utf-8") as csvdata:
# creating a csv dict reader object
reader = csv.DictReader(
open(csv_read, "r", encoding="utf-8"),
delimiter=";",
)
for row in reader:
policy_id = row["policy_id"]
policy_name = row["policy_name"]
print(f"[{policy_id}] - {policy_name}")
# confirm All or per item
if args.delete:
if actions.confirm(
prompt=(
"\nDelete all listed policies?"
"\n(press n to go on to confirm individually)?"
),
default=False,
):
delete_all = True
else:
delete_all = False
id_list = ""
# Enter the IDs of the policies you want to delete
if not delete_all:
chosen_ids = input(
"Enter the IDs of the policies you want to delete or leave blank to go through all: "
)
id_list = chosen_ids.split()
# prompt to delete each policy in turn
reader = csv.DictReader(
open(csv_read, "r", encoding="utf-8"),
delimiter=";",
)
for row in reader:
policy_id = row["policy_id"]
policy_name = row["policy_name"]
if delete_all or (
(policy_id in id_list or not id_list)
and actions.confirm(
prompt=(
Bcolors.OKBLUE
+ f"Delete [{policy_id}] - {policy_name}?"
+ Bcolors.ENDC
),
default=False,
)
):
print(f"Deleting {policy_name}...")
status_code = api_delete.delete_api_object(
jamf_url, "policy", policy_id, token, verbosity
)
if args.slack:
send_slack_notification(
jamf_url,
slack_webhook,
"policy",
policy_name,
"delete",
status_code,
)
def handle_policies_in_category(jamf_url, token, args, slack_webhook, verbosity):
"""Function for handling policies in a specific category"""
csv_fields = [
"policy_id",
"policy_name",
"category",
]
csv_data = []
categories = args.category
# print(f"categories to check are:\n{categories}\nTotal: {len(categories)}")
# now process the list of categories
for category in categories:
# create more specific output filename
csv_path = os.path.dirname(args.csv)
csv_file = os.path.basename(args.csv)
csv_write = os.path.join(csv_path, "Policies", "Categories", category, csv_file)
category = category.replace(" ", "%20")
# return all policies found in each category
print(f"\nChecking '{category}' on {jamf_url}")
obj = api_get.get_policies_in_category(jamf_url, category, token, verbosity)
if obj:
if not args.delete:
print(
f"Category '{category}' exists with {len(obj)} policies: "
"To delete them run this command again "
"with the --delete flag."
)
policies_in_category = {}
for obj_item in obj:
policies_in_category[obj_item["id"]] = obj_item["name"]
for policy_id, policy_name in policies_in_category.items():
print(Bcolors.FAIL + f"[{policy_id}] " + policy_name + Bcolors.ENDC)
csv_data.append(
{
"policy_id": policy_id,
"policy_name": policy_name,
"category": category,
}
)
if args.delete:
if actions.confirm(
prompt=(
f"\nDelete all policies in category '{category}'?"
"\n(press n to go on to confirm individually)?"
),
default=False,
):
delete_all = True
else:
delete_all = False
# Enter the IDs of the policies you want to delete
if not delete_all:
chosen_ids = input(
"Enter the IDs of the policies you want to delete or leave blank to go through all: "
)
id_list = chosen_ids.split()
id_list = ""
# prompt to delete each package in turn
for policy_id, policy_name in policies_in_category.items():
if delete_all or (
(policy_id in id_list or not id_list)
and actions.confirm(
prompt=(
Bcolors.OKBLUE
+ f"Delete [{policy_id}] {policy_name}?"
+ Bcolors.ENDC
),
default=False,
)
):
print(f"Deleting {policy_name}...")
status_code = api_delete.delete_api_object(
jamf_url, "policy", policy_id, token, verbosity
)
if args.slack:
send_slack_notification(
jamf_url,
slack_webhook,
"policy",
policy_name,
"delete",
status_code,
)
pathlib.Path(os.path.dirname(csv_write)).mkdir(parents=True, exist_ok=True)
api_connect.write_csv_file(csv_write, csv_fields, csv_data)
print(
"\n"
+ Bcolors.OKGREEN
+ f"CSV file written to {csv_write}"
+ Bcolors.ENDC
)
else:
print(f"Category '{category}' not found")
def handle_policy_list(jamf_url, token, args, slack_webhook, verbosity):
"""Function for handling a search list of policies"""
policy_names = args.names
print(
"policy names to check are:\n" f"{policy_names}\n" f"Total: {len(policy_names)}"
)
for policy_name in policy_names:
print(f"\nChecking '{policy_name}' on {jamf_url}")
obj_id = api_get.get_api_obj_id_from_name(
jamf_url, "policy", policy_name, token, verbosity
)
if obj_id:
# gather info from interesting parts of the policy API
# use a single call
# general/name
# scope/computer_gropus [0]['name']
generic_info = api_get.get_api_obj_value_from_id(
jamf_url, "policy", obj_id, "", token, verbosity
)
name = generic_info["general"]["name"]
try:
groups = generic_info["scope"]["computer_groups"][0]["name"]
except IndexError:
groups = ""
print(f"Match found: '{name}' ID: {obj_id} Group: {groups}")
if args.delete:
status_code = api_delete.delete_api_object(
jamf_url, "policy", obj_id, token, verbosity
)
if args.slack:
send_slack_notification(
jamf_url,
slack_webhook,
"policy",
policy_name,
"delete",
status_code,
)
else:
print(f"Policy '{policy_name}' not found")
def handle_profiles(jamf_url, api_endpoint, token, args, slack_webhook, verbosity):
"""Function for handling profiles"""
# declare the csv data for export
csv_fields = [
"profile_id",
"profile_name",
"category",
"distribution_method",
"scope",
"exclusions",
]
csv_data = []
if args.all or args.unused:
profiles = api_get.get_api_obj_list(jamf_url, api_endpoint, token, verbosity)
# create more specific output filename
csv_path = os.path.dirname(args.csv)
csv_file = os.path.basename(args.csv)
if "os_x" in api_endpoint:
profile_type = "Computer Profiles"
else:
profile_type = "Mobile Device Profiles"
if args.unused:
csv_write = os.path.join(csv_path, profile_type, "Unused", csv_file)
else:
csv_write = os.path.join(csv_path, profile_type, "All", csv_file)
if profiles:
unused_profiles = {}
for profile in profiles:
# loop all the profiles
groups = []
exclusion_groups = []
unused = "false"
if args.details or args.unused:
# gather interesting info for each profile via API
results = api_get.get_api_obj_from_id(
jamf_url, api_endpoint, profile["id"], token, verbosity
)
generic_info = results[api_endpoint]
category = generic_info["general"]["category"]["name"]
try: # macOS
distribution_method = generic_info["general"][
"distribution_method"
]
except KeyError: # iOS
distribution_method = generic_info["general"][
"deployment_method"
]
# get scope
if args.macosprofiles:
if generic_info["scope"]["all_computers"]:
groups = ["All Computers"]
unused = "false"
else:
g_count = len(generic_info["scope"]["computer_groups"])
for g in range(g_count):
groups.append(
generic_info["scope"]["computer_groups"][g][
"name"
] # noqa: E501
)
if len(groups) < 1:
unused = "true"
eg_count = len(
generic_info["scope"]["exclusions"][
"computer_groups"
] # noqa: E501
)
for eg in range(eg_count):
exclusion_groups.append(
generic_info["scope"]["exclusions"]["computer_groups"][
eg
][
"name"
] # noqa: E501
)
else:
if generic_info["scope"]["all_mobile_devices"]:
groups = ["All Mobile Devices"]
else:
g_count = len(generic_info["scope"]["mobile_device_groups"])
for g in range(g_count):
groups.append(
generic_info["scope"]["mobile_device_groups"][g][
"name"
] # noqa: E501
)
if len(groups) < 1:
unused = "true"
eg_count = len(
generic_info["scope"]["exclusions"][
"mobile_device_groups"
] # noqa: E501
)
for eg in range(eg_count):
exclusion_groups.append(
generic_info["scope"]["exclusions"][
"mobile_device_groups"
][eg][
"name"
] # noqa: E501
)
if unused == "true":
unused_profiles[profile["id"]] = profile["name"]
if verbosity:
print(
f"Number of unused profiles: {len(unused_profiles)}" # noqa: E501
)
do_print = 1
if args.unused and unused == "false":
do_print = 0
if do_print == 1:
print(
Bcolors.WARNING
+ f" profile {profile['id']}"
+ f"\tname : {profile['name']}\n"
+ Bcolors.ENDC
+ f"\t\tcategory : {category}\n"
+ f"\t\tdistribution_method : {distribution_method}\n"
+ f"\t\tscope : {groups}\n"
+ f"\t\texclusions : {exclusion_groups}"
)
csv_data.append(
{
"profile_id": profile["id"],
"profile_name": profile["name"],
"category": category,
"distribution_method": distribution_method,
"scope": groups,
"exclusions": exclusion_groups,
}
)
else:
print(
Bcolors.WARNING
+ f" profile {profile['id']}\n"
+ f" name : {profile['name']}"
+ Bcolors.ENDC
)
if args.details or args.unused:
pathlib.Path(os.path.dirname(csv_write)).mkdir(
parents=True, exist_ok=True
)
api_connect.write_csv_file(csv_write, csv_fields, csv_data)
print(
"\n"
+ Bcolors.OKGREEN
+ f"CSV file written to {csv_write}"
+ Bcolors.ENDC
)
id_list = ""
if len(unused_profiles) > 0 and args.delete:
if actions.confirm(
prompt=(
f"\nDelete all unused {api_endpoint}?"
"\n(press n to go on to confirm individually)?"
),
default=False,
):
delete_all = True
else:
delete_all = False
# Enter the IDs of the policies you want to delete
if not delete_all:
for profile_id, profile_name in unused_profiles.items():
print(profile_id, ":", profile_name)
chosen_ids = input(
f"Enter the IDs of the {api_endpoint} you want to delete, "
"or leave blank to go through all: "
)
id_list = chosen_ids.split()
# prompt to delete each policy in turn
for profile_id, profile_name in unused_profiles.items():
if delete_all or (
(profile_id in id_list or not id_list)
and actions.confirm(
prompt=(
Bcolors.OKBLUE
+ f"Delete [{profile_id}] {profile_name}?"
+ Bcolors.ENDC
),
default=False,
)
):
print(f"Deleting {profile_name}...")
status_code = api_delete.delete_api_object(
jamf_url, api_endpoint, profile_id, token, verbosity
)
if args.slack:
send_slack_notification(
jamf_url,
slack_webhook,
api_endpoint,
profile_name,
"delete",
status_code,
)
else:
print("\nNo profiles found")
else:
exit("ERROR: with --computerprofiles you must supply --all or --unused.")
def handle_advancedsearches(jamf_url, api_endpoint, token, args, verbosity):
"""Function for handling advanced searches"""
# declare the csv data for export
csv_fields = ["search_id", "search_name"]
csv_data = []
if args.all:
# create more specific output filename
csv_path = os.path.dirname(args.csv)
csv_file = os.path.basename(args.csv)
csv_write = os.path.join(csv_path, "Advanced Searches", csv_file)
advancedsearches = api_get.get_api_obj_list(
jamf_url, api_endpoint, token, verbosity
)
if advancedsearches:
for search in advancedsearches:
# loop all the advancedsearches
print(
Bcolors.WARNING
+ f" advancedsearch {search['id']}\n"
+ f" name : {search['name']}"
+ Bcolors.ENDC
)
csv_data.append(
{
"search_id": search["id"],
"search_name": search["name"],
}
)
if args.details:
pathlib.Path(os.path.dirname(csv_write)).mkdir(
parents=True, exist_ok=True
)
api_connect.write_csv_file(args.csv, csv_fields, csv_data)
print(
"\n"
+ Bcolors.OKGREEN
+ f"CSV file written to {csv_write}"
+ Bcolors.ENDC
)
else:
print("\nNo profiles found")
else:
exit("ERROR: with --computerprofiles you must supply --all.")
def handle_packages(jamf_url, token, args, slack_webhook, verbosity):
"""Function for handling packages"""
unused_packages = {}
used_packages = {}
if args.unused:
# get a list of packages in prestage enrollments
packages_in_prestages = api_get.get_packages_in_prestages(
jamf_url, token, verbosity
)
# get a list of packages in patch software titles
packages_in_titles = api_get.get_packages_in_patch_titles(
jamf_url, token, verbosity
)
# get a list of packages in policies
packages_in_policies = api_get.get_packages_in_policies(
jamf_url, token, verbosity
)
else:
packages_in_policies = []
packages_in_titles = []
packages_in_prestages = []
# create more specific output filename
csv_path = os.path.dirname(args.csv)
csv_file = os.path.basename(args.csv)
csv_fields = ""
csv_write = ""
if args.all or args.unused:
packages = api_get.get_api_obj_list(jamf_url, "package", token, verbosity)
if packages:
# declare the csv data for export
if args.unused:
csv_fields = ["pkg_id", "pkg_name", "used"]
csv_data = []
csv_write = os.path.join(csv_path, "Packages", "Unused", csv_file)
elif args.details:
csv_fields = [
"pkg_id",
"pkg_name",