This repository has been archived by the owner on Apr 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathspruce.py
executable file
·2440 lines (2063 loc) · 82.8 KB
/
spruce.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/local/autopkg/python
# -*- coding: utf-8 -*-
# Copyright (C) 2015-2018 Shea G Craig
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Spruce is a tool to help you clean up your filthy JSS."""
import argparse
from collections import Counter, namedtuple
import datetime
from distutils.version import StrictVersion
from html.parser import HTMLParser
import os
import re
import subprocess
import sys
import textwrap
from xml.etree import ElementTree as ET
# pylint: disable=import-error
from Foundation import (
NSData,
NSPropertyListSerialization,
NSPropertyListMutableContainersAndLeaves,
NSPropertyListXMLFormat_v1_0,
)
sys.path.insert(0, "/Library/AutoPkg/JSSImporter")
import requests
import jss
# pylint: enable=import-error
# Ensure that python-jss dependency is at minimum version
try:
from jss import __version__ as PYTHON_JSS_VERSION
except ImportError:
PYTHON_JSS_VERSION = "0.0.0"
REQUIRED_PYTHON_JSS_VERSION = StrictVersion("2.1.0")
# Globals
# Edit these if you want to change their default values.
AUTOPKG_PREFERENCES = "~/Library/Preferences/com.github.autopkg.plist"
PYTHON_JSS_PREFERENCES = "~/Library/Preferences/com.github.sheagcraig.python-jss.plist"
DESCRIPTION = (
"Spruce is a tool to help you clean up your filthy JSS."
"\n\nUsing the various reporting options, you can see "
"unused packages, printers, scripts,\ncomputer groups, "
"extension attributes, configuration profiles, mobile "
"device groups, and mobile\ndevice configuration "
"profiles.\n\nReports are by default output to stdout, "
"and may optionally be output as\nXML for later use in "
"automated removal.\n\n"
"Spruce uses configured AutoPkg/JSSImporter settings "
"first. If those are\nmissing, Spruce falls back to "
"python-jss settings.\n\nThe recommended workflow is to "
"begin by running the reports you find\ninteresting. "
"After becoming familiar with the scale of unused "
"things,\nreports can be output with the -o/--ofile "
"option. This file can then be\nedited down to include "
"only those things which you wish to remove.\nFinally, "
"pass this filename as an option to the --remove "
"argument to\nremove the specified objects."
)
__version__ = "2.0.1"
class Error(Exception):
"""Module base exception."""
pass
class PlistParseError(Error):
"""Error parsing a plist file."""
pass
class PlistDataError(Error):
"""Data can not be serialized to plist."""
pass
class PlistWriteError(Error):
"""Error writing a plist file."""
pass
class Plist(dict):
"""Abbreviated plist representation (as a dict)."""
def __init__(self, filename=None):
"""Init a Plist, optionally from parsing an existing file.
Args:
filename: String path to a plist file.
"""
if filename:
dict.__init__(self, self.read_file(filename))
else:
dict.__init__(self)
self.new_plist()
def read_file(self, path):
"""Replace internal XML dict with data from plist at path.
Args:
path: String path to a plist file.
Raises:
PlistParseError: Error in reading plist file.
"""
# pylint: disable=unused-variable
(
info,
pformat,
error,
) = NSPropertyListSerialization.propertyListWithData_options_format_error_(
NSData.dataWithContentsOfFile_(os.path.expanduser(path)),
NSPropertyListMutableContainersAndLeaves,
None,
None,
)
# pylint: enable=unused-variable
if info is None:
if error is None:
error = "Invalid plist file."
raise PlistParseError("Can't read %s: %s" % (path, error))
return info
def write_plist(self, path):
"""Write plist to path.
Args:
path: String path to desired plist file.
Raises:
PlistDataError: There was an error in the data.
PlistWriteError: Plist could not be written.
"""
(
plist_data,
error,
) = NSPropertyListSerialization.dataWithPropertyList_format_options_error_(
self, NSPropertyListXMLFormat_v1_0, 0, None
)
if plist_data is None:
if error is None:
error = "Failed to serialize data to plist."
raise PlistDataError(error)
else:
if not plist_data.writeToFile_atomically_(os.path.expanduser(path), True):
raise PlistWriteError("Failed writing data to %s" % path)
def new_plist(self):
"""Generate a barebones recipe plist."""
# Not implemented at this time.
pass
class JSSConnection(object):
"""Class for providing a single JSS connection."""
_jss_prefs = None
_jss = None
@classmethod
def setup(cls, connection=None):
"""Set up the jss connection class variable.
If no connection argument is provided, setup will use the
standard JSSImporter preferences
(com.github.autopkg).
Args:
connection: Dictionary with JSS connection info, keys:
jss_prefs: String path to a preference file.
url: Path with port to a JSS.
user: API Username.
password: API Password.
repo_prefs: A list of dicts with repository names and
passwords. See JSSPrefs.
ssl_verify: Boolean indicating whether to verify SSL
certificates. Defaults to True.
verbose: Boolean indicating the level of logging.
(Doesn't do much.)
jss_migrated: Boolean indicating whether scripts have
been migrated to the database. Used for determining
copy_script type.
suppress_warnings:
Turns off the urllib3 warnings. Remember, these
warnings are there for a reason! Use at your own
risk.
"""
if not connection:
connection = {"jss_prefs": jss.JSSPrefs()}
cls._jss_prefs = connection
# pylint: disable=not-a-mapping
if isinstance(connection, jss.JSSPrefs):
cls._jss = jss.JSS(jss_prefs=cls._jss_prefs)
else:
cls._jss = jss.JSS(**cls._jss_prefs)
# pylint: enable=not-a-mapping
@classmethod
def get(cls):
"""Return the shared JSS object."""
if not cls._jss:
cls.setup()
return cls._jss
class Result(object):
"""Encapsulates the metadata and results from a report."""
def __init__(self, results, verbose, heading, description=""):
"""Init our data structure.
Args:
results: A set of strings of some JSSObject names.
include_in_non_verbose: Bool whether or not report will be
included in non-verbose output.
heading: String heading summarizing the results.
description: Longer string describing the meaning of the
results.
"""
self.results = results
self.include_in_non_verbose = verbose
self.heading = heading
self.description = description
def __len__(self):
"""Return the length of the results list."""
return len(self.results)
class Report(object):
"""Represents a collection of Result objects."""
def __init__(self, obj_type, results, heading, metadata):
"""Init our data structure.
Args:
obj_type: String object type name (as returned by
device_type)
results: A list of Result objects to include in the
report.
heading: String heading describing the report.
metadata: Dictionary of other data you want to output.
key: Heading name.
val Another dictionary, with:
key: Subheading name.
val: String of data to print.
"""
self.obj_type = obj_type
self.results = results
self.heading = heading
self.metadata = metadata
def get_result_by_name(self, name):
"""Return a result with argument name.
Args:
name: String name to find in results.
Returns:
A Result object or None.
"""
found = None
for result in self.results:
if result.heading == name:
found = result
break
return found
class AppStoreVersionParser(HTMLParser):
"""Subclasses HTMLParser to scrape current app version number."""
def __init__(self):
HTMLParser.__init__(self)
self.version = "Version Not Found"
self.in_version_span = False
def reset(self):
"""Manage data state to know when we are in the version span."""
HTMLParser.reset(self)
self.in_version_span = False
def handle_starttag(self, tag, attrs):
"""Override handling of tags to find version metadata."""
# <span itemprop="softwareVersion">3.0.3
attrs_dict = dict(attrs)
if (
tag == "span"
and "itemprop" in attrs_dict
and attrs_dict["itemprop"] == "softwareVersion"
):
self.in_version_span = True
def handle_data(self, data):
if self.in_version_span:
self.version = data
self.in_version_span = False
def map_jssimporter_prefs(prefs):
"""Convert python-jss preferences to JSSImporter preferences."""
connection = {}
connection["url"] = prefs["JSS_URL"]
connection["user"] = prefs["API_USERNAME"]
connection["password"] = prefs["API_PASSWORD"]
connection["ssl_verify"] = prefs.get("JSS_VERIFY_SSL", True)
connection["suppress_warnings"] = prefs.get("JSS_SUPPRESS_WARNINGS", True)
connection["jss_migrated"] = prefs.get("JSS_MIGRATED", True)
connection["repo_prefs"] = prefs.get("JSS_REPOS")
print("JSS: {}".format(connection["url"]))
return connection
def build_container_report(containers_with_search_paths, jss_objects):
"""Report on the usage of objects contained in container objects.
Find the used and unused jss_objects across a list of containing
JSSContainerObjects.
For example, Computers can have packages or scripts scoped to
policies or configurations.
Args:
containers_with_search_paths: A list of 2-tuples of:
([list of JSSContainerObjects], xpath to search for
contained objects)
jss_objects: A list of JSSObject names to search for in
the containers_with_search_paths.
Returns:
A Report object with results and "cruftiness" metadata
added, but no heading.
"""
used_object_sets = []
for containers, search in containers_with_search_paths:
search = "container.%s" % search.replace("/", ".")
for container in containers: # pylint: disable=unused-variable
try:
obj = eval(search)
if obj is not None:
used_object_sets.append({(obj.id.text, obj.name.text)})
except AttributeError:
pass
used = set()
if used_object_sets:
used = used_object_sets.pop()
for used_object_set in used_object_sets:
used = used.union(used_object_set)
unused = set(jss_objects).difference(used)
# Use the xpath's second to last part to determine object type.
obj_type = (
containers_with_search_paths[0][1].split("/")[-1].replace("_", " ").title()
)
all_result = Result(jss_objects, False, "All", "All %ss on the JSS." % obj_type)
used_result = Result(used, False, "Used")
unused_result = Result(unused, True, "Unused")
report = Report(
obj_type, [all_result, used_result, unused_result], "", {"Cruftiness": {}}
)
cruftiness = calculate_cruft(
report.get_result_by_name("Unused").results,
report.get_result_by_name("All").results,
)
cruft_strings = get_cruft_strings(cruftiness)
report.metadata["Cruftiness"] = {"Unscoped %s Cruftiness" % obj_type: cruft_strings}
return report
def build_device_report(check_in_period, devices):
"""Build a report of out-of-date or unresponsive devices.
Finds the newest OS version and looks for devices which are out
of date. (Builds a histogram of installed OS versions).
Compiles a list of devices which have not checked in for
'check_in_period' days.
Finally, does a report on the hardware models present.
Args:
check_in_period: Integer number of days since last check-in to
include in report. Defaults to 30.
devices: List of all Computer or MobileDevice objects from the
JSS. These lists can be subsetted to include only the
sections needed for this report.
Returns:
A Report object.
"""
check_in_period = validate_check_in_period(check_in_period)
device_name = device_type(devices)
report = Report(device_name, [], "%s Report" % device_name, {"Cruftiness": {}})
# Out of Date results.
out_of_date_results = get_out_of_date_devices(check_in_period, devices)
report.results.append(out_of_date_results[0])
report.metadata["Cruftiness"][
"%ss Not Checked In Cruftiness" % device_name
] = out_of_date_results[1]
# Orphaned device results.
orphaned_device_results = get_orphaned_devices(devices)
report.results.append(orphaned_device_results[0])
report.metadata["Cruftiness"][
"%ss With no Group Membership Cruftiness" % device_name
] = orphaned_device_results[1]
# Version and model results.
(
report.metadata["Version Spread"],
report.metadata["Hardware Model Spread"],
) = get_version_and_model_spread(devices)
# All Devices
all_devices = [(device.id, device.name) for device in devices]
report.results.append(Result(all_devices, False, "All %ss" % device_name))
return report
def get_out_of_date_devices(check_in_period, devices):
"""Produce a report on devices not checked in since check_in_period.
Args:
check_in_period: Number of days to consider out of date.
devices: List of all Computer or MobileDevice objects on the
JSS.
Returns:
Tuple of (Result object, cruftiness)
"""
device_name = device_type(devices)
strptime = datetime.datetime.strptime
out_of_date = datetime.datetime.now() - datetime.timedelta(check_in_period)
# Example computer contact time format: 2015-08-06 10:46:51
# Example mobile device time format:Friday, August 07 2015 at 3:51 PM
if isinstance(devices[0], jss.Computer):
fmt_string = "%Y-%m-%d %H:%M:%S"
check_in = "general/last_contact_time"
else:
fmt_string = "%A, %B %d %Y at %H:%M %p"
check_in = "general/last_inventory_update"
out_of_date_devices = []
for device in devices:
last_contact = device.findtext(check_in)
# Fix incorrectly formatted Mobile Device times.
if last_contact and isinstance(device, jss.MobileDevice):
last_contact = hour_pad(last_contact)
if not last_contact or (strptime(last_contact, fmt_string) < out_of_date):
out_of_date_devices.append((device.id, device.name))
description = (
"This report collects %ss which have not checked in for "
"more than %i days (%s) based on their %s property."
% (device_name, check_in_period, out_of_date, check_in.split("/")[1])
)
out_of_date_report = Result(
out_of_date_devices, True, "Out of Date %ss" % device_name, description
)
out_of_date_cruftiness = calculate_cruft(out_of_date_report.results, devices)
cruftiness = get_cruft_strings(out_of_date_cruftiness)
return (out_of_date_report, cruftiness)
def get_orphaned_devices(devices):
"""Generate Result of devices with no group memberships.
Also, include a cruftiness result.
Args:
devices: List of all Computer or MobileDevice objects on the
JSS.
Returns:
Tuple of (Result object, cruftiness)
"""
device_name = device_type(devices)
orphaned_devices = [
(device.id, device.name)
for device in devices
if has_no_group_membership(device)
]
description = (
"This report collects %ss which do not belong to any "
"static or smart groups." % device_name
)
orphan_report = Result(
orphaned_devices,
True,
"%ss With no Group Membership" % device_name,
description,
)
orphan_cruftiness = calculate_cruft(orphan_report.results, devices)
cruftiness = get_cruft_strings(orphan_cruftiness)
return (orphan_report, cruftiness)
def device_type(devices):
"""Return a string type name for a list of devices."""
num_of_types = len({type(device) for device in devices})
if num_of_types == 1:
# print("TEST: device: %s" % type(devices[0]).__name__)
return type(devices[0]).__name__
elif num_of_types == 0:
return None
else:
raise ValueError
def get_version_and_model_spread(devices):
"""Generate version spread metadata for device reports.
Args:
devices: List of all Computer or MobileDevice objects on the
JSS.
Returns:
Dictionary appropriate for use in Report.metadata.
"""
if isinstance(devices[0], jss.Computer):
os_type_search = "hardware/os_name"
os_type = "Mac OS X"
os_version_search = "hardware/os_version"
model_search = "hardware/model"
model_identifier_search = "hardware/model_identifier"
else:
os_type_search = "general/os_type"
os_type = "iOS"
os_version_search = "general/os_version"
model_search = "general/model"
model_identifier_search = "general/model_identifier"
versions, models = [], []
for device in devices:
if device.findtext(os_type_search) == os_type:
versions.append(
device.findtext(os_version_search) or "No Version Inventoried"
)
models.append(
"%s / %s"
% (
device.findtext(model_search) or "No Model",
device.findtext(model_identifier_search,) or "No Model Identifier",
)
)
version_counts = Counter(versions)
# Standardize version number format.
version_counts = fix_version_counts(version_counts)
model_counts = Counter(models)
total = len(devices)
# Report on OS version spread
strings = sorted(get_histogram_strings(version_counts, padding=8))
version_metadata = {"%s Version Histogram (%s)" % (os_type, total): strings}
# Report on Model Spread
# Compare on the model identifier since it is an easy numerical
# sort.
strings = sorted(get_histogram_strings(model_counts, padding=8), key=model_compare)
model_metadata = {"Hardware Model Histogram (%s)" % total: strings}
return (version_metadata, model_metadata)
def model_compare(histogram_string):
"""Return Model Identifier for use as key in sorted() function.
Args:
histogram_string: Histogram string comprising of Mac model, count and emoji e.g.
iMac Intel (21.5-inch, Late 2013) / iMac14,1 (2): 🍕🍕🍕🍕🍕🍕
Returns:
Model Identifier e.g. iMac14,1
"""
pattern = re.compile(r"(\D+\d+,\d+)")
string_search = re.search(pattern, histogram_string)
if string_search:
return string_search.group(1)
def build_computers_report(check_in_period, **kwargs):
"""Build a report of out-of-date or unresponsive computers.
Finds the newest OS version and looks for computers which are out
of date. (Builds a histogram of installed OS versions).
Also, compiles a list of computers which have not checked in for
'check_in_period' days.
Finally, does a report on the hardware models present.
Args:
check_in_period: Integer number of days since last check-in to
include in report. Defaults to 30.
Returns:
A Report object.
"""
# All report functions support kwargs to support a unified interface,
# even if they don't use them.
_ = kwargs
jss_connection = JSSConnection.get()
all_computers = jss_connection.Computer(
["general", "hardware", "groups_accounts"]
).retrieve_all()
if all_computers:
report = build_device_report(check_in_period, all_computers)
report.heading = "Computer Report"
else:
report = Report("Computer", [], "Computer Report", {})
return report
def build_mobile_devices_report(check_in_period, **kwargs):
"""Build a report of out-of-date or unresponsive mobile devices.
Finds the newest OS version and looks for devices which are out
of date. (Builds a histogram of installed OS versions).
Also, compiles a list of computers which have not checked in for
'check_in_period' days.
Finally, does a report on the hardware models present.
Args:
check_in_period: Integer number of days since last check-in to
include in report. Defaults to 30.
Returns:
A Report object.
"""
# All report functions support kwargs to support a unified interface,
# even if they don't use them.
_ = kwargs
jss_connection = JSSConnection.get()
mobile_devices = jss_connection.MobileDevice(
["general", "mobile_device_groups", "mobiledevicegroups"]
).retrieve_all()
if mobile_devices:
report = build_device_report(check_in_period, mobile_devices)
report.heading = "Mobile Device Report"
else:
report = Report("MobileDevice", [], "Mobile Device Report", {})
return report
def validate_check_in_period(check_in_period):
"""Ensure check_in_period argument is correct.
Args:
check_in_period: Number of days to consider out of date.
Returns:
A valid int check-in-period number of days.
"""
if not check_in_period:
check_in_period = 30
if not isinstance(check_in_period, int):
try:
check_in_period = int(check_in_period)
except ValueError:
print("Incorrect check-in period given. Setting to 30.")
check_in_period = 30
return check_in_period
def hour_pad(datetime_string):
"""Fix time strings' zero padding.
JAMF's dates don't always properly zero pad the hour. Do so.
Args:
datetime_string: A time string as referenced in MobileDevice's
last_inventory_time field.
Returns:
The string plus any zero padding required.
"""
# Example mobile device time format:
# Friday, August 07 2015 at 3:51 PM
# Monday, February 10 2014 at 8:42 AM<
components = datetime_string.split()
if len(components[5]) == 1:
components[5] = "0" + components[5]
return " ".join(components)
def build_packages_report(**kwargs):
"""Report on package usage.
Looks for packages which are not installed by any policies, patch policies or
computer configurations.
Returns:
A Report object.
"""
# All report functions support kwargs to support a unified interface,
# even if they don't use them.
_ = kwargs
jss_connection = JSSConnection.get()
all_policies = jss_connection.Policy(
["general", "package_configuration", "packages"]
).retrieve_all()
all_configs = jss_connection.ComputerConfiguration().retrieve_all()
all_packages = [(pkg.id, pkg.name) for pkg in jss_connection.Package()]
if not all_packages:
report = Report("Package", [], "Package Usage Report", {})
else:
policy_xpath = "package_configuration/packages/package"
# patch_policy_xpath = "package_configuration/packages/package"
config_xpath = "packages/package"
report = build_container_report(
[(all_policies, policy_xpath), (all_configs, config_xpath)], all_packages
)
report.get_result_by_name("Used").description = (
"All packages which are installed by policies or imaging " "configurations."
)
report.get_result_by_name("Unused").description = (
"All packages which are not installed by any policies or imaging "
"configurations."
)
report.heading = "Package Usage Report"
return report
def build_printers_report(**kwargs):
"""Report on printer usage.
Looks for printers which are not installed by any policies or
computer configurations.
Returns:
A Report object.
"""
# All report functions support kwargs to support a unified interface,
# even if they don't use them.
_ = kwargs
jss_connection = JSSConnection.get()
all_policies = jss_connection.Policy(["general", "printers"]).retrieve_all()
all_configs = jss_connection.ComputerConfiguration().retrieve_all()
all_printers = [(printer.id, printer.name) for printer in jss_connection.Printer()]
if not all_printers:
report = Report("Printer", [], "Printer Usage Report", {})
else:
policy_xpath = "printers/printer"
config_xpath = "printers/printer"
report = build_container_report(
[(all_policies, policy_xpath), (all_configs, config_xpath)], all_printers
)
report.get_result_by_name("Used").description = (
"All printers which are installed by policies or imaging " "configurations."
)
report.get_result_by_name("Unused").description = (
"All printers which are not installed by any policies or imaging "
"configurations."
)
report.heading = "Printer Usage Report"
return report
def build_scripts_report(**kwargs):
"""Report on script usage.
Looks for scripts which are not executed by any policies or
computer configurations.
Returns:
A Report object.
"""
# All report functions support kwargs to support a unified interface,
# even if they don't use them.
_ = kwargs
jss_connection = JSSConnection.get()
all_policies = jss_connection.Policy(["general", "scripts"]).retrieve_all()
all_configs = jss_connection.ComputerConfiguration().retrieve_all()
all_scripts = [(script.id, script.name) for script in jss_connection.Script()]
if not all_scripts:
report = Report("Script", [], "Script Usage Report", {})
else:
policy_xpath = "scripts/script"
config_xpath = "scripts/script"
report = build_container_report(
[(all_policies, policy_xpath), (all_configs, config_xpath)], all_scripts
)
report.get_result_by_name("Used").description = (
"All scripts which are installed by policies or imaging " "configurations."
)
report.get_result_by_name("Unused").description = (
"All scripts which are not installed by any policies or imaging "
"configurations."
)
report.heading = "Script Usage Report"
return report
def build_group_report(container_searches, groups_names, full_groups):
"""Report on group usage.
Looks for computer or mobile device groups with no members. This
does not mean they neccessarily are in-need-of-deletion.
Args:
container_searches: List of tuples to be passed to
build_container_report.
groups: List of (id, name) tuples for all groups on the JSS.
full_groups: List of full JSSObject data for groups.
Returns:
A Report object.
"""
# Build results for groups which aren't scoped.
report = build_container_report(container_searches, groups_names)
# Here we do more work, since Smart Groups can nest other groups.
# We want to remove any groups nested (at any level) within a group
# that is used.
# For convenience, pull out unused and used sets.
unused_groups = report.get_result_by_name("Unused").results
used_groups = report.get_result_by_name("Used").results
used_full_group_objects = get_full_groups_from_names(used_groups, full_groups)
full_used_nested_groups = get_nested_groups(used_full_group_objects, full_groups)
used_nested_groups = get_names_from_full_objects(full_used_nested_groups)
# Remove the nested groups from the unused list and add to the used.
unused_groups.difference_update(used_nested_groups)
# There's no harm in doing a union with the nested used groups vs.
# adding _just_ the ones removed from unused_groups.
used_groups.update(used_nested_groups)
# Recalculate cruftiness
unused_cruftiness = calculate_cruft(unused_groups, groups_names)
obj_type = device_type(full_groups)
report.metadata["Cruftiness"][
"Unscoped %s Cruftiness" % obj_type
] = get_cruft_strings(unused_cruftiness)
# Build Empty Groups Report.
empty_groups = get_empty_groups(full_groups)
report.results.append(empty_groups)
# Calculate empty cruftiness.
empty_cruftiness = calculate_cruft(empty_groups, groups_names)
report.metadata["Cruftiness"]["Empty Group Cruftiness"] = get_cruft_strings(
empty_cruftiness
)
# Build No Criteria Groups Report.
no_criteria_groups = get_no_criteria_groups(full_groups)
report.results.append(no_criteria_groups)
# Calculate empty cruftiness.
no_criteria_cruftiness = calculate_cruft(no_criteria_groups, groups_names)
report.metadata["Cruftiness"]["No Criteria Group Cruftiness"] = get_cruft_strings(
no_criteria_cruftiness
)
return report
def build_computer_groups_report(**kwargs):
"""Report on computer groups usage.
Looks for computer groups with no members. This does not mean
they neccessarily are in-need-of-deletion.
Returns:
A Report object.
"""
# All report functions support kwargs to support a unified interface,
# even if they don't use them.
_ = kwargs
jss_connection = JSSConnection.get()
group_list = jss_connection.ComputerGroup()
if not group_list:
return Report("ComputerGroup", [], "Computer Group Report", {})
all_computer_groups = [(group.id, group.name) for group in group_list]
full_groups = group_list.retrieve_all()
# all_policies = jss_connection.Policy().retrieve_all(
# subset=[])
all_policies = jss_connection.Policy(["general", "scope"]).retrieve_all()
# all_configs = jss_connection.OSXConfigurationProfile().retrieve_all(
# subset=["general", "scope"])
all_configs = jss_connection.OSXConfigurationProfile(
["general", "scope"]
).retrieve_all()
# Account for fix in python-jss that isn't yet part of a release.
if hasattr(jss_connection, "RestrictedSoftware"):
all_restricted_software = jss_connection.RestrictedSoftware().retrieve_all()
else:
all_restricted_software = jss_connection.RestrictedSfotware().retrieve_all()
scope_xpath = "scope/computer_groups/computer_group"
scope_exclusions_xpath = "scope/exclusions/computer_groups/computer_group"
# Build results for groups which aren't scoped.
report = build_group_report(
[
(all_policies, scope_xpath),
(all_policies, scope_exclusions_xpath),
(all_configs, scope_xpath),
(all_configs, scope_exclusions_xpath),
(all_restricted_software, scope_xpath),
(all_restricted_software, scope_exclusions_xpath),
],
all_computer_groups,
full_groups,
)
report.heading = "Computer Group Usage Report"
report.get_result_by_name("Used").description = (
"All groups which participate in scoping. Computer groups are "
"considered to be in-use if they are designated in the scope or the "
"exclusions of a policy or a configuration profile. This report "
"includes all groups which are nested inside of smart groups using "
"the 'member_of' criterion."
)
report.get_result_by_name("Unused").description = (
"All groups which do not participate in scoping. Computer groups are "
"considered to be in-use if they are designated in the scope or the "
"exclusions of a policy or a configuration profile. This report "
"includes all groups which are nested inside of smart groups using "
"the 'member_of' criterion."
)
return report
def build_computer_ea_report(**kwargs):
"""Report on computer extension attributes usage.
Looks for computer extension attributes not being used as criteria in any
smart groups or advanced searches. This does not mean they neccessarily are in-need-of-deletion.
Returns:
A Report object.
"""
# All report functions support kwargs to support a unified interface,
# even if they don't use them.
_ = kwargs
jss_connection = JSSConnection.get()
all_eas = [(ea.id, ea.name) for ea in jss_connection.ComputerExtensionAttribute()]
if not all_eas: