def main(): ''' Main Controlling Module: - Checks preferences set - Checks for Path, if not creates - Downloads plist if needed ''' keys = {} keys["ManagedUser"] = CFPreferencesCopyAppValue( "ManagedUser", "com.github.wardsparadox.dock-maintainer") keys["ServerURL"] = CFPreferencesCopyAppValue( "ServerURL", "com.github.wardsparadox.dock-maintainer") keys["FileName"] = CFPreferencesCopyAppValue( "FileName", "com.github.wardsparadox.dock-maintainer") path = os.path.realpath( "/Library/Application Support/com.github.wardsparadox.dock-maintainer") if os.path.exists(path): logging.info("Path exists at %s", path) else: logging.info("Path not found, creating at %s", path) os.mkdir(path, 0755) if keys["ManagedUser"] is None: logging.error("No ManagedUser Preference set") exit(2) else: plistfilepath = os.path.join(path, keys["ManagedUser"]) completeurl = os.path.join(keys["ServerURL"], keys["FileName"]) try: fileurl = urllib2.urlopen(completeurl) meta = fileurl.info().getheaders("Last-Modified")[0] servermod = datetime.datetime.fromtimestamp( mktime( datetime.datetime.strptime( meta, "%a, %d %b %Y %X GMT").timetuple())) except urllib2.HTTPError: logging.error("Can not connect to url") exit(1) if not os.path.isfile(plistfilepath): logging.info("File not found! Downloading") downloadFile(fileurl, plistfilepath, servermod) exit(0) if xattr.listxattr(plistfilepath): logging.info("Got File Attributes") else: logging.info("No Attributes found! Downloading and setting them") downloadFile(fileurl, plistfilepath, servermod) exit(0) filexattrdate = xattr.getxattr(plistfilepath, 'dock-maintainer.Last-Modified-date') if str(servermod) != filexattrdate: logging.info("File is out of date") downloadFile(fileurl, plistfilepath, servermod) else: logging.info("File is synced.") exit(0)
def __init__(self): for key in self._SECTIONS: try: section = CFPreferencesCopyAppValue(key, self._DOMAIN) self.items[key] = section.mutableCopy() except Exception: raise
def __init__(self): for key in self._SECTIONS: try: section = CFPreferencesCopyAppValue(key, self._DOMAIN) self.items[key] = section.mutableCopy() except AttributeError: self.items[key] = self.default_settings[key] except Exception: raise
def __init__(self): for key in self._SECTIONS: try: section = CFPreferencesCopyAppValue(key, self._DOMAIN) self.items[key] = section.mutableCopy() except Exception: raise for key in self._MUTABLE_KEYS + self._IMMUTABLE_KEYS: try: value = CFPreferencesCopyAppValue(key, self._DOMAIN) setattr(self, key.replace('-', '_'), value) except Exception: raise
def pref(pref_name): """Return a preference. See prefs.py for details """ pref_value = CFPreferencesCopyAppValue(pref_name, BUNDLE_ID) return pref_value
def getPrefs(preferenceName, bundleid=''): # Attempt to get pref from MCX try: print "MunkiTimeWindow: Attempting to load", preferenceName, "from MCX" pref = CFPreferencesCopyAppValue(preferenceName, bundleid) if pref == None: print "MunkiTimeWindow: No MCX/mobileconfig found for", preferenceName print "MunkiTimeWindow: Attempting to load preference from", munki_prefs_location try: pref = munki_prefs[preferenceName] except: print "MunkiTimeWindow: Error loading", preferenceName, "from", munki_prefs_location print "MunkiTimeWindow: Unable to obtain", preferenceName, "preference" pref = DEFAULT_PREFS.get(preferenceName) print "MunkiTimeWindow: Using default value for", preferenceName, "(", pref, ")" print "MunkiTimeWindow:", preferenceName, "is", pref return pref except: print "MunkiTimeWindow: Error loading", preferenceName, "from MCX" print "MunkiTimeWindow: Attempting to load preference from", munki_prefs_location try: pref = munki_prefs[preferenceName] except: print "MunkiTimeWindow: Error loading", preferenceName, "from", munki_prefs_location print "MunkiTimeWindow: Unable to obtain", preferenceName, " preference" pref = DEFAULT_PREFS.get(preferenceName) print "MunkiTimeWindow: Using default value for", preferenceName, "(", pref, ")"
def pref(pref_name): """Return a preference value. Since this uses CFPreferencesCopyAppValue, Preferences can be defined several places. Precedence is: - MCX - /var/root/Library/Preferences/com.salopensource.sal.plist - /Library/Preferences/com.salopensource.sal.plist - default_prefs defined here. """ default_prefs = { 'ServerURL': 'http://sal', 'osquery_launchd': 'com.facebook.osqueryd.plist', 'SkipFacts': [], 'SyncScripts': True, 'BasicAuth': True, 'GetGrains': False, 'GetOhai': False, } pref_value = CFPreferencesCopyAppValue(pref_name, BUNDLE_ID) if pref_value == None and pref_name in default_prefs: pref_value = default_prefs.get(pref_name) # we're using a default value. We'll write it out to # /Library/Preferences/<BUNDLE_ID>.plist for admin # discoverability set_pref(pref_name, pref_value) if isinstance(pref_value, NSDate): # convert NSDate/CFDates to strings pref_value = str(pref_value) return pref_value
def print_config(): '''Prints the current Munki configuration''' print('Current Munki configuration:') max_pref_name_len = max([len(pref_name) for pref_name in DEFAULT_PREFS]) for pref_name in sorted(DEFAULT_PREFS): if pref_name == 'LastNotifiedDate': # skip it continue if pref_name in FORCE_FALSE_ON_APPLE_SILICON: value = False where = "Forced as False on Apple Silicon" else: value = pref(pref_name) where = get_config_level(BUNDLE_ID, pref_name, value) repr_value = value if is_a_string(value): repr_value = repr(value) print(('%' + str(max_pref_name_len) + 's: %5s %s ') % (pref_name, repr_value, where)) # also print com.apple.SoftwareUpdate CatalogURL config if # Munki is configured to install Apple updates if pref('InstallAppleSoftwareUpdates'): print('Current Apple softwareupdate configuration:') domain = 'com.apple.SoftwareUpdate' pref_name = 'CatalogURL' value = CFPreferencesCopyAppValue(pref_name, domain) where = get_config_level(domain, pref_name, value) repr_value = value if is_a_string(value): repr_value = repr(value) print(('%' + str(max_pref_name_len) + 's: %5s %s ') % (pref_name, repr_value, where))
def print_config(): '''Prints the current Munki configuration''' print 'Current Munki configuration:' max_pref_name_len = max( [len(pref_name) for pref_name in DEFAULT_PREFS.keys()]) for pref_name in sorted(DEFAULT_PREFS.keys()): if pref_name == 'LastNotifiedDate': # skip it continue value = pref(pref_name) where = get_config_level(BUNDLE_ID, pref_name, value) repr_value = value if isinstance(value, basestring): repr_value = repr(value) print('%' + str(max_pref_name_len) + 's: %5s %s ') % (pref_name, repr_value, where) # also print com.apple.SoftwareUpdate CatalogURL config if # Munki is configured to install Apple updates if pref('InstallAppleSoftwareUpdates'): print 'Current Apple softwareupdate configuration:' domain = 'com.apple.SoftwareUpdate' pref_name = 'CatalogURL' value = CFPreferencesCopyAppValue(pref_name, domain) where = get_config_level(domain, pref_name, value) repr_value = value if isinstance(value, basestring): repr_value = repr(value) print('%' + str(max_pref_name_len) + 's: %5s %s ') % (pref_name, repr_value, where)
def getPrefs(preferenceName, bundleid=''): # Attempt to get pref from MCX try: print('MunkiTimeWindow: Attempting to load %s from MCX' % preferenceName) pref = CFPreferencesCopyAppValue(preferenceName, bundleid) if pref == None: print('MunkiTimeWindow: No MCX/mobileconfig found for %s' % preferenceName) print('MunkiTimeWindow: Attempting to load preference from %s' % munki_prefs_location) try: pref = munki_prefs[preferenceName] except: print('MunkiTimeWindow: Error loading %s from %s' % (preferenceName, munki_prefs_location)) print('MunkiTimeWindow: Unable to obtain %s preference' % preferenceName) pref = DEFAULT_PREFS.get(preferenceName) print('MunkiTimeWindow: Using default value for %s (%s)' % (preferenceName, pref)) print('MunkiTimeWindow: %s is %s' % (preferenceName, pref)) return pref except: print('MunkiTimeWindow: Error loading %s from MCX' % preferenceName) print('MunkiTimeWindow: Attempting to load preference from %s' % munki_prefs_location) try: pref = munki_prefs[preferenceName] except: print('MunkiTimeWindow: Error loading %s from %s' % (preferenceName, munki_prefs_location)) print('MunkiTimeWindow: Unable to obtain %s preference' % preferenceName) pref = DEFAULT_PREFS.get(preferenceName) print('MunkiTimeWindow: Using default value for %s (%s)' % (preferenceName, pref))
def __init__(self): """Create a new Preferences object from the current settings. Examples: >>> preferences = Preferences() >>> keys = ['latexViewer', 'latexEngine', 'latexUselatexmk', ... 'latexVerbose', 'latexDebug', 'latexAutoView', ... 'latexKeepLogWin', 'latexEngineOptions'] >>> all([key in preferences.prefs for key in keys]) True """ tm_identifier = getenv('TM_APP_IDENTIFIER', 'com.macromates.textmate') CFPreferencesAppSynchronize(tm_identifier) self.default_values = { 'latexAutoView': 1, 'latexEngine': "pdflatex", 'latexEngineOptions': "", 'latexVerbose': 0, 'latexUselatexmk': 1, 'latexViewer': "TextMate", 'latexKeepLogWin': 1, 'latexDebug': 0, } self.prefs = self.default_values.copy() for key in self.prefs: preference_value = CFPreferencesCopyAppValue(key, tm_identifier) if preference_value is not None: self.prefs[key] = preference_value
def get_pref(pref_name, bundleid=BUNDLE_ID): """Get preference value for key from domain.""" pref_value = CFPreferencesCopyAppValue(pref_name, bundleid) if isinstance(pref_value, NSDate): # convert NSDate/CFDates to strings pref_value = str(pref_value) return pref_value
def fact(): """Returns the firewall status""" result = "None" plist = "/Library/Preferences/com.apple.alf.plist" firewall_status = CFPreferencesCopyAppValue("globalstate", plist) result = bool(firewall_status) return {factoid: result}
def fact(): '''Returns the firewall status''' result = 'None' plist = '/Library/Preferences/com.apple.alf.plist' firewall_status = CFPreferencesCopyAppValue('globalstate', plist) result = bool(firewall_status) return {factoid: result}
def pref(pref_name, default=None): default_prefs = { 'RepoURL': 'http://munki/managedmac', 'ClientIdentifier': '', } pref_value = CFPreferencesCopyAppValue(pref_name, BUNDLE_ID) if pref_value == None: pref_value = default_prefs.get(pref_name) return pref_value
def main(self): repo_path = CFPreferencesCopyAppValue( "MUNKI_REPO", "com.github.autopkg") if repo_path: call(['git', 'add', '-A'], cwd=repo_path) call(['git', 'commit', '-m', 'Automatic commit after AutoPKG run'], cwd=repo_path) call(['git', 'push'], cwd=repo_path) else: self.output("No munki repo set, nothing pushed")
def get_pref_value(key, domain): value = CFPreferencesCopyAppValue(key, domain) if (value is not None): return value elif (value is not None and len(value) == 0): return "" else: return ""
def recommended_updates(): """ Return a dict of pending recommended updates """ updates = CFPreferencesCopyAppValue( 'RecommendedUpdates', '/Library/Preferences/com.apple.SoftwareUpdate') # If there are no updates, explicitly return None if updates and len(updates) > 0: return updates else: return None
def pref(prefname): """Return a preference. Since this uses CFPreferencesCopyAppValue, Preferences can be defined several places. Precedence is: - MCX/Configuration Profile - ~/Library/Preferences/ByHost/ com.googlecode.munki.munkiimport.XX.plist - ~/Library/Preferences/com.googlecode.munki.munkiimport.plist - /Library/Preferences/com.googlecode.munki.munkiimport.plist """ return CFPreferencesCopyAppValue(prefname, BUNDLE_ID)
def main(self): if "pkginfo" not in self.env: self.env["pkginfo"] = {} default_catalog = CFPreferencesCopyAppValue( "default_catalog", "com.googlecode.munki.munkiimport") if default_catalog: self.env["pkginfo"]["catalogs"] = [default_catalog] self.output("Updated target catalogs into pkginfo with %s" % default_catalog) else: self.output("No default catalogs found, nothing changed")
def get_user_defaults(): """Get the user preferences for Recipe Robot. Returns: dict: The dictionary containing a key/value pair for Recipe Robot preferences. """ prefs_dict = { key: CFPreferencesCopyAppValue(key, BUNDLE_ID) for key in PREFERENCE_KEYS } return prefs_dict
def main(): bundle_id = "com.apple.RemoteDesktop.plist" sal_key = "ARD_Info_{}" prefs_key_prefix = "Text{}" data = { sal_key.format(i): CFPreferencesCopyAppValue(prefs_key_prefix.format(i), bundle_id) or "" for i in range(1, 5)} sal.add_plugin_results('ARD_Info', data)
def main(argv): p = optparse.OptionParser() p.set_usage("""Usage: %prog [options] verb""") p.add_option("-s", "--server") p.add_option("-u", "--username") p.add_option("-p", "--password") p.add_option("-P", "--prompt-password", action="store_true") options, argv = p.parse_args(argv) if len(argv) < 2: print >>sys.stderr, p.get_usage() return 1 verbs = dict() for name, func in globals().items(): if name.startswith("do_"): verbs[name[3:]] = func action = argv[1] if action not in verbs: sys.exit("Unknown verb %s" % action) server = options.server or CFPreferencesCopyAppValue("server", BUNDLE_ID) if not server: sys.exit("No server specified") username = options.username or CFPreferencesCopyAppValue("username", BUNDLE_ID) if not username: sys.exit("No username specified") password = options.password or CFPreferencesCopyAppValue("password", BUNDLE_ID) if options.prompt_password or not password: password = getpass.getpass("Password for %s@%s: " % (username, server)) if not password: sys.exit("No password specified") pm = profilemanager.ProfileManager(server) try: pm.authenticate(username, password) verbs[action](pm, list(x.decode("utf-8") for x in argv[2:])) except profilemanager.PMError as e: sys.exit(e) return 0
def get_repo(): try: repo_url = CFPreferencesCopyAppValue( 'repo_url', 'com.googlecode.munki.munkiimport') except: repo = False if not repo_url: repo = False else: url_parts = urlparse(repo_url) repo = url_parts.path return repo
def conditionalItemsPath(): # <http://code.google.com/p/munki/wiki/ConditionalItems> # Read the location of the ManagedInstallDir from ManagedInstall.plist BUNDLE_ID = 'ManagedInstalls' pref_name = 'ManagedInstallDir' managedinstalldir = CFPreferencesCopyAppValue(pref_name, BUNDLE_ID) # Make sure we're outputting our information to "ConditionalItems.plist" if managedinstalldir: return os.path.join(managedinstalldir, 'ConditionalItems.plist') else: # Munki default return "/Library/Managed Installs/ConditionalItems.plist"
def pref(pref_name): """Return a preference. Since this uses CFPreferencesCopyAppValue, Preferences can be defined several places. Precedence is: - MCX - ~/Library/Preferences/ManagedInstalls.plist - /Library/Preferences/ManagedInstalls.plist - default_prefs defined here. """ default_prefs = { 'LogFile': '/Library/Managed Installs/Logs/ManagedSoftwareUpdate.log' } pref_value = CFPreferencesCopyAppValue(pref_name, BUNDLE_ID) if pref_value == None: pref_value = default_prefs.get(pref_name) return pref_value
def check_and_disable_appnap_for_pdapp(self): """Log a warning if AppNap isn't disabled on the system.""" appnap_disabled = CFPreferencesCopyAppValue('NSAppSleepDisabled', 'com.adobe.PDApp') if not appnap_disabled: self.output("WARNING: A bug in Creative Cloud Packager makes " "it likely to stall indefinitely whenever the app " "window is hidden or obscured due to App Nap. To " "prevent this, we're setting a user preference to " "disable App Nap for just the " "Adobe PDApp application. This can be undone using " "this command: 'defaults delete com.adobe.PDApp " "NSAppSleepDisabled") CFPreferencesSetAppValue('NSAppSleepDisabled', True, 'com.adobe.PDApp')
def munkiinfo_report(): """Build our report data for our munkiinfo plist""" munkiprotocol = get_munkiprotocol() if 'file' in munkiprotocol: munkiprotocol = 'localrepo' AppleCatalogURL = str(CFPreferencesCopyAppValue('CatalogURL', 'com.apple.SoftwareUpdate')) if AppleCatalogURL == 'None': AppleCatalogURL = '' report = { 'AppleCatalogURL': AppleCatalogURL, 'munkiprotocol': munkiprotocol, } report.update(formated_prefs()) return ([report])
def read_prefs(prefs_section): """Read indicated preferences section and return a dict. Uses CFPreferencesCopyAppValue. Preferences can be defined several places. Precedence is: - MCX/configuration profile - /var/root/Library/Preferences/[BUNDLE_ID].plist - /Library/Preferences/[BUNDLE_ID].plist - .GlobalPreferences defined at various levels (ByHost, user, system) """ macos_dict = CFPreferencesCopyAppValue(prefs_section, BUNDLE_ID) if macos_dict is None: macos_dict = {} else: macos_dict = convert_dict(macos_dict) return macos_dict
def write_conditional(): # Read the location of the ManagedInstallDir from ManagedInstall.plist BUNDLE_ID = 'ManagedInstalls' pref_name = 'ManagedInstallDir' managedinstalldir = CFPreferencesCopyAppValue(pref_name, BUNDLE_ID) # Make sure we're outputting our information to "ConditionalItems.plist" conditionalitemspath = os.path.join(managedinstalldir, 'ConditionalItems.plist') if os.path.exists(conditionalitemspath): # "ConditionalItems.plist" exists, so read it FIRST data_dict = plistlib.readPlist(conditionalitemspath) else: # "ConditionalItems.plist" does not exist, # create an empty dict data_dict = {} external_ip = get_wan() # Write out data to "ConditionalItems.plist" data_dict['external_ip'] = external_ip plistlib.writePlist(data_dict, conditionalitemspath)
# CoreFoundation release notes for 10.6-10.8: # https://developer.apple.com/library/mac/releasenotes/DataManagement/RN-CoreFoundationOlderNotes from Foundation import CFPreferencesAppSynchronize, \ CFPreferencesCopyAppValue, \ CFPreferencesSetMultiple, \ kCFPreferencesAnyHost, \ kCFPreferencesCurrentUser major_versions = ['10', '11', 'DC', '2015'] final_prefs = {} for version in major_versions: prefs_for_vers = CFPreferencesCopyAppValue(version, 'com.adobe.Reader') if prefs_for_vers: print "Found existing key '%s'" % version # if there were preferences, then make a copy and put these in # our final_prefs we're building # - mutableCopy() isn't Python, it's Objective-C - this is because # the Objective-C wrapping around CFPreferences returns immutable # copies, and we want to add our data (EULAAccepted) to these final_prefs[version] = prefs_for_vers.mutableCopy() else: # if no prefs key for this version, create the key as an empty dict # for us to add the EULA key to print "No existing key for '%s', creating new dict" % version final_prefs[version] = {} if 'EULAAccepted' not in final_prefs[version]: