def test_nondictroot(self): test1 = "abc" test2 = [1, 2, 3, "abc"] result1 = plistlib.readPlistFromString(plistlib.writePlistToString(test1)) result2 = plistlib.readPlistFromString(plistlib.writePlistToString(test2)) self.assertEqual(test1, result1) self.assertEqual(test2, result2)
def handlePlist(self, file): print file.readlines() plistlib.readPlistFromString(file.readlines()) for line in file.readlines(): for b in line: print str(b) print str(line.replace("\0", ""))
def readPlistFromString(string): try: data = plistlib.readPlistFromString(string) except Exception as e: # Solo si tiene error data = plistlib.readPlistFromString(__fixString(string)) return __fixItems(data, __fixReadItem)
def testGetCoreStorageStateEnabled(self, get_plist_from_exec_mock): pl = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LIST_ENABLED) pl2 = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LVF_INFO_ENABLED) pl3 = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LV_INFO) get_plist_from_exec_mock.side_effect = [pl, pl2, pl3] cs = corestorage.CoreStorage() self.assertEqual(cs.GetState(), corestorage.State.ENABLED)
def testGetCoreStorageStateFailed(self, get_plist_from_exec_mock): pl = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LIST_ENABLED) pl2 = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LVF_INFO_ENABLED) pl3 = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LV_INFO) pl3['CoreStorageLogicalVolumeConversionState'] = 'Failed' get_plist_from_exec_mock.side_effect = [pl, pl2, pl3] cs = corestorage.CoreStorage() self.assertEqual(cs.GetState(), corestorage.State.FAILED)
def testGetCoreStorageStateEnabled(self): self.mox.StubOutWithMock(util, "GetPlistFromExec") pl = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LIST_ENABLED) pl2 = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LVF_INFO_ENABLED) pl3 = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LV_INFO) util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl) util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl2) util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl3) self.mox.ReplayAll() self.assertEquals(corestorage.GetState(), corestorage.State.ENABLED) self.mox.VerifyAll()
def examinePreviousSystem(sourceRoot, targetRoot, diskAccessor=None): """ Examines the old caldavd.plist and carddavd.plist to see where data lives in the previous system. """ if diskAccessor is None: diskAccessor = DiskAccessor() oldServerRootValue = None oldCalDocumentRootValue = None oldCalDataRootValue = None oldABDocumentRootValue = None uid = pwd.getpwnam("calendar").pw_uid gid = grp.getgrnam("calendar").gr_gid # Try and read old caldavd.plist oldCalConfigDir = os.path.join(sourceRoot, CALDAVD_CONFIG_DIR) oldCalPlistPath = os.path.join(oldCalConfigDir, CALDAVD_PLIST) if diskAccessor.exists(oldCalPlistPath): contents = diskAccessor.readFile(oldCalPlistPath) oldCalPlist = readPlistFromString(contents) log("Found previous caldavd plist at %s" % (oldCalPlistPath,)) oldServerRootValue = oldCalPlist.get("ServerRoot", None) oldCalDocumentRootValue = oldCalPlist.get("DocumentRoot", None) oldCalDataRootValue = oldCalPlist.get("DataRoot", None) else: log("Can't find previous calendar plist at %s" % (oldCalPlistPath,)) oldCalPlist = None # Try and read old carddavd.plist oldABConfigDir = os.path.join(sourceRoot, CARDDAVD_CONFIG_DIR) oldABPlistPath = os.path.join(oldABConfigDir, CARDDAVD_PLIST) if diskAccessor.exists(oldABPlistPath): contents = diskAccessor.readFile(oldABPlistPath) oldABPlist = readPlistFromString(contents) log("Found previous carddavd plist at %s" % (oldABPlistPath,)) oldABDocumentRootValue = oldABPlist.get("DocumentRoot", None) else: log("Can't find previous carddavd plist at %s" % (oldABPlistPath,)) oldABPlist = None return ( oldServerRootValue, oldCalDocumentRootValue, oldCalDataRootValue, oldABDocumentRootValue, uid, gid )
def testIsBootVolumeEncryptedWhenEncrypted(self, get_plist_from_exec_mock): p1 = plistlib.readPlistFromString(DISKUTIL_INFO_PLIST) p2 = plistlib.readPlistFromString(APFS_PLIST_LIST_ENCRYPTED) get_plist_from_exec_mock.side_effect = [p1, p2] volume = apfs.APFSStorage() self.assertEqual(True, volume.IsBootVolumeEncrypted()) get_plist_from_exec_mock.assert_has_calls([ mock.call(['/usr/sbin/diskutil', 'info', '-plist', '/']), mock.call(['/usr/sbin/diskutil', 'apfs', 'list', '-plist'])])
def testGetCoreStorageStateFailed(self): self.mox.StubOutWithMock(util, 'GetPlistFromExec') pl = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LIST_ENABLED) pl2 = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LVF_INFO_ENABLED) pl3 = plistlib.readPlistFromString(CORE_STORAGE_PLIST_LV_INFO) pl3['CoreStorageLogicalVolumeConversionState'] = 'Failed' util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl) util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl2) util.GetPlistFromExec(mox.In(DISKUTIL)).AndReturn(pl3) self.mox.ReplayAll() self.assertEquals(corestorage.GetState(), corestorage.State.FAILED) self.mox.VerifyAll()
def decode(self, data): # this has some sucky workarounds for odd handling # of UTF-8 data in sqlite3 try: plist = plistlib.readPlistFromString(data) return plist except ExpatError: try: plist = plistlib.readPlistFromString(data.encode('UTF-8')) return plist except ExpatError: return self.b64bz_decode(data)
def open_settings(self): if self.settings_file[:7] == 'http://': fcb = ForumCodeBlock.ForumCodeBlock() fcb.forum_url = self.settings_file fcb.block_type = 'plist' self.settings_dict = plistlib.readPlistFromString(fcb.text()) else: with open(self.settings_file, 'r') as fS: self.__sA = fS.read() self.__iS = self.__sA.find('<?xml') self.__iF = self.__sA.find('</plist>') + 8 self.settings_dict = plistlib.readPlistFromString(self.__sA[self.__iS:self.__iF]) return True
def from_string(string): try: return plistlib.readPlistFromString(string) except ExpatError: # string must have contained a TM format plist, which cannot be # parsed. Try converting it using pretty_list proc = subprocess.Popen([pretty_list, '-a'], stdin=subprocess.PIPE, stdout=subprocess.PIPE ) string, _ = proc.communicate(string) print string return plistlib.readPlistFromString(string)
def unpackage_theme(pl_string): theme_pl = plistlib.readPlistFromString(pl_string) unwrap_data(theme_pl) # Extract plist for each bplist encoded key/value for k,v in theme_pl.iteritems(): if k not in bplist_keys: continue v_plist = bplist_to_xml(v['data']) v_plist = plistlib.readPlistFromString(v_plist) unwrap_data(v_plist) theme_pl[k]['data'] = v_plist return json.dumps(theme_pl, indent=4)
def get_disk_list(self): disk_size_list = [] if sys.platform == 'darwin': # get plist of disks from diskutil list_command = ['diskutil', 'list', '-plist'] try: output = subprocess.check_output(list_command) except subprocess.CalledProcessError as err: raise Exception( "Could not get list of disks. \nError: %s" % err) list_plist = plistlib.readPlistFromString(output) disk_list = list_plist["WholeDisks"] # parse the plist for sizes. this might be able to be combined with first step eventually. for disk in disk_list: # maybe someday check for usb drives only. meh. size_command = ['diskutil', 'info', '-plist', disk] try: output = subprocess.check_output(size_command) except subprocess.CalledProcessError as err: raise Exception("Could not get disk information. \nError: %s" % err) size_plist = plistlib.readPlistFromString(output) size = self.bytes_to_mb( size_plist["TotalSize"] ) disk_path = "/dev/" + disk disk_size_list.append( (disk_path, size, "MB") ) else: disk_size_list = [] #get list of disks using lsblk list_command = ["lsblk", "-d", "-n", "-o", "NAME,SIZE,TYPE"] try: output = subprocess.check_output(list_command) except subprocess.CalledProcessError as err: raise Exception( "Could not get list of disks. Make sure you have 'lsblk' installed. \nError: %s" % err ) disk_list = output.splitlines() for disk in disk_list: disk_info = disk.split() disk_path = "/dev/" + disk_info[0] if disk_info[2] == "disk": disk_size_list.append( (disk_path, disk_info[1]) ) return disk_size_list
def test_string(self): pl = self._create() data = plistlib.writePlistToString(pl) pl2 = plistlib.readPlistFromString(data) self.assertEqual(dict(pl), dict(pl2)) data2 = plistlib.writePlistToString(pl2) self.assertEqual(data, data2)
def _available_services(): ''' Return a dictionary of all available services on the system ''' available_services = dict() for launch_dir in _launchd_paths(): for root, dirs, files in os.walk(launch_dir): for filename in files: file_path = os.path.join(root, filename) try: # This assumes most of the plist files will be already in XML format plist = plistlib.readPlist(file_path) except Exception: # If plistlib is unable to read the file we'll need to use # the system provided plutil program to do the conversion cmd = '/usr/bin/plutil -convert xml1 -o - -- "{0}"'.format(file_path) plist_xml = __salt__['cmd.run_all'](cmd)['stdout'] plist = plistlib.readPlistFromString(plist_xml) available_services[plist.Label.lower()] = { 'filename': filename, 'file_path': file_path, 'plist': plist, } return available_services
def _osx_java_homes(cls): # OSX will have a java_home tool that can be used to locate a unix-compatible java home dir. # # See: # https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/java_home.1.html # # The `--xml` output looks like so: # <?xml version="1.0" encoding="UTF-8"?> # <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" # "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> # <plist version="1.0"> # <array> # <dict> # ... # <key>JVMHomePath</key> # <string>/Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home</string> # ... # </dict> # ... # </array> # </plist> if os.path.exists(cls._OSX_JAVA_HOME_EXE): try: plist = subprocess.check_output([cls._OSX_JAVA_HOME_EXE, '--failfast', '--xml']) for distribution in plistlib.readPlistFromString(plist): home = distribution['JVMHomePath'] yield cls._Location.from_home(home) except subprocess.CalledProcessError: pass
def gatewayCommandReceived(self, command): """ Process a command via gateway.Runner @param command: GatewayAMPCommand @returns: a deferred returning a dict """ command = readPlistFromString(command) output = cStringIO.StringIO() from calendarserver.tools.gateway import Runner runner = Runner( self.store, [command], output=output ) try: yield runner.run() result = output.getvalue() output.close() except Exception as e: error = {"Error": str(e)} result = writePlistToString(error) output.close() returnValue(dict(result=result))
def getInstalledApps(): #list of apps installedApps = None #command-line for system_profiler # ->xml, mini, etc. commandLine = ['system_profiler', 'SPApplicationsDataType', '-xml', '-detailLevel', 'mini', ] #on newer OS's (10.9+) system_profiler supports a timeout if int(getOSVersion()[1]) >= 9: #add timeout commandLine.extend(['-timeout', '60']) #wrap try: #get info about all installed apps via 'system_profiler' # ->(string)output is read in as plist systemProfileInfo = plistlib.readPlistFromString(subprocess.check_output(commandLine)) #get all installed apps # ->under '_items' key installedApps = systemProfileInfo[0]['_items'] #exception except Exception, e: #reset installedApps = None
def get_collection_items(url, hurry=False): try: xml = get_page(url, hurry=hurry) lang = 1 except ValueError: # If there's a bad URL, skip this link return None # Get the tracklisting for this collection if xml: root = etree.fromstring(xml) items = root.xpath('.//itms:TrackList',namespaces={'itms':'http://www.apple.com/itms/'}) else: try: print("Trying lang=2 instead...") xml = get_page(url,2,hurry=hurry) lang = 2 except ValueError: # If there's a bad URL, skip this link return None if xml: root = etree.fromstring(xml) items = root.xpath('.') else: return None plist = plistlib.readPlistFromString(etree.tostring(items[0])) if lang == 2: #Get rid of all non-podcast-episode plist elements from the list of items to be returned. tobereturned = plist.get('items') tobereturned_norubbish = [] for i in tobereturned: if i['type'] == 'podcast-episode': tobereturned_norubbish.append(i) return tobereturned_norubbish else: return plist.get('items')
def GetPlistValue(key, secure=False, plist=None): """Returns the value of a given plist key. Args: key: string key to get from the plist. secure: boolean; True = munki secure plist, False = munki regular plist. plist: optional, str plist path to use, instead of Munki plist. Note, if plist is supplied, secure boolean is ignored. Returns: string value, or empty string if the key doesn't exist. """ if not plist: if secure: plist = DEFAULT_SECURE_MANAGED_INSTALLS_PLIST_PATH else: plist = DEFAULT_MANAGED_INSTALLS_PLIST_PATH if OBJC_OK: pl = fpl.readPlist(plist) return pl.get(key, '') # get XML output of (potential) binary plist from plutil. exit_code, plist_xml, unused_err = Exec( ['/usr/bin/plutil', '-convert', 'xml1', '-o', '-', plist]) if exit_code: logging.error('Failed to convert plist to xml1: %s', plist) return '' plist_contents = plistlib.readPlistFromString(plist_xml) return plist_contents.get(key, '')
def set_from_provision_file(self, provision_file_path): if not os.path.exists(provision_file_path): raise MobileProvisionReadException("Could not find mobile provision file at path %s" % provision_file_path) provision_dict = None with open(provision_file_path) as provision_file: provision_data = provision_file.read() start_tag = '<?xml version="1.0" encoding="UTF-8"?>' stop_tag = "</plist>" try: start_index = provision_data.index(start_tag) stop_index = provision_data.index(stop_tag, start_index + len(start_tag)) + len(stop_tag) except ValueError: raise MobileProvisionReadException("This is not a valid mobile provision file") plist_data = provision_data[start_index:stop_index] provision_dict = plistlib.readPlistFromString(plist_data) self.name = provision_dict["Name"] self.uuid = provision_dict["UUID"] self.application_identifier = ApplicationIdentifier(provision_dict["Entitlements"]["application-identifier"]) self.creation_date = provision_dict["CreationDate"] self.expiration_date = provision_dict["ExpirationDate"] self.time_to_live = provision_dict["TimeToLive"] devices_udids = provision_dict.get("ProvisionedDevices", None) self.devices_udids = devices_udids or [] self.is_appstore = devices_udids is None
def sendCommand(commandDict, configFile=None): args = [CALENDARSERVER_CONFIG] if configFile is not None: args.append("-f {}".format(configFile)) child = subprocess.Popen( args=args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) commandString = plistlib.writePlistToString(commandDict) log("Sending to calendarserver_config: {}".format(commandString)) output, error = child.communicate(input=commandString) log("Output from calendarserver_config: {}".format(output)) if child.returncode: log( "Error from calendarserver_config: {}, {}".format( child.returncode, error ) ) return None else: return plistlib.readPlistFromString(output)["result"]
def _GetRightData(right): """Get the current configuration for the requested right as a dict.""" output = subprocess.check_output( ['/usr/bin/security', 'authorizationdb', 'read', right], stderr=subprocess.PIPE) data = plistlib.readPlistFromString(output) return data
def extract_plist_data(self, name): extract_info = self.get_filename_from_ipa(name) zip_obj = extract_info['zip_obj'] plist_filename = extract_info['filename'] data = {} if plist_filename == '': self.errors.append('%s.plist file not found in IPA' % name) else: content = zip_obj.read(plist_filename) if ParseIPA.xml_rx.match(content): data = plistlib.readPlistFromString(content) else: self.temp_directory = tempfile.mkdtemp() zip_obj.extract(plist_filename, self.temp_directory) fullpath_plist = '%s/%s' % (self.temp_directory, plist_filename) os_info = os.uname() if os_info[0] == 'Linux': cmd = 'plutil -i "%s" -o "%s"' % (fullpath_plist, fullpath_plist) else: cmd = 'plutil -convert xml1 "%s"' % fullpath_plist if self.verbose: pprint(cmd) os.system(cmd) data = plistlib.readPlist(fullpath_plist) # end if plist == '' return data
def _machine_id(): """ for informational purposes, try to get a machine unique id thing """ if platform.isLinux(): try: # why this? see: http://0pointer.de/blog/projects/ids.html with open('/var/lib/dbus/machine-id', 'r') as f: return f.read().strip() except: # Non-dbus using Linux, get a hostname return socket.gethostname() elif platform.isMacOSX(): # Get the serial number of the platform import plistlib plist_data = subprocess.check_output(["ioreg", "-rd1", "-c", "IOPlatformExpertDevice", "-a"]) if six.PY2: # Only API on 2.7 return plistlib.readPlistFromString(plist_data)[0]["IOPlatformSerialNumber"] else: # New, non-deprecated 3.4+ API return plistlib.loads(plist_data)[0]["IOPlatformSerialNumber"] else: # Something else, just get a hostname return socket.gethostname()
def tooltip(self, message="", format="text", transparent=False): try: data = plistlib.readPlistFromString(message) if data is not None: message = data[format] except ExpatError, reason: pass
def popup(self, **kwargs): suggestions = plistlib.readPlistFromString(kwargs["suggestions"]) if kwargs.get("returnChoice", False): def sendSelectedSuggestion(suggestion): if suggestion is not None: self.sendResult(suggestion) else: self.sendResult({}) self.application.currentEditor().showCompleter( suggestions=suggestions["suggestions"], source="external", alreadyTyped=kwargs.get("alreadyTyped"), caseInsensitive=kwargs.get("caseInsensitive", True), callback=sendSelectedSuggestion, ) else: self.application.currentEditor().showCompleter( suggestions=suggestions["suggestions"], source="external", alreadyTyped=kwargs.get("alreadyTyped"), caseInsensitive=kwargs.get("caseInsensitive", True), ) self.sendResult()
def systemReport(): spx = {} # This is our key value schema SPHardwareDataType = { 'platform_UUID': 'platform_UUID', } _dataTypes = { 'SPHardwareDataType': SPHardwareDataType, } dataTypes = _dataTypes.keys() # run the system_profiler command with data types arguments = [system_profiler,"-xml"] + dataTypes getspx = subprocess.Popen(arguments, stdout=subprocess.PIPE) spxOut, err = getspx.communicate() # Someone give me an example of doing read from string via bridge and I will fix this #spxNSString = NSString.alloc().initWithString_(spxOut) #spxData = NSData.dataWithData_(spxNSString.dataUsingEncoding_(NSUTF8StringEncoding)) #rootObject = NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_(spxData,NSPropertyListImmutable,None,None) rootObject = plistlib.readPlistFromString(spxOut) # Parse datatype top level keys below for array in rootObject: for _dataType in _dataTypes: if array['_dataType'] == _dataType: _dataTypeSchema = _dataTypes[_dataType] for key in _dataTypeSchema: for item in array['_items']: # add a key to our dict per the schema spx[key] = item[_dataTypeSchema[key]] return spx
def wait_for_input(self, **kwargs): try: parameters = plistlib.readPlistFromString(kwargs["parameters"]) except ExpatError: parameters = {} instance = self.dialogInstance(int(kwargs["token"])) self.sendResult()
def fact(): '''Returns the user profiles''' profiles = [] console_user = SCDynamicStoreCopyConsoleUser(None, None, None)[0] if os.getuid() == 0: cmd = [ 'sudo', '-u', console_user, '/usr/bin/profiles', '-Lo', 'stdout-xml' ] else: cmd = ['/usr/bin/profiles', '-Lo', 'stdout-xml'] task = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out = task.stdout.read() if out: d = plistlib.readPlistFromString(out) if d: for i in d[console_user]: profiles.append(i['ProfileDisplayName']) return {factoid: profiles}
def by_volumes_from_disks(disk): """Checks value of "VolumesFromDisks" to determine if a disk was secure erased. Args: disk (str): Disk. Returns: True if length of "VolumesFromDisks" is 0. False otherwise. """ # <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> # Run command. cmd = ['diskutil', 'list', '-plist', disk] output = sp.check_output(cmd) # <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> # Get value of "VolumesFromDisks". vols_from_disks = plistlib.readPlistFromString(output)['VolumesFromDisks'] # <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> # If length of value is 0, return True. if len(vols_from_disks) == 0: logger.info("Secure erase successful as per byAllVolumesFromDisks()") return True logger.info("Secure erase failed as per byAllVolumesFromDisks()") return False
def runCommand( self, command, error=False, script="calendarserver_command_gateway", additionalArgs=None, parseOutput=True ): """ Run the given command by feeding it as standard input to calendarserver_command_gateway in a subprocess. """ if isinstance(command, unicode): command = command.encode("utf-8") sourceRoot = os.path.dirname( os.path.dirname(os.path.dirname(os.path.dirname(__file__))) ) cmd = script # assumes it's on PATH args = [cmd, "-f", self.configFileName] if error: args.append("--error") if additionalArgs: args.extend(additionalArgs) cwd = sourceRoot deferred = Deferred() reactor.spawnProcess(CapturingProcessProtocol(deferred, command), cmd, args, env=os.environ, path=cwd) output = yield deferred if parseOutput: try: plist = readPlistFromString(output) returnValue(plist) except xml.parsers.expat.ExpatError, e: # @UndefinedVariable print("Error (%s) parsing (%s)" % (e, output)) raise
def fromPList(cls, s): u""" >>> tl = AList([2, 3, 4]) >>> pl = tl.asPList() >>> tl2 = A.fromPList(pl) >>> tl2 <AList:[2, 3, 4]> >>> td = ADict(dict(a=1, b=2)) >>> pl = td.asPList() >>> td2 = A.fromPList(pl) >>> td2 <ADict:{'a': 1, 'b': 2}> >>> x = A.fromPList("<integer>4</integer>") Traceback (most recent call last): ... TypeError: Top level plist object must be list or dict, not int """ obj = plistlib.readPlistFromString(s) if isinstance(obj, dict): return cls._getDictClass()(obj) elif isinstance(obj, (list, tuple)): return cls._getListClass()(obj) raise TypeError("Top level plist object must be list or dict, not %s" % type(obj).__name__)
def get_template_dct(str_path): """Find a an iThoughts plist in an .itm file or in a zipped .itmz file""" # if no pth component, assume the same path as the script if (str_path.count('/') < 1): str_path = ''.join([os.path.dirname(sys.argv[0]), '/', str_path]) if (os.path.isfile(str_path)): if (str_path[-1].lower() == 'z'): if (zipfile.is_zipfile(str_path)): zf = zipfile.ZipFile(str_path, 'r') lst_map = zf.namelist() if (len(lst_map) > 0): str_map_file = 'map.itm' if (lst_map[0] == str_map_file): data = zf.read(str_map_file) dct = plistlib.readPlistFromString(data) return dct else: dct = plistlib.readPlist(str_path) return dct else: sys.exit('Template not found: ' + str_path)
def download_and_parse_sucatalog(sucatalog, workdir, ignore_cache=False): '''Downloads and returns a parsed softwareupdate catalog''' try: localcatalogpath = replicate_url( sucatalog, root_dir=workdir, ignore_cache=ignore_cache) except ReplicationError as err: print('Could not replicate %s: %s' % (sucatalog, err), file=sys.stderr) exit(-1) if os.path.splitext(localcatalogpath)[1] == '.gz': with gzip.open(localcatalogpath) as the_file: content = the_file.read() try: catalog = plistlib.readPlistFromString(content) return catalog except ExpatError as err: print('Error reading %s: %s' % (localcatalogpath, err), file=sys.stderr) exit(-1) else: try: catalog = plistlib.readPlist(localcatalogpath) return catalog except (OSError, IOError, ExpatError) as err: print('Error reading %s: %s' % (localcatalogpath, err), file=sys.stderr) exit(-1)
def write_mobileconfig_and_add_to_repo(given_mobileconfig_dict): '''Writes the given mobileconfig to the working directory then imports it into munki.''' this_dir = os.path.dirname(os.path.realpath(__file__)) print "Working dir is %s." % this_dir mobileconfig_file_path = os.path.join(MUNKI_PKGS_PATH, CONFIG_PROFILE_FILE_NAME) plistlib.writePlist(given_mobileconfig_dict, mobileconfig_file_path) print "Wrote mobileconfig to %s." % mobileconfig_file_path pkginfo_file_path = os.path.join(MUNKI_PKGSINFO_PATH, PKGSINFO_FILE_NAME) print "Pkginfo will be %s." % pkginfo_file_path # Call makepkginfo: try: output = subprocess.check_output([ '/usr/local/munki/makepkginfo', '--name=%s' % CONFIG_PROFILE_FILE_NAME, '--catalog=configuration', '--unattended_install', '--pkgvers=%s' % CONFIG_PROFILE_VERSION, mobileconfig_file_path ]) output_dict = plistlib.readPlistFromString(output) plistlib.writePlist(output_dict, pkginfo_file_path) except subprocess.CalledProcessError: print "Error creating pkginfo!"
def main(): parser = argparse.ArgumentParser() parser.add_argument('-d', '--device') args = parser.parse_args() data = subprocess.check_output(['system_profiler', '-xml', 'SPUSBDataType']) usb_data = plistlib.readPlistFromString(data) for _item in usb_data[0]['_items']: for item in _item['_items']: add_device(item) if args.device: matches = filter(lambda d: d.startswith(args.device), devices) if len(matches) == 0: sys.exit(1) for match in matches: print match sys.exit(0) for device in devices: print device
def by_all_disks(disk): """Checks the value of "AllDisks" to determine if a disk was secure erased. Args: disk (str): Disk. Returns: True if length of "AllDisks" is 1. False otherwise. """ # <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> # Run command. cmd = ['diskutil', 'list', '-plist', disk] output = sp.check_output(cmd) # <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> # Get value of "AllDisks" all_disks = plistlib.readPlistFromString(output)['AllDisks'] # <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><> # If length of "AllDisks" is 1, return True. if len(all_disks) == 1: logger.info("Secure erase successful as per by_all_disks()") return True logger.info("Secure erase failed as per by_all_disks()") return False
def sendCommand(commandDict, configFile=None): args = [CALENDARSERVER_CONFIG] if configFile is not None: args.append("-f {}".format(configFile)) child = subprocess.Popen( args=args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) commandString = plistlib.writePlistToString(commandDict) log("Sending to calendarserver_config: {}".format(commandString)) output, error = child.communicate(input=commandString) log("Output from calendarserver_config: {}".format(output)) if child.returncode: log("Error from calendarserver_config: {}, {}".format( child.returncode, error)) return None else: return plistlib.readPlistFromString(output)["result"]
def _available_services(): ''' Return a dictionary of all available services on the system ''' available_services = dict() for launch_dir in _launchd_paths(): for root, dirs, files in os.walk(launch_dir): for filename in files: file_path = os.path.join(root, filename) # Follow symbolic links of files in _launchd_paths true_path = os.path.realpath(file_path) # ignore broken symlinks if not os.path.exists(true_path): continue try: # This assumes most of the plist files will be already in XML format with salt.utils.fopen(file_path): plist = plistlib.readPlist(true_path) except Exception: # If plistlib is unable to read the file we'll need to use # the system provided plutil program to do the conversion cmd = '/usr/bin/plutil -convert xml1 -o - -- "{0}"'.format( true_path) plist_xml = __salt__['cmd.run_all']( cmd, python_shell=False)['stdout'] plist = plistlib.readPlistFromString(plist_xml) available_services[plist.Label.lower()] = { 'filename': filename, 'file_path': true_path, 'plist': plist, } return available_services
def installed_core_resource_packages(): """ Returns a list of installed Office core resource packages These packages have the following identifier format: com.microsoft.office.<language>.core_resources.pkg.<version> """ cmd = ["/usr/sbin/pkgutil", "--pkgs-plist"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (results, err) = p.communicate() if p.returncode != 0: return [] all_package_identifiers = plistlib.readPlistFromString(results) re_core_resource = re.compile( r'^com\.microsoft\.office\.(?P<language_code>.*)\.core_resources\.pkg\.(?P<version>[0-9\.]+)(.update$|$)' ) matching_packages = [] for identifier in all_package_identifiers: m = re.match(re_core_resource, identifier) if m and m.group('language_code'): item_info = info_for_package_identifier(identifier) item_info['language'] = m.group('language_code') matching_packages.append(item_info) return matching_packages
def downloadCurrentVersion(): """ Download the current version (dmg) and mount it """ if PY2: path = "https://static.typemytype.com/drawBot/DrawBotPy2.dmg" else: path = "https://static.typemytype.com/drawBot/DrawBot.dmg" try: # download and mount cmds = ["hdiutil", "attach", "-plist", path] popen = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = popen.communicate() if popen.returncode != 0: raise DrawBotError("Mounting failed") output = plistlib.readPlistFromString(out) dmgPath = None for item in output["system-entities"]: if "mount-point" in item: dmgPath = item["mount-point"] break AppKit.NSWorkspace.sharedWorkspace().openFile_(dmgPath) except: print("Something went wrong while downloading %s" % path)
def mountdmg(dmgpath, use_shadow=False): """ Attempts to mount the dmg at dmgpath and returns a list of mountpoints If use_shadow is true, mount image with shadow file """ mountpoints = [] dmgname = os.path.basename(dmgpath) stdin = '' if DMGhasSLA(dmgpath): stdin = 'Y\n' cmd = [ '/usr/bin/hdiutil', 'attach', dmgpath, '-mountRandom', '/tmp', '-nobrowse', '-plist', '-owners', 'on' ] if use_shadow: shadowname = dmgname + '.shadow' shadowpath = os.path.join(TMPDIR, shadowname) cmd.extend(['-shadow', shadowpath]) else: shadowpath = None proc = subprocess.Popen(cmd, bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (pliststr, err) = proc.communicate(stdin) if proc.returncode: print >> sys.stderr, 'Error: "%s" while mounting %s.' % (err, dmgname) if pliststr: plist = plistlib.readPlistFromString(pliststr) for entity in plist['system-entities']: if 'mount-point' in entity: mountpoints.append(entity['mount-point']) return mountpoints, shadowpath
def status(job_label, runas=None): ''' Return the status for a service, returns a bool whether the service is running. CLI Example: .. code-block:: bash salt '*' service.status <service label> ''' service = _service_by_name(job_label) lookup_name = service['plist']['Label'] if service else job_label launchctl_data = _get_launchctl_data(lookup_name, runas=runas) if launchctl_data: if BEFORE_YOSEMITE: return 'PID' in dict(plistlib.readPlistFromString(launchctl_data)) else: pattern = '"PID" = [0-9]+;' return True if re.search(pattern, launchctl_data) else False else: return False
def getdeviceinfo(): deviceinfo = {} try: cmd = ['/usr/sbin/system_profiler', '-xml', 'SPHardwareDataType'] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = proc.communicate() plist = plistlib.readPlistFromString(output) deviceinfo['type'] = plist[0]['_items'][0][ 'machine_name'] #e.g. MacBook Pro deviceinfo['model'] = plist[0]['_items'][0][ 'machine_model'] #e.g. MacBookPro14,3 deviceinfo['uuid'] = plist[0]['_items'][0]['platform_UUID'] deviceinfo['serial'] = plist[0]['_items'][0]['serial_number'] except Exception as e: #noqa oslog('Error getting system info via system_profiler') oslog(str(e)) depnotify('Command: WindowStyle: Activate') depnotify('Command: Quit: Error getting system info') cleanup() else: deviceinfo['osvers'] = platform.mac_ver()[0] #OS Version, e.g. 10.14.1 return deviceinfo
def __init__(self, provisioning_profile_path): """Initializes the ProvisioningProfile with data from profile file.""" self._path = provisioning_profile_path self._data = plistlib.readPlistFromString(subprocess.check_output([ 'xcrun', 'security', 'cms', '-D', '-u', 'certUsageAnyCA', '-i', provisioning_profile_path]))
def Parse(self): try: self.plist = plistlib.readPlistFromString(self._xml) except xml.parsers.expat.ExpatError as e: raise Error(str(e))
plistLines = plistDump.splitlines() if len(plistLines) < 3 or plistLines[1] != ("Contents of (%s,%s) section" % (segmentName, sectionName)): raise CheckException("tool %s / %s section dump malformed (1)" % (segmentName, sectionName), toolPath) del plistLines[0:2] try: bytes = [] for line in plistLines: # line looks like this: # # '0000000100000b80\t3c 3f 78 6d 6c 20 76 65 72 73 69 6f 6e 3d 22 31 ' columns = line.split("\t") assert len(columns) == 2 for hexStr in columns[1].split(): bytes.append(int(hexStr, 16)) plist = plistlib.readPlistFromString(bytearray(bytes)) except: raise CheckException("tool %s / %s section dump malformed (2)" % (segmentName, sectionName), toolPath) # Check the root of the property list. if not isinstance(plist, dict): raise CheckException("tool %s / %s property list root must be a dictionary" % (segmentName, sectionName), toolPath) return plist def checkStep1(appPath): """Checks that the app and the tool are both correctly code signed.""" if not os.path.isdir(appPath): raise CheckException("app not found", appPath)
def parse_plist(catalog_data): if sys.version_info > (3, 0): root = plistlib.loads(catalog_data) else: root = plistlib.readPlistFromString(catalog_data) return root
def get_mso2011update_info(self): """Gets info about an Office 2011 update from MS metadata.""" if "base_url" in self.env: base_url = self.env["base_url"] else: culture_code = self.env.get("culture_code", CULTURE_CODE) base_url = BASE_URL % culture_code version_str = self.env.get("version") if not version_str: version_str = "latest" # Get metadata URL req = urllib2.Request(base_url) # Add the MAU User-Agent, since MAU feed server seems to explicitly block # a User-Agent of 'Python-urllib/2.7' - even a blank User-Agent string # passes. req.add_header( "User-Agent", "Microsoft%20AutoUpdate/3.0.2 CFNetwork/720.2.4 Darwin/14.1.0 (x86_64)" ) try: fref = urllib2.urlopen(req) data = fref.read() fref.close() except BaseException as err: raise ProcessorError("Can't download %s: %s" % (base_url, err)) metadata = plistlib.readPlistFromString(data) if version_str == "latest": # Office 2011 update metadata is a list of dicts. # we need to sort by date. sorted_metadata = sorted(metadata, key=itemgetter('Date')) # choose the last item, which should be most recent. item = sorted_metadata[-1] else: # we've been told to find a specific version. Unfortunately, the # Office2011 update metadata items don't have a version attibute. # The version is only in text in the update's Title. So we look for # that... # Titles are in the format "Office 2011 x.y.z Update" padded_version_str = " " + version_str + " " matched_items = [ item for item in metadata if padded_version_str in item["Title"] ] if len(matched_items) != 1: raise ProcessorError( "Could not find version %s in update metadata. " "Updates that are available: %s" % (version_str, ", ".join( ["'%s'" % item["Title"] for item in metadata]))) item = matched_items[0] self.env["url"] = item["Location"] self.env["pkg_name"] = item["Payload"] self.output("Found URL %s" % self.env["url"]) self.output("Got update: '%s'" % item["Title"]) # now extract useful info from the rest of the metadata that could # be used in a pkginfo pkginfo = {} pkginfo["description"] = "<html>%s</html>" % item["Short Description"] pkginfo["display_name"] = item["Title"] max_os = self.value_to_os_version_string(item['Max OS']) min_os = self.value_to_os_version_string(item['Min OS']) if max_os != "0.0.0": pkginfo["maximum_os_version"] = max_os if min_os != "0.0.0": pkginfo["minimum_os_version"] = min_os installs_items = self.get_installs_item_from_update(item) if installs_items: pkginfo["installs"] = installs_items requires = self.get_requires_from_update(item) if requires: pkginfo["requires"] = requires self.output("Update requires previous update version %s" % requires[0].split("-")[1]) pkginfo['name'] = self.env.get("munki_update_name", MUNKI_UPDATE_NAME) self.env["additional_pkginfo"] = pkginfo self.output("Additional pkginfo: %s" % self.env["additional_pkginfo"])
def validate_pairing(self): pair_record = None certPem = None privateKeyPem = None if sys.platform == "win32": folder = os.environ["ALLUSERSPROFILE"] + "/Apple/Lockdown/" elif sys.platform == "darwin": folder = "/var/db/lockdown/" elif len(sys.platform) >= 5: if sys.platform[0:5] == "linux": folder = "/var/lib/lockdown/" try: pair_record = plistlib.readPlist(folder + "%s.plist" % self.identifier) except: pair_record = None if pair_record: self.logger.info("Using iTunes pair record: %s.plist", self.identifier) certPem = pair_record["HostCertificate"].data privateKeyPem = pair_record["HostPrivateKey"].data else: self.logger.warn("No iTunes pairing record found for device %s", self.identifier) self.logger.warn("Looking for pymobiledevice pairing record") record = readHomeFile(HOMEFOLDER, "%s.plist" % self.identifier) if record: pair_record = plistlib.readPlistFromString(record) self.logger.info( "Found pymobiledevice pairing record for device %s", self.udid) certPem = pair_record["HostCertificate"].data privateKeyPem = pair_record["HostPrivateKey"].data else: self.logger.warn( "No pymobiledevice pairing record found for device %s", self.identifier) return False self.record = pair_record ValidatePair = { "Label": self.label, "Request": "ValidatePair", "PairRecord": pair_record } self.c.sendPlist(ValidatePair) r = self.c.recvPlist() if not r or "Error" in r: pair_record = None self.logger.error("ValidatePair fail: %s", ValidatePair) return False self.hostID = pair_record.get("HostID", self.hostID) self.SystemBUID = pair_record.get("SystemBUID", self.SystemBUID) d = { "Label": self.label, "Request": "StartSession", "HostID": self.hostID, 'SystemBUID': self.SystemBUID } self.c.sendPlist(d) startsession = self.c.recvPlist() self.SessionID = startsession.get("SessionID") if startsession.get("EnableSessionSSL"): sslfile = self.identifier + "_ssl.txt" sslfile = writeHomeFile(HOMEFOLDER, sslfile, certPem + "\n" + privateKeyPem) self.c.ssl_start(sslfile, sslfile) self.paired = True return True
def plist_analysis(src): #Plist Analysis try: print("[LOG] iOS Info.plist Analysis Started") plist_info = {} plist_info["bin_name"] = "" plist_info["bin"] = "" plist_info["id"] = "" plist_info["ver"] = "" plist_info["sdk"] = "" plist_info["pltfm"] = "" plist_info["min"] = "" plist_info["plist_xml"] = "" plist_info["permissions"] = [] plist_info["inseccon"] = [] info_plist_content = '' xml_file = os.path.join(src, "Info.plist") if not isFileExists(xml_file): print( "[WARNING] Cannot find Info.plist file. Skipping Plist Analysis." ) else: info_plist_content = convert_bin_xml(xml_file) #Generic Plist Analysis plist_info["plist_xml"] = info_plist_content if isinstance(info_plist_content, unicode): info_plist_content = info_plist_content.encode("utf-8", "replace") plist_obj = plistlib.readPlistFromString(info_plist_content) if "CFBundleDisplayName" in plist_obj: plist_info["bin_name"] = plist_obj["CFBundleDisplayName"] else: plist_info["bin_name"] = plist_obj["CFBundleName"] if "CFBundleExecutable" in plist_obj: plist_info["bin"] = plist_obj["CFBundleExecutable"] if "CFBundleIdentifier" in plist_obj: plist_info["id"] = plist_obj["CFBundleIdentifier"] if "CFBundleVersion" in plist_obj: plist_info["ver"] = plist_obj["CFBundleVersion"] if "DTSDKName" in plist_obj: plist_info["sdk"] = plist_obj["DTSDKName"] if "DTPlatformVersion" in plist_obj: plist_info["pltfm"] = plist_obj["DTPlatformVersion"] if "MinimumOSVersion" in plist_obj: plist_info["min"] = plist_obj["MinimumOSVersion"] # Check possible app-permissions plist_info["permissions"] = __check_permissions(plist_obj) plist_info["inseccon"] = __check_insecure_connections(plist_obj) result = [] result.append(plist_info["bin_name"]) result.append(plist_info["bin"]) result.append(plist_info["id"]) result.append(plist_info["ver"]) result.append(plist_info["sdk"]) result.append(plist_info["pltfm"]) result.append(plist_info["min"]) result.extend(plist_info["permissions"]) result.extend(plist_info["inseccon"]) return (plist_info, 'InfoPlist') except: print("[ERROR] - Reading from Info.plist")
def test_gh463(self): """https://github.com/IronLanguages/ironpython2/issues/463""" import plistlib x = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>A</key><string>B</string></dict></plist>' self.assertEquals(plistlib.readPlistFromString(x), {'A': 'B'})
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2009 Doug Hellmann. All rights reserved. # """ """ #end_pymotw_header import plistlib import pprint DATA = """<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>binary_data</key> <data> VGhpcyBkYXRhIGhhcyBhbiBlbWJlZGRlZCBudWxsLiAA </data> </dict> </plist> """ d = plistlib.readPlistFromString(DATA) print repr(d['binary_data'].data)
'-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog') def make_sparse_image(volume_name, output_path): '''Make a sparse disk image we can install a product to''' cmd = [ '/usr/bin/hdiutil', 'create', '-size', '8g', '-fs', 'HFS+', '-volname', volume_name, '-type', 'SPARSE', '-plist', output_path ] try: output = subprocess.check_output(cmd) except subprocess.CalledProcessError, err: print >> sys.stderr, err exit(-1) try: return plistlib.readPlistFromString(output)[0] except IndexError, err: print >> sys.stderr, 'Unexpected output from hdiutil: %s' % output exit(-1) except ExpatError, err: print >> sys.stderr, 'Malformed output from hdiutil: %s' % output print >> sys.stderr, err exit(-1) def make_compressed_dmg(app_path, diskimagepath): """Returns path to newly-created compressed r/o disk image containing Install macOS.app""" print('Making read-only compressed disk image containing %s...' % os.path.basename(app_path))
def _decode(self, obj, context): return plistlib.readPlistFromString(obj)
# Build the connection response_handle = urllib2.urlopen(request) try: response = response_handle.read() except HTTPError, e: raise ProcessorError("Invalid adam-id %s" % e) response_handle.close() # Currently returning the raw response # Initial analysis: # - It appears that applications that need updating will be under the 'incompatible-items' key # - 'version-external-identifiers' is a list of historical versions, in order # - 'version-external-identifier' is the current version # - 'current-version' is the CFBundleShortVersionString # - 'bundle-id' is the CFBundleIdentifier # - 'preflight' is a *very* interesting 'pfpkg'. See details at bottom. return plistlib.readPlistFromString(response) # # End of pudquick code # __all__ = ["AppStoreUpdateChecker"] class AppStoreUpdateChecker(Processor): description = "Check a given Mac App Store app for updates." input_variables = { "app_item": { "required": True, "description": "Path to a local Mac App Store app.",
def _get_system_profiler(data_type): """Returns an XML about the system display properties.""" sp = subprocess.check_output(['system_profiler', data_type, '-xml']) return plistlib.readPlistFromString(sp)[0].get('_items', [])
def raw_to_object(self, raw): return plistlib.readPlistFromString(raw)