This repository has been archived by the owner on Jun 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBananaEndocarp.py
executable file
·228 lines (189 loc) · 6.8 KB
/
BananaEndocarp.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
BananaEndocarp
BananaEndocarp is a GUI built using nibbler for interacting with mwa2's api.
It was designed to work in a limited environment such as an NetInstall
environment. It connects to a mwa2 instance utilizing the API to create
a manifest per machine based off of the serial number.
Author: Clayton Burlison <https://clburlison.com>
Last modified: Sept 8, 2016
Version: 2.2
Referenced code:
https://github.com/pudquick/nibbler
https://github.com/typesupply/vanilla/blob/master/Lib/vanilla/vanillaPopUpButton.py
https://github.com/typesupply/vanilla/blob/master/Lib/vanilla/vanillaCheckBox.py
'''
import os
import urllib2
import json
import subprocess
from nibbler import *
# Included manifests
included_manifests_options = [
"manifest A",
"manifest B",
"manifest C",
]
# Your mwa2 URL
mwa2_url = "http://localhost:8000"
# Authorization key for mwa2 API. Create this string via:
# python -c 'import base64; print "Authorization: Basic %s" % base64.b64encode("username:password")'
# Make sure and only paste the "Basic STRINGVALUE"
authorization = "Basic ABBAABAABAABBAAB"
# Default munki catalog
default_catalog = "production"
# You should rarely use the following...AKA: almost never!
default_managed_installs = []
default_managed_uninstalls = []
default_managed_updates = []
default_optional_installs = []
# When set to True, always override repo manifest with values from GUI prompt.
# DEFAULT value for always_override = False
always_override = False
################
# No variables below this point
################
try:
script_path = os.path.dirname(os.path.realpath(__file__))
n = Nibbler(os.path.join(script_path, 'BananaEndocarp.nib'))
except IOError, ImportError:
print "Unable to load nib!"
exit(20)
def showMsg(message):
"""
Show feedback to our label field.
"""
feedback = n.views['feedback_result']
feedback.setStringValue_(message)
def getSerialNumber():
"""
Returns the serial number of the Mac.
"""
cmd = "/usr/sbin/ioreg -c \"IOPlatformExpertDevice\" | awk -F '\"' \
'/IOPlatformSerialNumber/ {print $4}'"
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(out, err) = proc.communicate()
return out.strip()
def setItems(items):
"""
Function to set items to appear in the drop down menu.
"""
menu = n.views['manifest_input']
menu.removeAllItems()
for item in items:
menu.addItemWithTitle_(item)
def getItem():
"""
Return the manifest value from our selected drop down menu item.
"""
index = n.views['manifest_input'].indexOfSelectedItem()
values = n.views['manifest_input'].itemTitles()
return values[index]
def exitScript():
"""
Exit BananaEndocarp.
"""
print "Goodbye!"
n.quit()
def apiCaller(url, machine_serial, method='GET', data=None):
"""
Function to make requests to the api end point.
"""
request = urllib2.Request(url,
headers={
"Authorization": authorization,
"Content-Type": "application/json"
}, data=json.dumps(data))
request.get_method = lambda: method
try:
f = urllib2.urlopen(request)
contents = f.read()
code = f.getcode()
return (code, contents)
except urllib2.HTTPError as e:
return (e.code, e.read())
except urllib2.URLError as e:
return e
def apiHandler():
"""
Function to process api calls and return feedback to the user.
"""
username = n.views['username_input'].stringValue()
hostname = n.views['hostname_input'].stringValue()
# Get the current manifest selection
manifest = getItem()
# Print values
print manifest
print username
print hostname
machine_serial = getSerialNumber()
url = "{0}{1}{2}".format(mwa2_url, '/api/manifests/', machine_serial)
print url
data = {"catalogs": [default_catalog],
"display_name": hostname,
"included_manifests": [manifest],
"managed_installs": default_managed_installs,
"managed_uninstalls": default_managed_uninstalls,
"managed_updates": default_managed_updates,
"optional_installs": default_optional_installs,
"user": username
}
# Run our api caller on a loop so we can handle errors,
# typos, and modifications.
loop_handler = True
x = 1
while loop_handler:
print "We're on api loop {0}".format(x)
x += 1
no_mod = " \n\nNo modifications have been made."
get_request = apiCaller(url, machine_serial)
print "API call status code: {0}".format(get_request[0])
if get_request[0] == 200: # manifest already exists
checkbox = n.views['override_checkbox'].state()
print "checkbox state is {0}".format(checkbox)
if checkbox == 1:
delete_request = apiCaller(url, machine_serial, 'DELETE')
if delete_request[0] == 204:
showMsg("SUCESS: A manifest was deleted")
else:
print delete_request
showMsg("ERROR: An error occurred while deleting the"
"previous manifest.{0}".format(no_mod))
else:
showMsg("WARNING: A manifest was already found for"
"this machine.{0}".format(no_mod))
loop_handler = False
elif get_request[0] == 401: # unauthorized attempt
showMsg("ERROR: An unauthorized attempt to make modifications."
"Please verify your API key.{0}".format(no_mod))
loop_handler = False
elif get_request[0] == 404: # manifest does not exist
post_request = apiCaller(url, machine_serial, 'POST', data)
if post_request[0] == 201:
showMsg("SUCESS: A manifest was created")
else:
showMsg("ERROR: {0} \n {1}{2}".format(get_request[0],
"Unable to create our manifest", no_mod))
loop_handler = False
else:
showMsg("ERROR: {0}{1}".format(get_request[0], no_mod))
loop_handler = False
def main():
"""
Main method to handle setting GUI properties and attaching buttons.
"""
n.attach(apiHandler, 'continueButton')
n.attach(exitScript, 'exitButton')
# Debug statements
# print n.nib_contents
# print n.views
# Set values for drop down menu
setItems(included_manifests_options)
# Set default override state for the checkbox
n.views['override_checkbox'].setState_(always_override)
n.hidden = False
n.run()
if __name__ == '__main__':
main()