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
|
import sys import os import optparse import subprocess import re from uuid import uuid4 from Foundation import NSData, \ NSDate, \ NSPropertyListSerialization, \ NSPropertyListMutableContainers, \ NSPropertyListXMLFormat_v1_0, \ CFPreferencesCopyKeyList, \ CFPreferencesCopyMultiple, \ kCFPreferencesCurrentUser, \ kCFPreferencesAnyUser, \ kCFPreferencesCurrentHost, \ kCFPreferencesAnyHost, \ kCFPreferencesCurrentApplication, \ kCFPreferencesAnyApplication
class PayloadDict: """Class to create and manipulate Configuration Profiles. The actual plist content can be accessed as a dictionary via the 'data' attribute. """ def __init__(self, identifier, uuid=False, removal_allowed=False, organization='', displayname=''): self.data = {} self.data['PayloadVersion'] = 1 self.data['PayloadOrganization'] = organization if uuid: self.data['PayloadUUID'] = uuid else: self.data['PayloadUUID'] = makeNewUUID() if removal_allowed: self.data['PayloadRemovalDisallowed'] = False else: self.data['PayloadRemovalDisallowed'] = True self.data['PayloadType'] = 'Configuration' self.data['PayloadScope'] = 'System' self.data['PayloadDescription'] = "Included custom settings:\n" self.data['PayloadDisplayName'] = displayname self.data['PayloadIdentifier'] = identifier
self.gitrev = None root_dir = os.path.abspath(os.path.dirname(sys.argv[0])) if '.git' in os.listdir(root_dir): git_p = subprocess.Popen('git rev-parse HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=root_dir) out, err = git_p.communicate() if not git_p.returncode: self.gitrev = out.strip()
self.data['PayloadContent'] = []
def _addPayload(self, payload_content_dict): """Add a Custom Settings payload to the profile. Takes a dict which will be the PayloadContent dict within the payload. Handles the boilerplate, naming and descriptive elements. """ domains = payload_content_dict.keys() if len(domains) == 1: domain = domains[0] self.data['PayloadDescription'] += "%s\n" % domain else: domain = 'multiple preference domains' self.data['PayloadDescription'] += '\n'.join(domains)
payload_dict = {} payload_dict['PayloadVersion'] = 1 payload_dict['PayloadUUID'] = makeNewUUID() payload_dict['PayloadEnabled'] = True payload_dict['PayloadType'] = 'com.apple.ManagedClient.preferences' payload_dict['PayloadIdentifier'] = "%s.%s.alacarte.customsettings.%s" % ( 'MCXToProfile', self.data['PayloadUUID'], payload_dict['PayloadUUID'])
if self.data['PayloadDisplayName'] == '': self.data['PayloadDisplayName'] = 'MCXToProfile: %s' % domain
payload_dict['PayloadContent'] = payload_content_dict
self.data['PayloadContent'].append(payload_dict)
def addPayloadFromPlistContents(self, plist_dict, domain, manage, is_byhost=False): """Add one plist dict contents to the profile's payloads. domain is the preferences domain (ie. com.apple.finder), manage is one of 'Once', 'Often' or 'Always', and is_byhost is a boolean representing whether the preference is to be used as a ByHost. """
payload_dict = {}
if manage == 'Always': state = 'Forced' else: state = 'Set-Once'
if is_byhost: domain += '.ByHost'
payload_dict[domain] = {} payload_dict[domain][state] = [] payload_dict[domain][state].append({}) payload_dict[domain][state][0]['mcx_preference_settings'] = plist_dict
if manage == 'Once': now = NSDate.new() payload_dict[domain][state][0]['mcx_data_timestamp'] = now
self._addPayload(payload_dict)
def addPayloadFromMCX(self, mcxdata): """Add MCX data to the profile's payloads. """ self._addPayload(mcxdata)
def finalizeAndSave(self, output_path): """Perform last modifications and save to an output plist. """ if self.gitrev: self.data['PayloadDescription'] += "\nGit revision: %s" % self.gitrev[0:10] writePlist(self.data, output_path)
def makeNewUUID(): return str(uuid4())
def errorAndExit(errmsg): print >> sys.stderr, errmsg exit(-1)
"""FoundationPlist.py -- a tool to generate and parse MacOSX .plist files.
This is intended as a drop-in replacement for Python's included plistlib, with a few caveats: - readPlist() and writePlist() operate only on a filepath, not a file object. - there is no support for the deprecated functions: readPlistFromResource() writePlistToResource() - there is no support for the deprecated Plist class.
The Property List (.plist) file format is a simple XML pickle supporting basic object types, like dictionaries, lists, numbers and strings. Usually the top level object is a dictionary.
To write out a plist file, use the writePlist(rootObject, filepath) function. 'rootObject' is the top level object, 'filepath' is a filename.
To parse a plist from a file, use the readPlist(filepath) function, with a file name. It returns the top level object (again, usually a dictionary).
To work with plist data in strings, you can use readPlistFromString() and writePlistToString(). """
class FoundationPlistException(Exception): pass
class NSPropertyListSerializationException(FoundationPlistException): pass
class NSPropertyListWriteException(FoundationPlistException): pass
def readPlist(filepath): """ Read a .plist file from filepath. Return the unpacked root object (which is usually a dictionary). """ plistData = NSData.dataWithContentsOfFile_(filepath) dataObject, plistFormat, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None) if error: error = error.encode('ascii', 'ignore') errmsg = "%s in file %s" % (error, filepath) raise NSPropertyListSerializationException(errmsg) else: return dataObject
def readPlistFromString(data): '''Read a plist data from a string. Return the root object.''' plistData = buffer(data) dataObject, plistFormat, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plistData, NSPropertyListMutableContainers, None, None) if error: error = error.encode('ascii', 'ignore') raise NSPropertyListSerializationException(error) else: return dataObject
def writePlist(dataObject, filepath): ''' Write 'rootObject' as a plist to filepath. ''' plistData, error = \ NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_( dataObject, NSPropertyListXMLFormat_v1_0, None) if error: error = error.encode('ascii', 'ignore') raise NSPropertyListSerializationException(error) else: if plistData.writeToFile_atomically_(filepath, True): return else: raise NSPropertyListWriteException( "Failed to write plist data to %s" % filepath)
def getDomainFromPlist(plist_path_or_name): """Assuming the domain is also the name of the plist file, strip the path and the ending '.plist'""" domain_info = {} domain_info['is_byhost'] = False
byhost_pattern = re.compile('.ByHost$|.[0-9a-fA-F]{12}$|.[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')
plist_file_name = os.path.basename(plist_path_or_name).split('.plist')[0] byhost_match = re.search(byhost_pattern, plist_file_name) if byhost_match: domain_info['is_byhost'] = True domain_info['name'] = '.'.join(plist_file_name.split('.')[0:-1]) else: domain_info['name'] = plist_file_name
return domain_info
def getMCXData(ds_object): '''Returns a dictionary representation of dsAttrTypeStandard:MCXSettings from the given DirectoryServices object. This is an array of dicts.''' ds_object_parts = ds_object.split('/') ds_node = '/'.join(ds_object_parts[0:3]) ds_object_path = '/' + '/'.join(ds_object_parts[3:]) cmd = ['/usr/bin/dscl', '-plist', ds_node, 'read', ds_object_path, 'dsAttrTypeStandard:MCXSettings'] proc = subprocess.Popen(cmd, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (pliststr, err) = proc.communicate() if proc.returncode: errorAndExit("dscl error: %s" % err)
try: mcx_dict = readPlistFromString(pliststr) except FoundationPlistException: errorAndExit( "Could not decode plist data from dscl:\n" % pliststr)
try: mcx_data_plist = mcx_dict['dsAttrTypeStandard:MCXSettings'] except KeyError: errorAndExit("No mcx_settings in %s:\n%s" % (ds_object, pliststr))
mcx_data = [] for mcx_item in mcx_data_plist: try: mcx_item = mcx_item.encode('UTF-8') mcx_item_data = readPlistFromString(str(mcx_item)) mcx_data.append(mcx_item_data['mcx_application_data']) except KeyError: errorAndExit( "Unexpected mcx_settings format in MCXSettings array item:\n%s" % mcx_item)
return mcx_data
def getDefaultsData(app_id, current_host, any_user): '''Returns the content of the defaults domain as an array or dict obejct.'''
if app_id == "NSGlobalDomain": app_id = kCFPreferencesAnyApplication
if current_host: host_domain = kCFPreferencesCurrentHost else: host_domain = kCFPreferencesAnyHost
if any_user: user_domain = kCFPreferencesAnyUser else: user_domain = kCFPreferencesCurrentUser
allKeys = CFPreferencesCopyKeyList(app_id, user_domain, host_domain) prefs_dict = CFPreferencesCopyMultiple(allKeys, app_id, user_domain, host_domain)
if len(prefs_dict) == 0: errorAndExit("Error: no values found for app id: %s" % app_id)
return prefs_dict
def getIdentifierFromProfile(profile_path): """Return a tuple containing the PayloadIdentifier and PayloadUUID from the profile at the path specified.""" profile_dict = readPlist(profile_path) try: profile_id = profile_dict['PayloadIdentifier'] profile_uuid = profile_dict['PayloadUUID'] except: errorAndExit("Can't find a ProfileIdentifier in the profile at %s." % profile_path) return (profile_id, profile_uuid)
def main(): parser = optparse.OptionParser() parser.set_usage( """usage: %prog [--dsobject DSOBJECT | --plist PLIST | --defaults DOMAIN] [--identifier IDENTIFIER | --identifier-from-profile PATH] [options] One of '--dsobject', '--plist', or '--defaults' must be specified, and only one identifier option. Run '%prog --help' for more information.""")
parser.add_option('--dsobject', '-d', metavar='DSOBJECT', help="""Directory Services object from which to convert MCX data. Examples: /Local/Default/Computers/foo /LDAPv3/some_ldap_server/ComputerGroups/bar""") parser.add_option('--plist', '-p', action="append", metavar='PLIST_FILE', help="""Path to a plist to be added as a profile payload. Can be specified multiple times.""") parser.add_option('--defaults', action="append", metavar='APP_ID', help="""Default or preferences application id to be added as profile payload. Can be specified multiple times. User NSGlobalDomain to designate the global or 'anyApp' domain.""") parser.add_option('--identifier', '-i', action="store", help="""Top-level payload identifier. This is used to uniquely identify a profile. A profile can be removed using this identifier using the 'profiles' command and the '-R -p' options.""") parser.add_option('--identifier-from-profile', '-f', action="store", metavar="PATH", help="""Path to an existing .mobileconfig file from which to copy the identifier and UUID, as opposed to specifying it with the --identifier option.""")
parser.add_option('--removal-allowed', '-r', action="store_true", default=False, help="""Specifies that the profile can be removed.""") parser.add_option('--organization', '-g', action="store", default="", help="Cosmetic name for the organization deploying the profile.") parser.add_option('--output', '-o', action="store", metavar='PATH', help="Output path for profile. Defaults to 'identifier.mobileconfig' in the current working directory.") parser.add_option('--displayname', action="store", default="", help="Display name for profile. Defaults to 'MCXToProfile: <first domain>'.")
plist_options = optparse.OptionGroup(parser, title="Plist-specific options", description="""These options are useful only in conjunction with --plist. If multiple plists are supplied, they are applied to all, not on a per-plist basis.""")
parser.add_option_group(plist_options)
plist_options.add_option('--manage', '-m', action="store", help=("Management frequency - 'Once' or 'Always'. Defaults to " "Always. 'Often' is also supported, but is not recommended " "due to its having undesirable effects on clients running " "Yosemite."))
defaults_options = optparse.OptionGroup(parser, title="Defaults-specific options", description="""These options are useful only in conjunction with --defaults. if multiple application ids are supplied they are applied to all.""" )
parser.add_option_group(defaults_options)
defaults_options.add_option('--currentHost', action="store_true", default=False, help="""When using the '--defaults' option this sets the '--currentHost' flag for the 'defaults' command.""" ) defaults_options.add_option('--anyUser', action="store_true", default=False, help="""When using the '--defaults' option this looks in the 'anyUser' domain, i.e. /Library/Preferences, rather than ~/Library/Preferences.""" )
options, args = parser.parse_args()
if len(args): parser.print_usage() sys.exit(-1)
number_of_options = int(bool(options.dsobject)) + int(bool(options.plist)) + int(bool(options.defaults)) if number_of_options > 1: parser.print_usage() errorAndExit("Error: The '--dsobject', '--plist', and '--defaults' options are mutually exclusive.")
if number_of_options == 0: parser.print_usage() errorAndExit("Error: One of '--dsobject' or '--plist' or '--defaults' must be specified.")
if options.dsobject and options.manage: print options.manage parser.print_usage() errorAndExit("Error: The '--manage' option is used only in conjunction with '--plist'. DS Objects already contain this information.")
if options.currentHost and not options.defaults: parser.print_usage() errorAndExit("Error: The '--currentHost' option is used only with '--defaults'.")
if options.anyUser and not options.defaults: parser.print_usage() errorAndExit("Error: The '--anyUser' option is used only with '--defaults'.")
if (not options.identifier and not options.identifier_from_profile) or \ (options.identifier and options.identifier_from_profile): parser.print_usage() errorAndExit("Error: identifier must be provided with either '--identifier' or '--identifier-from-profile'")
if options.identifier: identifier = options.identifier uuid = False elif options.identifier_from_profile: if not os.path.exists(options.identifier_from_profile): errorAndExit("Error reading a profile at path %s" % options.identifier_from_profile) identifier, uuid = getIdentifierFromProfile(options.identifier_from_profile)
if options.plist or options.defaults: if not options.manage: manage = 'Always' else: manage = options.manage.capitalize() else: manage = None if manage == 'Often': print >> sys.stderr, \ ("WARNING: Deploying profiles configured for 'Often' settings " "management is known to have undesirable effects on OS X " "Yosemite. \n" " Consider using 'Once' instead, and see this repo's " "README for links to more documentation.")
if options.output: output_file = options.output else: output_file = os.path.join(os.getcwd(), identifier + '.mobileconfig')
newPayload = PayloadDict(identifier=identifier, uuid=uuid, removal_allowed=options.removal_allowed, organization=options.organization, displayname=options.displayname)
if options.plist: for plist_path in options.plist: if not os.path.exists(plist_path): errorAndExit("No plist file exists at %s" % plist_path) try: source_data = readPlist(plist_path) except FoundationPlistException: errorAndExit("Error decoding plist data in file %s" % plist_path)
source_domain = getDomainFromPlist(plist_path) newPayload.addPayloadFromPlistContents(source_data, source_domain['name'], manage, is_byhost=source_domain['is_byhost']) if options.dsobject: mcx_data = getMCXData(options.dsobject) for mcx_domain in mcx_data: newPayload.addPayloadFromMCX(mcx_domain) if options.defaults: for defaults_domain in options.defaults: defaults_data = getDefaultsData(defaults_domain, options.currentHost, options.anyUser) isByHost = options.currentHost and not options.anyUser
newPayload.addPayloadFromPlistContents(defaults_data, defaults_domain, manage, isByHost)
newPayload.finalizeAndSave(output_file)
if __name__ == "__main__": main()
|