-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathscriptorium
executable file
·840 lines (770 loc) · 28.1 KB
/
scriptorium
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# scriptorium
# https://github.com/honestpuck/scriptorium
# software system for handling the scripts in Jamf Pro
# providing easy editing and a revision system
""" software system for handling scripts in Jamf Pro """
__program__ = "scriptorium"
__author__ = "Tony Williams"
__email__ = "tonyw@honestpuck.com"
__copyright__ = "Copyright (c) 2021 Tony Williams"
__license__ = "MIT"
__version__ = "1.0b2"
from pathlib import Path
import os
from sys import argv, stderr, stdout
import argparse
import plistlib
import xml.etree.ElementTree as ET
import logging.handlers
import requests
import subprocess
import difflib
import inquirer
import platform
from decouple import config
# from icecream import ic
home = str(Path.home()) # home directory path
cwd = Path.cwd() # current working directory
env = Path(".env") # environment file
# where we stash the XML files
xml_dir = f"{cwd}/config/xml"
# where we stash the text files
txt_dir = f"{cwd}/config/text"
# prefs file
if platform.system() == "Darwin":
prefs_file = Path(f"{home}/Library/Preferences/com.github.autopkg.stage.plist")
elif platform.system() == "linux" or platform.system() == "linux2":
prefs_file = Path(f"{cwd}/config/com.github.autopkg.stage.plist")
# TODO: fill out .env or plist programmatically with `else` block
def get_creds():
""" Get credentials from .env file or plist, if not found, check env variables """
try:
if env.exists():
API_PASSWORD = config("API_PASSWORD")
API_USERNAME = config("API_USERNAME")
JSS_URL = config("JSS_URL")
elif prefs_file.exists() and prefs_file.stat().st_size > 0:
plist = os.path.expanduser(prefs_file)
fp = open(plist, "rb")
prefs = plistlib.load(fp)
API_PASSWORD = prefs["API_PASSWORD"]
API_USERNAME = prefs["API_USERNAME"]
JSS_URL = prefs["JSS_URL"]
else:
API_PASSWORD = os.environ.get("API_PASSWORD")
API_USERNAME = os.getenv("API_USERNAME")
JSS_URL = os.getenv("JSS_URL")
except Exception as e:
print(f"Error: {e}")
logger.error(f"Error: {e}")
if not API_PASSWORD or not API_USERNAME or not JSS_URL:
print("Error: API_PASSWORD, API_USERNAME, or JSS_URL not found in .env, plist, or environment variables")
logger.error("Error: API_PASSWORD, API_USERNAME, or JSS_URL not found in .env, plist, or environment variables")
exit()
return API_USERNAME, API_PASSWORD, JSS_URL
def check_file_dir(path, type):
""" Check if file or directory exists then create if not """
try:
if type == "file" and not Path(path).is_file():
Path(path).touch()
logger.info(f"Created {path}")
elif type == "dir" and not Path(path).is_dir():
Path(path).mkdir(parents=True, exist_ok=True)
logger.info(f"Created {path}")
except (FileExistsError, NotADirectoryError):
logger.error(f"{path} already exists")
# template for use by add
template = """<?xml version="1.0" encoding="UTF-8"?>
<script>
<id>0</id>
<name>Garbage</name>
<category>End User Experience</category>
<filename>Garbage</filename>
<info/>
<notes/>
<priority>After</priority>
<parameters/>
<os_requirements/>
<script_contents>#!/bin/bash
</script_contents>
</script>
"""
LOGLEVEL = logging.DEBUG
logger = logging.getLogger(__program__)
# log and print routine
def info(msg):
print(msg)
logger.info(msg)
class Jamf:
"""Exists to carry some variables"""
def __init__(self):
self.scriptsURL = "" # URL for JPC scripts
self.catURL = "" # URL for JPC categories
self.auth = "" # name and password for JPC
self.hdrs = "" # header for requests, for JSON instead of XML
self.xml_dir = ""
self.txt_dir = ""
class Parser:
"""Parses the command line and runs the right function"""
def __init__(self):
"""build our command line parser"""
parser = argparse.ArgumentParser(
epilog="for command help: `scriptorium <command> -h`"
)
subparsers = parser.add_subparsers(description="", required=True)
#
# create parser for `add`
#
parser_add = subparsers.add_parser("add", help="add script to system")
parser_add.add_argument("-f", "--filename", help="name of new script")
parser_add.add_argument("-c", "--category", help="category of script")
parser_add.add_argument("-n", "--notes", help="notes about script")
group = parser_add.add_mutually_exclusive_group()
group.add_argument(
"-p",
"--push",
help="do a git push after commit",
action="store_true",
)
group.add_argument(
"-d",
"--dont-commit",
help="don't do a commit",
action="store_true",
)
parser_add.add_argument("-m", "--message", help="set commit message")
priority = parser_add.add_mutually_exclusive_group()
priority.add_argument(
"-a",
"--after",
help="run script with priority 'after'",
action="store_true",
)
priority.add_argument(
"-b",
"--before",
help="run script with priority 'before'",
action="store_true",
)
priority.add_argument(
"-r", "--reboot", help="run script at reboot", action="store_true"
)
parser_add.add_argument(
"-z",
"--zero",
help="zero parameters for script",
action="store_true",
)
parser_add.set_defaults(func=Scripts.do_add)
self.parser = parser
#
# create parser for `commit`
#
parser_commit = subparsers.add_parser("commit", help="git commit")
parser_commit.add_argument(
"-p",
"--push",
help="do a git push after commit",
action="store_true",
)
parser_commit.add_argument(
"-m",
"--message",
help="set commit message",
)
parser_commit.set_defaults(func=Scripts.do_commit)
#
# create parser for `delete`
#
parser_del = subparsers.add_parser(
"delete", help="delete a script from system"
)
parser_del.add_argument("name", help="name of script to remove")
group = parser_del.add_mutually_exclusive_group()
group.add_argument(
"-p",
"--push",
help="do a git push after commit",
action="store_true",
)
group.add_argument(
"-d",
"--dont-commit",
help="don't do a commit",
action="store_true",
)
parser_del.add_argument("-m", "--message", help="set commit message")
parser_del.set_defaults(func=Scripts.do_del)
#
# create parser for `down`
#
parser_down = subparsers.add_parser(
"down", help="downloads all scripts from the server"
)
parser_down.add_argument(
"-n",
"--no-force",
help="don't force overwrite of existing script or XML file",
action="store_true",
)
parser_down.add_argument(
"-s", "--script", help="specify a single script to check"
)
parser_down.add_argument(
"-p",
"--push",
help="do a git push after commit",
action="store_true",
)
parser_down.add_argument(
"-m",
"--message",
help="set commit message",
)
parser_down.set_defaults(func=Scripts.do_down)
#
# creeate parser for `git`
#
parser_git = subparsers.add_parser(
"git", help="asks for a string and runs it as a git command"
)
parser_git.add_argument(
"-c", "--command", help="quoted string containing git command"
)
parser_git.set_defaults(func=Scripts.do_git)
#
# create parser for `list`
#
parser_ls = subparsers.add_parser(
"list", help="lists all scripts on the server"
)
parser_ls.set_defaults(func=Scripts.do_list)
#
# create parser for `push`
#
parser_push = subparsers.add_parser("push", help="git push")
parser_push.set_defaults(func=Scripts.do_push)
#
# create parser for `rename`
#
parser_re = subparsers.add_parser("rename", help="rename a script")
group = parser_re.add_mutually_exclusive_group()
group.add_argument(
"-p",
"--push",
help="do a git push after commit",
action="store_true",
)
group.add_argument(
"-d",
"--dont-commit",
help="don't do a commit",
action="store_true",
)
parser_re.add_argument("-m", "--message", help="set commit message")
parser_re.add_argument("src", help="current name of script")
parser_re.add_argument("dst", help="new name of script")
parser_re.set_defaults(func=Scripts.do_rename)
#
# create parser for 'up'
#
parser_up = subparsers.add_parser("up", help="upload changed scripts")
parser_up.set_defaults(func=Scripts.do_up)
#
# create parser for `verify`
#
parser_ver = subparsers.add_parser(
"verify", help="verify text against XML against Jamf server"
)
parser_ver.add_argument(
"-d",
"--diff",
help="print diff when checking every script",
action="store_true",
)
parser_ver.add_argument(
"-q",
"--quick",
help="Just check lists not actual text",
action="store_true",
)
parser_ver.add_argument(
"-s", "--script", help="specify a single script to check"
)
parser_ver.set_defaults(func=Scripts.do_verify)
class ScriptError(Exception):
def __init__(self, message):
print(f"scriptorium: error: {message}", file=stderr)
logger.error(f"scriptorium: error: {message}")
exit(1)
class Scripts:
"""doing all the work"""
def setup_logging():
"""Defines a nicely formatted logger"""
log_dir = Path(f"{home}/Library/Logs")
check_file_dir(log_dir, "dir")
LOGFILE = log_dir / f"{__program__}.log"
ch = logging.handlers.TimedRotatingFileHandler(
LOGFILE, when="D", interval=1, backupCount=7
)
ch.setFormatter(
logging.Formatter(
"%(asctime)s %(levelname)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
)
logger.addHandler(ch)
logger.setLevel(LOGLEVEL)
def both_repos(args, jpc, command, sh=False):
"""do a shell command in each of our two directories"""
complete = subprocess.run(
command, text=True, shell=sh, cwd=jpc.txt_dir
)
if complete.returncode != 0:
# git can print a heap of output so give our user just the first 5 lines
out = f"{complete.stderr}{complete.stdout}"
lines = out.split("\n")
for i in lines[0:5]:
print(i)
raise ScriptError(f"text directory failed: {command}")
if complete.stderr:
print("Text")
print(" ".join(command))
info(complete.stderr)
complete = subprocess.run(
command, text=True, shell=sh, cwd=jpc.xml_dir
)
if complete.returncode != 0:
# git can print a heap so give our user just the first 5 lines
out = f"{complete.stderr}{complete.stdout}"
lines = out.split("\n")
for i in lines[0:5]:
print(i)
raise ScriptError(f"XML directory failed: {command}")
if complete.stderr:
print("XML")
print(" ".join(command))
info(complete.stderr)
def do_add(args, jpc):
"""add in all three spots"""
filename = args.filename if args.filename else input("Filename: ")
notes = args.notes if args.notes else input("Notes: ")
if not args.zero:
prompts = []
prompt = "a"
count = 4
while prompt:
prompt = input(f"Prompt {count}: ")
if prompt:
prompts.append(prompt)
count += 1
if count > 11:
break
# build list of categories
choices = []
ret = requests.get(jpc.catURL, headers=jpc.hdrs, auth=jpc.auth)
if ret.status_code != 200:
raise ScriptError(
f"failed to read categories: {ret.status_code}: {jpc.catURL}"
)
for category in ret.json()["categories"]:
choices.append(category["name"])
questions = [
inquirer.List(
"category",
message="Category (up and down to choose, return to select) ",
choices=choices,
)
]
answer = inquirer.prompt(questions)
category = answer["category"]
if not (args.after or args.before or args.reboot):
# we haven't specified a priority
questions = [
inquirer.List(
"priority",
message="Priority: after, before or at reboot",
choices=["After", "Before", "Reboot"],
)
]
answer = inquirer.prompt(questions)
priority = answer["priority"]
elif args.after:
priority = "After"
elif args.before:
priority = "Before"
elif args.reboot:
priority = "Reboot"
else:
raise ScriptError("Bad priority in Add")
root = ET.fromstring(template)
root.find("id").text = "0"
root.find("filename").text = filename
root.find("name").text = filename
root.find("category").text = category
root.find("script_contents").text = f"# {filename}"
root.find("notes").text = notes
root.find("priority").text = priority
params = root.find("parameters")
if not args.zero:
count = 4
for p in prompts:
ET.SubElement(params, f"parameter{count}").text = p
count += 1
# we should now have a nice XML tree.
data = ET.tostring(root)
url = f"{jpc.scriptsURL}/id/0"
ret = requests.post(url, auth=jpc.auth, data=data)
if ret.status_code != 201:
raise ScriptError(
f"failed to write to JPC: {ret.status_code}: {url}"
)
root = ET.fromstring(ret.text)
idn = root.find("id").text
ret = requests.get(f"{jpc.scriptsURL}/id/{idn}", auth=jpc.auth)
if ret.status_code != 200:
raise ScriptError(
f"script get failed: {ret.status_code} : {ret.url}"
)
root = ET.fromstring(ret.text)
ET.indent(root)
xml = ET.tostring(root)
xml_filepath = jpc.xml_dir / filename
sh_filepath = jpc.txt_dir / filename
with xml_filepath.open(mode="w") as fp:
fp.write(xml.decode())
with sh_filepath.open(mode="w") as fp:
fp.write(f"# {filename}")
args.message = f"adding {filename}"
if args.dont_commit:
exit()
Scripts.do_commit(args, jpc)
def do_commit(args, jpc):
"""
do a git commit
this commit, and optionally a push, on both directories
"""
lst = Scripts.do_up(args, jpc)
command = ["git", "add", "*"]
Scripts.both_repos(args, jpc, command)
msg = args.message if args.message else lst
command = ["git", "commit", "-m", msg]
Scripts.both_repos(args, jpc, command)
if args.push:
command = ["git", "push"]
Scripts.both_repos(args, jpc, command)
def do_down(args, jpc):
"""subcommand `down`"""
logger.info(" ".join(argv[1:]))
ret = requests.get(jpc.scriptsURL, auth=jpc.auth, headers=jpc.hdrs)
if ret.status_code != 200:
raise ScriptError(f"list get failed with error: {ret.status_code}")
for script in ret.json()["scripts"]:
idn = script["id"]
name = script["name"]
if args.script and name != args.script:
continue
if "/" in name:
print(f"Illegal character '/' in script {name}:{idn}")
continue
# we want XML so don't use the header
ret = requests.get(f"{jpc.scriptsURL}/id/{idn}", auth=jpc.auth)
if ret.status_code != 200:
raise ScriptError(
f"script get failed: {ret.status_code} : {ret.url}"
)
root = ET.fromstring(ret.text)
ET.indent(root)
text = root.findtext("script_contents")
ET.indent(root)
xml = ET.tostring(root)
xml_filepath = Path(f"{jpc.xml_dir}/{name}")
sh_filepath = Path(f"{jpc.txt_dir}/{name}")
if not args.no_force or not xml_filepath.is_file():
info(f"Writing XML {name}")
with xml_filepath.open(mode="w") as fp:
fp.write(xml.decode())
if not args.no_force or not sh_filepath.is_file():
info(f"Writing script {name}")
with sh_filepath.open(mode="w") as fp:
fp.write(text)
exit()
def do_git(args, jpc):
"""subcommand `git`"""
if args.command:
string = args.command
else:
string = input("Command for git: ")
command = f"git {string}".split(" ")
logger.info(f"Git command: {command}")
Scripts.both_repos(args, jpc, command)
exit()
def do_list(args, jpc):
"""subcommand `list`"""
logger.info("list command")
# JSON is easier to deal with so use the header
ret = requests.get(jpc.scriptsURL, auth=jpc.auth, headers=jpc.hdrs)
if ret.status_code != 200:
raise ScriptError(f"list get failed with error: {ret.status_code}")
for script in ret.json()["scripts"]:
idn = script["id"]
name = script["name"]
print(f"{idn}:\t{name}")
logger.info("list succeeded")
exit()
def do_push(args, jpc):
command = ["git", "push"]
Scripts.both_repos(args, jpc, command)
def do_del(args, jpc):
"""subcommand `delete`"""
logger.info(" ".join(argv[1:]))
xml_filepath = jpc.xml_dir / args.name
x = xml_filepath.read_text()
root = ET.fromstring(x)
idn = root.findtext("id")
data = ET.tostring(root)
url = f"{jpc.scriptsURL}/id/{idn}"
ret = requests.delete(url, auth=jpc.auth, data=data)
if ret.status_code != 200:
raise ScriptError(
f"failed to delete to JPC: {ret.status_code}: {url}"
)
f = Path(args.name)
command = ["git", "rm", f]
Scripts.both_repos(args, jpc, command, sh=False)
if args.dont_commit:
exit()
args.message = f"remove {args.name}"
Scripts.do_commit(args, jpc)
exit()
def do_rename(args, jpc):
"""subcommand `rename`"""
logger.info(" ".join(argv[1:]))
xml_filepath = jpc.xml_dir / args.src
x = xml_filepath.read_text()
root = ET.fromstring(x)
idn = root.findtext("id")
root.find("name").text = args.dst
root.find("script_contents_encoded").text = ""
ET.indent(root)
data = ET.tostring(root)
with xml_filepath.open(mode="w") as fp:
fp.write(str(data))
url = f"{jpc.scriptsURL}/id/{idn}"
ret = requests.put(url, auth=jpc.auth, data=data)
if ret.status_code != 201:
raise ScriptError(
f"failed to write to JPC: {ret.status_code}: {url}"
)
command = ["git", "mv", Path(args.src), Path(args.dst)]
Scripts.both_repos(args, jpc, command)
if args.dont_commit:
exit()
args.message = f"{args.src} to {args.dst}"
Scripts.do_commit(args, jpc)
logger.info("remove succeeded")
exit()
def do_up(args, jpc):
"""subcommand `up`"""
logger.info(" ".join(argv[1:]))
# then see if we do have scripts to be done
command = ["git", "diff", "--name-only", "-z"]
complete = subprocess.run(
command, text=True, capture_output=True, cwd=jpc.txt_dir
)
if complete.returncode != 0:
# git diff prints a heap so give our user just the first 5 lines
lines = complete.stderr.split("\n")
for i in lines[0:5]:
print(i)
raise ScriptError("git diff in scripts directory failed")
if complete.stdout == "":
return "empty"
# we have work to do
# git diff --name-only -z gives us a list of
# the changed files with a null after each so ...
files = complete.stdout.split("\0")
for fn in files:
if fn == "":
continue
info(f"Processing {fn}")
# first get our script
txt_file = jpc.txt_dir / fn
scrpt = txt_file.read_text()
x_file = jpc.xml_dir / fn
xml = x_file.read_text()
root = ET.fromstring(xml)
root.find("script_contents").text = scrpt
# blank the encoded field as you can't have both in an upload
root.find("script_contents_encoded").text = ""
idn = root.findtext("id")
ET.indent(root)
data = ET.tostring(root)
url = f"{jpc.scriptsURL}/id/{idn}"
ret = requests.put(url, auth=jpc.auth, data=data)
if ret.status_code != 201:
print(f"failed to write to JPC: {ret.status_code}: {url}")
logger.debug(
f"failed to write to JPC: {ret.status_code}: {url}"
)
exit(1)
# since Jamf will give us <script_encoded> get our record again
# so a verify will be identical
ret = requests.get(url, auth=jpc.auth)
xml = ret.text
root = ET.fromstring(xml)
ET.indent(root)
xml = ET.tostring(root)
x_file.write_text(xml.decode())
return " ".join(files)
def do_verify(args, jpc):
"""verify scripts, XML and server against each other"""
# get list of script files
print("Lists:")
command = ["ls"]
complete = subprocess.run(
command, text=True, capture_output=True, cwd=jpc.txt_dir
)
sh = complete.stdout.splitlines()
complete = subprocess.run(
command, text=True, capture_output=True, cwd=jpc.xml_dir
)
xml = complete.stdout.splitlines()
ret = requests.get(jpc.scriptsURL, auth=jpc.auth, headers=jpc.hdrs)
if ret.status_code != 200:
raise ScriptError(f"list get failed with error: {ret.status_code}")
# scripts on server
scripts = []
for script in ret.json()["scripts"]:
scripts.append(script["name"])
# good for lists
d = difflib.Differ()
# first compare
result = list(d.compare(xml, sh))
out = []
# print only changes
for line in result:
if line[0] != " ":
out.append(line)
if out:
print("XML > text")
for line in out:
print(line)
else:
print("XML = text")
# it's likely that the OS sort of an `ls` will be different
# to the Jamf Pro server sort so use the Python sort on both
xml.sort()
scripts.sort()
result = list(d.compare(xml, scripts))
out = []
# print only changes
for line in result:
if line[0] != " ":
out.append(line)
if out:
print("XML > Jamf")
for line in out:
print(line)
else:
print("XML = Jamf")
if args.quick:
exit()
# main loop
for script in ret.json()["scripts"]:
name = script["name"]
if args.script and name != args.script:
continue
print("*", end="")
# info(f"Verifying {name}")
stdout.flush()
idn = script["id"]
xml_filepath = jpc.xml_dir / name
sh_filepath = jpc.txt_dir / name
xml = xml_filepath.read_text()
text = sh_filepath.read_text()
text = text.splitlines()
root = ET.fromstring(xml)
# removing encoded as it will only vary if contents vary
root.find("script_contents_encoded").text = ""
xml_text = root.findtext("script_contents")
xml_text = xml_text.splitlines()
xml = ET.tostring(root)
xml = xml.decode()
xml = xml.splitlines()
result = list(d.compare(xml_text, text))
out = []
# print only changes
for line in result:
if line[0] != " ":
out.append(line)
if out:
print(f"\n{name}: XML > text")
if args.diff:
for line in out:
print(line)
elif args.script:
print(f"\n{name}: XML = text")
ret = requests.get(f"{jpc.scriptsURL}/id/{idn}", auth=jpc.auth)
if ret.status_code != 200:
raise ScriptError(
f"get script {name} failed with error: {ret.status_code}"
)
root = ET.fromstring(ret.text)
# removing encoded as it will only vary if contents vary
root.find("script_contents_encoded").text = ""
ET.indent(root)
jamf = ET.tostring(root)
jamf = jamf.decode()
jamf = jamf.splitlines()
result = list(d.compare(xml, jamf))
out = []
# print only changes
for line in result:
if line[0] != " ":
out.append(line)
if out:
print(f"\n{name}: XML > Jamf")
if args.diff:
for line in out:
print(line)
elif args.script:
print(f"\n{name}: XML = Jamf")
exit()
def main():
Scripts.setup_logging()
logger.info("Start")
# sanity check (pre-flight)
API_USERNAME, API_PASSWORD, JSS_URL = get_creds()
# init
jpc = Jamf()
# sanity check (post-flight)
check_file_dir(xml_dir, "dir")
check_file_dir(txt_dir, "dir")
# check_file_dir(prefs_file, "file") # will create an empty file
jpc.xml_dir = Path(xml_dir).expanduser()
jpc.txt_dir = Path(txt_dir).expanduser()
# we only operate on scripts so create a URL for the endpoint
jpc.scriptsURL = f"{JSS_URL}/JSSResource/scripts"
# we get a list of categories for `add` so another endpoint
jpc.catURL = f"{JSS_URL}/JSSResource/categories"
# for the whole list JSON is handier so
jpc.hdrs = {"Accept": "application/json"}
jpc.auth = API_USERNAME, API_PASSWORD
logger.debug("Prefs loaded")
fred = Parser() # I just love Fred, he does all the dirty work
# handle no arguments on command line, fred doesn't do this well
if len(argv) == 1:
print("Missing subcommand")
fred.parser.print_help()
exit(1)
args = fred.parser.parse_args()
# we never return from below call
if args:
args.func(args, jpc)
else:
exit()
if __name__ == "__main__":
Scripts.main()