def getServerURL(): # Try the user's homedir try: NSLog("Trying Home Location") homedir = os.path.expanduser("~") plist = FoundationPlist.readPlist(os.path.join(homedir, "Library", "Preferences", "com.grahamgilbert.Imagr.plist")) return plist['serverurl'] except: pass # Try the main prefs try: NSLog("Trying System Location") plist = FoundationPlist.readPlist(os.path.join("/Library", "Preferences", "com.grahamgilbert.Imagr.plist")) return plist['serverurl'] except: pass # Hopefully we're in a netboot set, try in /System/Installation/Packages try: NSLog("Trying NetBoot Location") plist = FoundationPlist.readPlist(os.path.join("/System", "Installation", "Packages", "com.grahamgilbert.Imagr.plist")) return plist['serverurl'] except: pass
def main(): """Set up arguments and start processing.""" args = get_argument_parser().parse_args() autopkg_plist_path = "~/Library/Preferences/com.github.autopkg.plist" # Read preferences. if os.path.exists(os.path.expanduser(autopkg_plist_path)): try: autopkg_prefs = FoundationPlist.readPlist( os.path.expanduser(autopkg_plist_path)) if "MUNKI_REPO" in autopkg_prefs: MUNKI_REPO = autopkg_prefs["MUNKI_REPO"] else: print_error("No MUNKI_REPO key in AutoPkg preferences.") except FoundationPlist.NSPropertyListSerializationException as e: print_error("Error reading preferences: %s" % e) else: print_error("No file exists at %s." % autopkg_plist_path) production_cat = FoundationPlist.readPlist( os.path.join(MUNKI_REPO, "catalogs/%s" % args.catalog)) pkginfo_template = (get_pkginfo_template(args.pkginfo) if args.pkginfo else {}) recipes = args.recipes if args.recipes else get_recipes(args.recipe_list) try: process_overrides(recipes, args, production_cat, pkginfo_template) except KeyboardInterrupt: print_error("Bailing!") finally: reset_term_colors()
def getPlistData(data): # Try the user's homedir try: # NSLog("Trying Home Location") homedir = os.path.expanduser("~") plist = FoundationPlist.readPlist( os.path.join(homedir, "Library", "Preferences", "com.grahamgilbert.Imagr.plist")) return plist[data] except: pass # Try the main prefs try: # NSLog("Trying System Location") plist = FoundationPlist.readPlist( os.path.join("/Library", "Preferences", "com.grahamgilbert.Imagr.plist")) return plist[data] except: pass # Hopefully we're in a netboot set, try in /System/Installation/Packages try: # NSLog("Trying NetBoot Location") plist = FoundationPlist.readPlist( os.path.join("/System", "Installation", "Packages", "com.grahamgilbert.Imagr.plist")) return plist[data] except: pass
def getPlistData(data): # Try the user's homedir try: # NSLog("Trying Home Location") homedir = os.path.expanduser("~") plist = FoundationPlist.readPlist(os.path.join(homedir, "Library", "Preferences", "com.grahamgilbert.Imagr.plist")) return plist[data] except: pass # Try the main prefs try: # NSLog("Trying System Location") plist = FoundationPlist.readPlist(os.path.join("/Library", "Preferences", "com.grahamgilbert.Imagr.plist")) return plist[data] except: pass # Hopefully we're in a netboot set, try in /System/Installation/Packages try: # NSLog("Trying NetBoot Location") plist = FoundationPlist.readPlist(os.path.join("/System", "Installation", "Packages", "com.grahamgilbert.Imagr.plist")) return plist[data] except: pass # last chance; look for a file next to the app appPath = NSBundle.mainBundle().bundlePath() appDirPath = os.path.dirname(appPath) try: plistData = open(os.path.join(appDirPath, "com.grahamgilbert.Imagr.plist")).read() plistData = plistData.replace("{{current_volume_path}}", currentVolumePath()).encode("utf8") plist = FoundationPlist.readPlistFromString(plistData) return plist[data] except: pass
def main(): ard_path = "/Library/Preferences/com.apple.RemoteDesktop.plist" if os.path.exists(ard_path): ard_prefs = FoundationPlist.readPlist(ard_path) else: ard_prefs = {} sal_result_key = "ARD_Info_{}" prefs_key_prefix = "Text{}" data = { sal_result_key.format(i): ard_prefs.get(prefs_key_prefix.format(i), "") for i in xrange(1, 5) } formatted_results = { "plugin": "ARD_Info", "historical": False, "data": data } if os.path.exists(RESULTS_PATH): plugin_results = FoundationPlist.readPlist(RESULTS_PATH) else: plugin_results = [] plugin_results.append(formatted_results) FoundationPlist.writePlist(plugin_results, RESULTS_PATH)
def userSelfServiceChoicesChanged(): """Is WRITEABLE_SELF_SERVICE_MANIFEST_PATH different from the 'system' version of this file?""" if not os.path.exists(WRITEABLE_SELF_SERVICE_MANIFEST_PATH): return False user_choices = FoundationPlist.readPlist(WRITEABLE_SELF_SERVICE_MANIFEST_PATH) managedinstallbase = pref("ManagedInstallDir") system_path = os.path.join(managedinstallbase, "manifests", "SelfServeManifest") if not os.path.exists(system_path): return True system_choices = FoundationPlist.readPlist(system_path) return user_choices != system_choices
def userSelfServiceChoicesChanged(): '''Is WRITEABLE_SELF_SERVICE_MANIFEST_PATH different from the 'system' version of this file?''' if not os.path.exists(WRITEABLE_SELF_SERVICE_MANIFEST_PATH): return False user_choices = FoundationPlist.readPlist(WRITEABLE_SELF_SERVICE_MANIFEST_PATH) managedinstallbase = pref('ManagedInstallDir') system_path = os.path.join(managedinstallbase, "manifests", "SelfServeManifest") if not os.path.exists(system_path): return True system_choices = FoundationPlist.readPlist(system_path) return (user_choices != system_choices)
def availableUpdatesAreDownloaded(): '''Verifies that applicable/available Apple updates have been downloaded. Returns False if one or more product directories are missing, True otherwise (including when there are no available updates).''' appleUpdates = getSoftwareUpdateInfo() if not appleUpdates: return True try: downloadIndex = FoundationPlist.readPlist( '/Library/Updates/index.plist') downloaded = downloadIndex.get('ProductPaths', []) except FoundationPlist.FoundationPlistException: munkicommon.log('Apple downloaded update index is invalid. ' '/Library/Updates/index.plist') return False for update in appleUpdates: productKey = update.get('productKey') if productKey: if (productKey not in downloaded or not os.path.isdir( os.path.join('/Library/Updates', downloaded[productKey]))): munkicommon.log('Apple Update product directory for %s is ' 'missing.' % update['name']) return False return True
def get_pkginfo_template(pkginfo_template_path): """Return the pkginfo top-level key from a plist file.""" pkginfo_template = FoundationPlist.readPlist( os.path.expanduser(pkginfo_template_path)).get("pkginfo") if not pkginfo_template: sys.exit("Pkginfo template format incorrect!. Quitting.") return pkginfo_template
def main(): data = raw_battery_dict() # If this is not a laptop, data will just be empty. No need to do # more work. if data: adjusted_dict = adjusted_battery_dict() if adjusted_dict and "BatteryHealth" in adjusted_dict: data["BatteryHealth"] = adjusted_dict["BatteryHealth"] else: data["BatteryHealth"] = "Unkonwn" formatted_results = { "plugin": "Battery", "historical": False, "data": data } if os.path.exists(RESULTS_PATH): plugin_results = FoundationPlist.readPlist(RESULTS_PATH) else: plugin_results = [] plugin_results.append(formatted_results) FoundationPlist.writePlist(plugin_results, RESULTS_PATH)
def load_template(self, template_path, template_type): """Load a package info template in Info.plist or PackageInfo format.""" if template_path.endswith(".plist"): # Try to load Info.plist in bundle format. try: info = FoundationPlist.readPlist(self.env["template_path"]) except FoundationPlist.FoundationPlistException: raise ProcessorError( "Malformed Info.plist template %s" % self.env["template_path"] ) if template_type == "bundle": return info else: return self.convert_bundle_info_to_flat(info) else: # Try to load PackageInfo in flat format. try: info = ElementTree.parse(template_path) except FoundationPlist.FoundationPlistException: raise ProcessorError( "Malformed PackageInfo template %s" % self.env["template_path"] ) if template_type == "flat": return info else: return self.convert_flat_info_to_bundle(info)
def get_version(self, filepath): if os.path.exists(filepath): #try to determine the version version_basename = os.path.basename(filepath) # is it an app bundle? if version_basename.endswith(".app"): filepath = os.path.join(filepath, "Contents", "Info.plist") else: self.output("Cannot determine version. %s does not exist." % (filepath)) return None try: plist = FoundationPlist.readPlist(filepath) version_key = self.env.get("plist_version_key", "CFBundleShortVersionString") version = plist.get(version_key, None) self.output("Found version %s in file %s" % (version, filepath)) except FoundationPlist.FoundationPlistException as err: raise ProcessorError(err) return version
def readPlist(self, pathname): if not pathname: return {} try: return FoundationPlist.readPlist(pathname) except Exception, err: raise ProcessorError('Could not read %s: %s' % (pathname, err))
def buildplist(nbiindex, nbidescription, nbiname, nbienabled, destdir=__file__): """buildplist takes a source, destination and name parameter that are used to create a valid plist for imagetool ingestion.""" nbipath = os.path.join(destdir, nbiname + '.nbi') platformsupport = FoundationPlist.readPlist(os.path.join(nbipath, 'i386', 'PlatformSupport.plist')) enabledsystems = platformsupport.get('SupportedModelProperties') nbimageinfo = {'IsInstall': True, 'Index': nbiindex, 'Kind': 1, 'Description': nbidescription, 'Language': 'Default', 'IsEnabled': nbienabled, 'SupportsDiskless': False, 'RootPath': 'NetInstall.dmg', 'EnabledSystemIdentifiers': enabledsystems, 'BootFile': 'booter', 'Architectures': ['i386'], 'BackwardCompatible': False, 'DisabledSystemIdentifiers': [], 'Type': 'NFS', 'IsDefault': False, 'Name': nbiname, 'osVersion': '10.9'} plistfile = os.path.join(nbipath, 'NBImageInfo.plist') FoundationPlist.writePlist(nbimageinfo, plistfile)
def getComputerName_(self, component): auto_run = component.get('auto', False) hardware_info = Utils.get_hardware_info() # Try to get existing HostName try: preferencePath = os.path.join(self.targetVolume.mountpoint,'Library/Preferences/SystemConfiguration/preferences.plist') preferencePlist = FoundationPlist.readPlist(preferencePath) existing_name = preferencePlist['System']['System']['HostName'] except: # If we can't get the name, assign empty string for now existing_name = '' if auto_run: if component.get('use_serial', False): self.computerName = hardware_info.get('serial_number', 'UNKNOWN') else: self.computerName = existing_name self.theTabView.selectTabViewItem_(self.mainTab) self.workflowOnThreadPrep() else: if component.get('use_serial', False): self.computerNameInput.setStringValue_(hardware_info.get('serial_number', '')) elif component.get('prefix', None): self.computerNameInput.setStringValue_(component.get('prefix')) else: self.computerNameInput.setStringValue_(existing_name) # Switch to the computer name tab self.theTabView.selectTabViewItem_(self.computerNameTab) self.mainWindow.makeFirstResponder_(self.computerNameInput)
def convertIconToPNG(app_name, destination_path, desired_size): '''Converts an application icns file to a png file, choosing the representation closest to (but >= than if possible) the desired_size. Returns True if successful, False otherwise''' app_path = os.path.join('/Applications', app_name + '.app') if not os.path.exists(app_path): return False try: info = FoundationPlist.readPlist(os.path.join(app_path, 'Contents/Info.plist')) except (FoundationPlist.FoundationPlistException): info = {} icon_filename = info.get('CFBundleIconFile', app_name) icon_path = os.path.join(app_path, 'Contents/Resources', icon_filename) if not os.path.splitext(icon_path)[1]: # no file extension, so add '.icns' icon_path += u'.icns' if os.path.exists(icon_path): image_data = NSData.dataWithContentsOfFile_(icon_path) bitmap_reps = NSBitmapImageRep.imageRepsWithData_(image_data) chosen_rep = None for bitmap_rep in bitmap_reps: if not chosen_rep: chosen_rep = bitmap_rep elif (bitmap_rep.pixelsHigh() >= desired_size and bitmap_rep.pixelsHigh() < chosen_rep.pixelsHigh()): chosen_rep = bitmap_rep if chosen_rep: png_data = chosen_rep.representationUsingType_properties_(NSPNGFileType, None) png_data.writeToFile_atomically_(destination_path, False) return True return False
def launchApp(app_path): # Get the binary path so we can launch it using a threaded subprocess try: app_plist = FoundationPlist.readPlist( os.path.join(app_path, 'Contents', 'Info.plist')) binary = app_plist['CFBundleExecutable'] except: NSLog("Failed to get app binary location, cannot launch.") app_list = NSWorkspace.sharedWorkspace().runningApplications() # Before launching the app, check to see if it is already running app_running = False for app in app_list: if app_plist['CFBundleIdentifier'] == app.bundleIdentifier(): app_running = True # Only launch the app if it isn't already running if not app_running: thread = CustomThread( os.path.join(app_path, 'Contents', 'MacOS', binary)) thread.daemon = True thread.start() time.sleep(1) # Bring application to the front as they launch in the background in Netboot for some reason NSWorkspace.sharedWorkspace().launchApplication_(app_path)
def config_profile_info(ignore_cache=False): '''Returns a dictionary representing the output of `profiles -C -o`''' global CONFIG_PROFILE_INFO if not profiles_supported(): CONFIG_PROFILE_INFO = {} return CONFIG_PROFILE_INFO if not ignore_cache and CONFIG_PROFILE_INFO is not None: return CONFIG_PROFILE_INFO output_plist = os.path.join( tempfile.mkdtemp(dir=munkicommon.tmpdir()), 'profiles') cmd = ['/usr/bin/profiles', '-C', '-o', output_plist] proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc.communicate() if proc.returncode != 0: munkicommon.display_error( 'Could not obtain configuration profile info: %s' % proc.stderr) CONFIG_PROFILE_INFO = {} else: try: CONFIG_PROFILE_INFO = FoundationPlist.readPlist( output_plist + '.plist') except BaseException, err: munkicommon.display_error( 'Could not read configuration profile info: %s' % err) CONFIG_PROFILE_INFO = {} finally:
def main(self): # Check if we're trying to read something inside a dmg. (dmg_path, dmg, dmg_source_path) = self.env['input_plist_path'].partition(".dmg/") dmg_path += ".dmg" try: if dmg: # Mount dmg and copy path inside. mount_point = self.mount(dmg_path) input_plist_path = os.path.join(mount_point, dmg_source_path) else: # just use the given path input_plist_path = self.env['input_plist_path'] try: plist = FoundationPlist.readPlist(input_plist_path) version_key = self.env.get("plist_version_key", "CFBundleShortVersionString") self.env['version'] = plist.get(version_key, "UNKNOWN_VERSION") self.output("Found version %s in file %s" % (self.env['version'], input_plist_path)) except FoundationPlist.FoundationPlistException, err: raise ProcessorError(err) finally: if dmg: self.unmount(dmg_path)
def main(self): # Check if we're trying to read something inside a dmg. (dmg_path, dmg, dmg_source_path) = self.env[ 'input_plist_path'].partition(".dmg/") dmg_path += ".dmg" try: if dmg: # Mount dmg and copy path inside. mount_point = self.mount(dmg_path) input_plist_path = os.path.join(mount_point, dmg_source_path) else: # just use the given path input_plist_path = self.env['input_plist_path'] try: plist = FoundationPlist.readPlist(input_plist_path) version_key = self.env.get( "plist_version_key", "CFBundleShortVersionString") self.env['version'] = plist.get(version_key, "UNKNOWN_VERSION") self.output("Found version %s in file %s" % (self.env['version'], input_plist_path)) except FoundationPlist.FoundationPlistException, err: raise ProcessorError(err) finally: if dmg: self.unmount(dmg_path)
def convertIconToPNG(app_name, destination_path, desired_size): '''Converts an application icns file to a png file, choosing the representation closest to (but >= than if possible) the desired_size. Returns True if successful, False otherwise''' app_path = os.path.join('/Applications', app_name + '.app') if not os.path.exists(app_path): return False try: info = FoundationPlist.readPlist( os.path.join(app_path, 'Contents/Info.plist')) except (FoundationPlist.FoundationPlistException): info = {} icon_filename = info.get('CFBundleIconFile', app_name) icon_path = os.path.join(app_path, 'Contents/Resources', icon_filename) if not os.path.splitext(icon_path)[1]: # no file extension, so add '.icns' icon_path += u'.icns' if os.path.exists(icon_path): image_data = NSData.dataWithContentsOfFile_(icon_path) bitmap_reps = NSBitmapImageRep.imageRepsWithData_(image_data) chosen_rep = None for bitmap_rep in bitmap_reps: if not chosen_rep: chosen_rep = bitmap_rep elif (bitmap_rep.pixelsHigh() >= desired_size and bitmap_rep.pixelsHigh() < chosen_rep.pixelsHigh()): chosen_rep = bitmap_rep if chosen_rep: png_data = chosen_rep.representationUsingType_properties_( NSPNGFileType, None) png_data.writeToFile_atomically_(destination_path, False) return True return False
def profile_receipt_data(): '''Reads profile install data''' try: profile_data = FoundationPlist.readPlist(profile_receipt_data_path()) return profile_data except BaseException: return {}
def main(self): """Return a version for file at input_plist_path""" # Check if we're trying to read something inside a dmg. (dmg_path, dmg, dmg_source_path) = ( self.parsePathForDMG(self.env['input_plist_path'])) try: if dmg: # Mount dmg and copy path inside. mount_point = self.mount(dmg_path) input_plist_path = os.path.join(mount_point, dmg_source_path) else: # just use the given path input_plist_path = self.env['input_plist_path'] try: plist = FoundationPlist.readPlist(input_plist_path) version_key = self.env.get("plist_version_key") self.env['version'] = plist.get(version_key, "UNKNOWN_VERSION") self.output("Found version %s in file %s" % (self.env['version'], input_plist_path)) except FoundationPlist.FoundationPlistException, err: raise ProcessorError(err) finally: if dmg: self.unmount(dmg_path)
def load_template(self, template_path, template_type): """Load a package info template in Info.plist or PackageInfo format.""" if template_path.endswith(".plist"): # Try to load Info.plist in bundle format. try: info = FoundationPlist.readPlist(self.env['template_path']) except FoundationPlist.FoundationPlistException: raise ProcessorError("Malformed Info.plist template %s" % self.env['template_path']) if template_type == "bundle": return info else: return self.convert_bundle_info_to_flat(info) else: # Try to load PackageInfo in flat format. try: info = ElementTree.parse(template_path) except FoundationPlist.FoundationPlistException: raise ProcessorError("Malformed PackageInfo template %s" % self.env['template_path']) if template_type == "flat": return info else: return self.convert_flat_info_to_bundle(info)
def main(self): """Return a version for file at input_plist_path""" # Check if we're trying to read something inside a dmg. (dmg_path, dmg, dmg_source_path) = self.parsePathForDMG( self.env["input_plist_path"] ) try: if dmg: # Mount dmg and copy path inside. mount_point = self.mount(dmg_path) input_plist_path = os.path.join(mount_point, dmg_source_path) else: # just use the given path input_plist_path = self.env["input_plist_path"] if not os.path.exists(input_plist_path): raise ProcessorError( "File '%s' does not exist or could not be read." % input_plist_path ) try: plist = FoundationPlist.readPlist(input_plist_path) version_key = self.env.get("plist_version_key") self.env["version"] = plist.get(version_key, "UNKNOWN_VERSION") self.output( "Found version %s in file %s" % (self.env["version"], input_plist_path) ) except FoundationPlist.FoundationPlistException as err: raise ProcessorError(err) finally: if dmg: self.unmount(dmg_path)
def getIdentifierFromProfile(profile_path): profile_dict = FoundationPlist.readPlist(profile_path) try: profile_id = profile_dict['PayloadIdentifier'] except: errorAndExit("Can't find a ProfileIdentifier in the profile at %s." % profile_path) return profile_id
def config_profile_info(ignore_cache=False): '''Returns a dictionary representing the output of `profiles -C -o`''' global CONFIG_PROFILE_INFO if not profiles_supported(): CONFIG_PROFILE_INFO = {} return CONFIG_PROFILE_INFO if not ignore_cache and CONFIG_PROFILE_INFO is not None: return CONFIG_PROFILE_INFO output_plist = os.path.join(tempfile.mkdtemp(dir=munkicommon.tmpdir()), 'profiles') cmd = ['/usr/bin/profiles', '-C', '-o', output_plist] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc.communicate() if proc.returncode != 0: munkicommon.display_error( 'Could not obtain configuration profile info: %s' % proc.stderr) CONFIG_PROFILE_INFO = {} else: try: CONFIG_PROFILE_INFO = FoundationPlist.readPlist(output_plist + '.plist') except BaseException, err: munkicommon.display_error( 'Could not read configuration profile info: %s' % err) CONFIG_PROFILE_INFO = {} finally:
def buildplist(nbiindex, nbidescription, nbiname, nbienabled, destdir=__file__): """buildplist takes a source, destination and name parameter that are used to create a valid plist for imagetool ingestion.""" nbipath = os.path.join(destdir, nbiname + '.nbi') platformsupport = FoundationPlist.readPlist( os.path.join(nbipath, 'i386', 'PlatformSupport.plist')) enabledsystems = platformsupport.get('SupportedModelProperties') nbimageinfo = { 'IsInstall': True, 'Index': nbiindex, 'Kind': 1, 'Description': nbidescription, 'Language': 'Default', 'IsEnabled': nbienabled, 'SupportsDiskless': False, 'RootPath': 'NetInstall.dmg', 'EnabledSystemIdentifiers': enabledsystems, 'BootFile': 'booter', 'Architectures': ['i386'], 'BackwardCompatible': False, 'DisabledSystemIdentifiers': [], 'Type': 'NFS', 'IsDefault': False, 'Name': nbiname, 'osVersion': '10.9' } plistfile = os.path.join(nbipath, 'NBImageInfo.plist') FoundationPlist.writePlist(nbimageinfo, plistfile)
def autoset_timezone(): """enable timezone based on current location""" das_plist = '/Library/Preferences/com.apple.timezone.auto.plist' enabler = FoundationPlist.readPlist(das_plist) val = enabler.get('Active') if val != 1: enabler['Active'] = 1 FoundationPlist.writePlist(enabler, das_plist)
def readPlist(self, pathname): if not pathname: return {} try: return FoundationPlist.readPlist(pathname) except Exception, err: raise ProcessorError( 'Could not read %s: %s' % (pathname, err))
def read_info_plist(self, app_path): """Read Contents/Info.plist from the app.""" #pylint: disable=no-self-use plistpath = os.path.join(app_path, "Contents", "Info.plist") try: plist = FoundationPlist.readPlist(plistpath) except FoundationPlist.FoundationPlistException, err: raise ProcessorError("Can't read %s: %s" % (plistpath, err))
def main(): """Set up arguments and start processing.""" args = get_argument_parser().parse_args() autopkg_prefs = FoundationPlist.readPlist( os.path.expanduser("~/Library/Preferences/com.github.autopkg.plist")) MUNKI_REPO = autopkg_prefs.get("MUNKI_REPO") production_cat = FoundationPlist.readPlist( os.path.join(MUNKI_REPO, "catalogs/%s" % args.catalog)) pkginfo_template = (get_pkginfo_template(args.pkginfo) if args.pkginfo else {}) recipes = args.recipes if args.recipes else get_recipes(args.recipe_list) try: process_overrides(recipes, args, production_cat, pkginfo_template) except KeyboardInterrupt: print_error("Bailing!") finally: reset_term_colors()
def cacheSwupdMetadata(): '''Copies ServerMetadata (.smd), Metadata (.pkm), and Distribution (.dist) files for the available updates to the local machine and writes a new sucatalog that refers to the local copies of these files.''' filtered_catalogpath = os.path.join( swupdCacheDir(), 'content/catalogs/filtered_index.sucatalog') catalog = FoundationPlist.readPlist(filtered_catalogpath) if 'Products' in catalog: product_keys = list(catalog['Products'].keys()) for product_key in product_keys: munkicommon.display_status('Caching metadata for product ID %s', product_key) product = catalog['Products'][product_key] if 'ServerMetadataURL' in product: unused_path = replicateURLtoFilesystem( product['ServerMetadataURL'], copy_only_if_missing=True) for package in product.get('Packages', []): ### not replicating the packages themselves ### #if 'URL' in package: # unused_path = replicateURLtoFilesystem( # package['URL'], # copy_only_if_missing=fast_scan) if 'MetadataURL' in package: munkicommon.display_status( 'Caching package metadata for product ID %s', product_key) unused_path = replicateURLtoFilesystem( package['MetadataURL'], copy_only_if_missing=True) distributions = product['Distributions'] for dist_lang in distributions.keys(): munkicommon.display_status( 'Caching %s distribution for product ID %s', dist_lang, product_key) dist_url = distributions[dist_lang] unused_path = replicateURLtoFilesystem( dist_url, copy_only_if_missing=True) # rewrite URLs to point to local resources rewriteURLs(catalog, rewrite_pkg_urls=False) # write out the rewritten catalog localcatalogpath = os.path.join(swupdCacheDir(), 'content', 'catalogs') if not os.path.exists(localcatalogpath): try: os.makedirs(localcatalogpath) except OSError, oserr: raise ReplicationError(oserr) localcatalogpathname = os.path.join(localcatalogpath, 'local_download.sucatalog') FoundationPlist.writePlist(catalog, localcatalogpathname) rewriteURLs(catalog, rewrite_pkg_urls=True) localcatalogpathname = os.path.join(localcatalogpath, 'local_install.sucatalog') FoundationPlist.writePlist(catalog, localcatalogpathname)
def read_plist(self, pathname): """reads a plist from pathname""" # pylint: disable=no-self-use if not pathname: return {} try: return FoundationPlist.readPlist(pathname) except Exception as err: raise ProcessorError("Could not read %s: %s" % (pathname, err))
def read_bundle_info(self, path): """Read Contents/Info.plist inside a bundle.""" #pylint: disable=no-self-use try: info = FoundationPlist.readPlist( os.path.join(path, "Contents", "Info.plist")) except FoundationPlist.FoundationPlistException as err: raise ProcessorError(err) return info
def main(self): keys = self.env.get('plist_keys', {"CFBundleShortVersionString": "version"}) # Many types of paths are accepted. Figure out which kind we have. path = os.path.normpath(self.env['info_path']) try: # Wrap all other actions in a try/finally so if we mount an image, # it will always be unmounted. # Check if we're trying to read something inside a dmg. (dmg_path, dmg, dmg_source_path) = self.parsePathForDMG(path) if dmg: mount_point = self.mount(dmg_path) path = os.path.join(mount_point, dmg_source_path.lstrip('/')) # Finally check whether this is at least a valid path if not os.path.exists(path): raise ProcessorError("Path '%s' doesn't exist!" % path) # Is the path a bundle? info_plist_path = self.get_bundle_info_path(path) if info_plist_path: path = info_plist_path # Does it have a 'plist' extension (naively assuming 'plist' only names, for now) elif path.endswith('.plist'): # Full path to a plist was supplied, move on. pass # Might the path contain a bundle at its root? else: path = self.find_bundle(path) # Try to read the plist self.output("Reading: %s" % path) try: info = FoundationPlist.readPlist(path) except (FoundationPlist.NSPropertyListSerializationException, UnicodeEncodeError) as err: raise ProcessorError(err) # Copy each plist_keys' values and assign to new env variables self.env["plist_reader_output_variables"] = {} for key, val in keys.items(): try: self.env[val] = info[key] self.output("Assigning value of '%s' to output variable '%s'" % (self.env[val], val)) # This one is for documentation/recordkeeping self.env["plist_reader_output_variables"][val] = self.env[val] except KeyError: raise ProcessorError( "Key '%s' could not be found in the plist %s!" % (key, path)) finally: if dmg: self.unmount(dmg_path)
def read_plist(self, pathname): """Read a plist from pathname.""" # pylint: disable=no-self-use if not pathname: return {} try: return FoundationPlist.readPlist(pathname) except Exception as err: raise ProcessorError('Could not read %s: %s' % (pathname, err))
def clear_clients(): """Clear clients.plist in locationd settings.""" auth_plist = {} das_plist = '/private/var/db/locationd/clients.plist' clients_dict = FoundationPlist.readPlist(das_plist) service_handler('unload') clients_dict = auth_plist FoundationPlist.writePlist(clients_dict, das_plist) os.chown(das_plist, 205, 205) service_handler('load')
def get_autopkg_version(): try: version_plist = FoundationPlist.readPlist( os.path.join(os.path.dirname(__file__), "version.plist")) except FoundationPlist.FoundationPlistException: return "UNKNOWN" try: return version_plist["Version"] except (AttributeError, TypeError): return "UNKNOWN"
def get_identifer_from_recipe_file(filename): '''Attempts to read plist file filename and get the identifier. Otherwise, returns None.''' try: # make sure we can read it recipe_plist = FoundationPlist.readPlist(filename) except FoundationPlist.FoundationPlistException, err: print >> sys.stderr, ( "WARNING: plist error for %s: %s" % (filename, unicode(err))) return None
def get_identifer_from_recipe_file(filename): '''Attempts to read plist file filename and get the identifier. Otherwise, returns None.''' try: # make sure we can read it recipe_plist = FoundationPlist.readPlist(filename) except FoundationPlist.FoundationPlistException, err: print >> sys.stderr, ("WARNING: plist error for %s: %s" % (filename, unicode(err))) return None
def getInstallInfo(): '''Returns the dictionary describing the managed installs and removals''' managedinstallbase = pref('ManagedInstallDir') plist = {} installinfo = os.path.join(managedinstallbase, 'InstallInfo.plist') if os.path.exists(installinfo): try: plist = FoundationPlist.readPlist(installinfo) except FoundationPlist.NSPropertyListSerializationException: pass return plist
def sysprefs_boxchk(): """Enables location services in sysprefs globally""" uuid = ioreg() path_stub = "/private/var/db/locationd/Library/Preferences/ByHost/com.apple.locationd." das_plist = path_stub + uuid.strip() + ".plist" on_disk = FoundationPlist.readPlist(das_plist) val = on_disk.get('LocationServicesEnabled', None) if val != 1: on_disk['LocationServicesEnabled'] = 1 FoundationPlist.writePlist(on_disk, das_plist) os.chown(das_plist, 205, 205)
def getAppleUpdates(): """Returns any available Apple updates""" managedinstallbase = pref("ManagedInstallDir") plist = {} appleUpdatesFile = os.path.join(managedinstallbase, "AppleUpdates.plist") if os.path.exists(appleUpdatesFile) and (pref("InstallAppleSoftwareUpdates") or pref("AppleSoftwareUpdatesOnly")): try: plist = FoundationPlist.readPlist(appleUpdatesFile) except FoundationPlist.NSPropertyListSerializationException: pass return plist
def read_profile(profile_path): '''Reads a profile.''' try: return FoundationPlist.readPlist(profile_path) except FoundationPlist.NSPropertyListSerializationException: # possibly a signed profile return read_signed_profile(profile_path) except BaseException, err: munkicommon.display_error( 'Error reading profile %s: %s' % (profile_path, err)) return {}
def read_profile(profile_path): '''Reads a profile.''' try: return FoundationPlist.readPlist(profile_path) except FoundationPlist.NSPropertyListSerializationException: # possibly a signed profile return read_signed_profile(profile_path) except BaseException, err: munkicommon.display_error('Error reading profile %s: %s' % (profile_path, err)) return {}
def __init__(self, filename): self.filename = filename try: self._bm = FoundationPlist.readPlist(self.filename) except: self.create() self.__init__(filename) self.bookmarks_bar = self.find("BookmarksBar") self.bookmarks_menu = self.find("BookmarksMenu") self.history = self.find("History") self.reading_list = self.find("com.apple.ReadingList")
def getAppleUpdates(): '''Returns any available Apple updates''' managedinstallbase = pref('ManagedInstallDir') plist = {} appleUpdatesFile = os.path.join(managedinstallbase, 'AppleUpdates.plist') if (os.path.exists(appleUpdatesFile) and pref('InstallAppleSoftwareUpdates')): try: plist = FoundationPlist.readPlist(appleUpdatesFile) except FoundationPlist.NSPropertyListSerializationException: pass return plist
def get_url(self, os_ver): try: plist_text = subprocess.check_output(['/usr/bin/curl', '-s', '-1', CHECK_URL]) except BaseException as e: print e raise ProcessorError('Could not retrieve check URL %s' % CHECK_URL) plist_filename = os.path.join(self.env['RECIPE_CACHE_DIR'], PLIST_FN) try: plistf = open(plist_filename, 'w') plistf.write(plist_text) plistf.close() except: raise ProcessorError('Could not write NVIDIA plist file %s' % plist_filename) try: plist = FoundationPlist.readPlist(plist_filename) except: raise ProcessorError('Could not read NVIDIA plist file %s' % plist_filename) # the Version is blank here due to the plist NSPredicate # testing it to not be the current version. pred_obj = {'Ticket': {'Version': ''}, 'SystemVersion': {'ProductVersion': os_ver}} url = None version = None for rule in plist['Rules']: if self.evaluate_predicate(pred_obj, rule['Predicate']): self.output('Satisfied predicate for OS version %s' % os_ver) url = rule['Codebase'] version = rule['kServerVersion'] # with a satisfied predicate, evaluate lower OS versions # so as to determine a minimum OS constraint, decrementing # one 10.x version at a time while self.evaluate_predicate(pred_obj, rule['Predicate']): # record the currently-evaluated OS version as the minimum required minimum_os_ver = os_ver osx, major = os_ver.split('.') os_ver = osx + '.' + str(int(major) - 1) pred_obj['SystemVersion']['ProductVersion'] = os_ver self.output('Evaluating predicate for lower OS version %s' % os_ver) self.output('OS version %s too low!' % os_ver) # highest required versions seem to be always first, so we break # after we've satisfied one Predicate break if not url: raise ProcessorError('No valid Predicate rules found!') return (url, version, minimum_os_ver)
def restartNeeded(): '''Returns True if any update in AppleUpdates.plist requires an update; False otherwise.''' try: appleupdates = FoundationPlist.readPlist(appleUpdatesFile()) except FoundationPlist.NSPropertyListSerializationException: return True for item in appleupdates.get('AppleUpdates', []): if (item.get('RestartAction') == 'RequireRestart' or item.get('RestartAction') == 'RecommendRestart'): return True # if we get this far, there must be no items that require restart return False
def get_os_version(app_path): '''Returns the os version from the OS Installer app''' installinfo_plist = os.path.join( app_path, 'Contents/SharedSupport/InstallInfo.plist') if not os.path.isfile(installinfo_plist): # no Contents/SharedSupport/InstallInfo.plist return '' try: info = FoundationPlist.readPlist(installinfo_plist) return info['System Image Info']['version'] except (FoundationPlist.FoundationPlistException, IOError, KeyError, AttributeError, TypeError): return ''