Python plistlib 模块,readPlistFromString() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用plistlib.readPlistFromString()

项目:whatsapp-rest-webservice    作者:svub    | 项目源码 | 文件源码
def parse(self, xml, pvars):

        #tmp = minidom.parseString(xml)

        if sys.version_info >= (3, 0):
            pl = plistlib.readPlistFromBytes(xml.encode());
        else:
            pl = plistlib.readPlistFromString(xml);

        parsed= {}
        pvars = self.getVars(pvars)

        for k,v in pvars.items():
            parsed[k] = pl[k] if  k in pl else None

        return parsed;
项目:qt-xcodeproj-embeded-frameworks    作者:lukevear    | 项目源码 | 文件源码
def Load(cls, path, pure_python=False):
        if pure_python:
            import openstep_parser as osp
            tree = osp.OpenStepDecoder.ParseFromFile(open(path, 'r'))
        else:
            cls.plutil_path = os.path.join(os.path.split(__file__)[0], 'plutil')

            if not os.path.isfile(XcodeProject.plutil_path):
                cls.plutil_path = 'plutil'

            # load project by converting to xml and then convert that using plistlib
            p = subprocess.Popen([XcodeProject.plutil_path, '-convert', 'xml1', '-o', '-', path], stdout=subprocess.PIPE)
            stdout, stderr = p.communicate()

            # If the plist was malformed, return code will be non-zero
            if p.returncode != 0:
                print stdout
                return None

            tree = plistlib.readPlistFromString(stdout)

        return XcodeProject(tree, path)
项目:appleLoops    作者:carlashley    | 项目源码 | 文件源码
def readPlistFromString(data):
    '''Read a plist data from a string. Return the root object.'''
    try:
        plistData = buffer(data)
    except TypeError, err:
        raise NSPropertyListSerializationException(err)
    dataObject, dummy_plistFormat, error = (
        NSPropertyListSerialization.
        propertyListFromData_mutabilityOption_format_errorDescription_(
            plistData, NSPropertyListMutableContainers, None, None))
    if dataObject is None:
        if error:
            error = error.encode('ascii', 'ignore')
        else:
            error = "Unknown error"
        raise NSPropertyListSerializationException(error)
    else:
        return dataObject


# Requests
项目:appleLoops    作者:carlashley    | 项目源码 | 文件源码
def local_version(self, pkg_id):
        cmd = ['/usr/sbin/pkgutil', '--pkg-info-plist', pkg_id]
        (result, error) = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()  # NOQA

        if result:
            try:
                ver = plistlib.readPlistFromString(result)['pkg-version']
            except:
                # If the plist can't be read, or throws an exception, the package is probably not installed.  # NOQA
                ver = '0.0.0'

        if error:
            # If there is an error, then the package is probably not installed.
            # Unlikely to happen, because Apple seems to send stderr to stdout here.  # NOQA
            ver = '0.0.0'

        return ver
项目:macOS-Security-and-Privacy-Guide    作者:ManuGutierrez    | 项目源码 | 文件源码
def LoadPlist(filename):
  """Plists can be read with plistlib."""
  # creating our own data
  data = None

  try:
    p = subprocess.Popen(
        ['/usr/bin/plutil', '-convert', 'xml1', '-o', '-', filename],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out_data, err_data = p.communicate()
  except IOError as e:
    # file could not be found
    print e

  if(p.returncode == 0):
      data = plistlib.readPlistFromString(out_data)

  return data
项目:iOS-private-api-checker    作者:NetEaseGame    | 项目源码 | 文件源码
def extract_provision_data(self):
        extract_info = self.get_filename_from_ipa('Provision')
        zip_obj = extract_info['zip_obj']
        provision_filename = extract_info['filename']

        data = {}
        if provision_filename == '':
            self.errors.append('embedded.mobileprovision file not found in IPA')
        else:
            content = zip_obj.read(provision_filename)
            match = ParseIPA.provision_xml_rx.search(content)
            if (match is not None):
                provision_xml_content = match.group()
                data = plistlib.readPlistFromString(provision_xml_content)
            else:
                self.errors.append('unable to parse embedded.mobileprovision file')

        self.provision_data = data
    # end extract_provision_data
项目:Indigo-MyQ    作者:FlyingDiver    | 项目源码 | 文件源码
def _readPluginInfoFromArchive(self, zipfile):
        topdir = zipfile.namelist()[0]

        # read and the plugin info contained in the zipfile
        plistFile = os.path.join(topdir, self.path, 'Contents', 'Info.plist')
        self._debug('Reading plugin info: %s' % plistFile)

        plistData = zipfile.read(plistFile)
        if (plistData == None):
            raise Exception('Unable to read new plugin info')

        plist = plistlib.readPlistFromString(plistData)

        return self._buildPluginInfo(plist)

    #---------------------------------------------------------------------------
    # verifies the provided plugin info matches what we expect
项目:installapplications    作者:erikng    | 项目源码 | 文件源码
def checkreceipt(packageid):
    try:
        cmd = ['/usr/sbin/pkgutil', '--pkg-info-plist', packageid]
        proc = subprocess.Popen(cmd, stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output = proc.communicate()
        receiptout = output[0]
        if receiptout:
            plist = plistlib.readPlistFromString(receiptout)
            version = plist['pkg-version']
        else:
            version = '0.0.0.0.0'
        return version
    except Exception:
        version = '0.0.0.0.0'
        return version
项目:rules_apple    作者:bazelbuild    | 项目源码 | 文件源码
def _plisttool_result(control):
  """Helper function that runs PlistTool with the given control struct.

  This function inserts a StringIO object as the control's "output" key and
  returns the dictionary containing the result of the tool after parsing it
  from that StringIO.

  Args:
    control: The control struct to pass to PlistTool. See the module doc for
        the plisttool module for a description of this format.
  Returns:
    The dictionary containing the result of the tool after parsing it from
    the in-memory string file.
  """
  output = StringIO.StringIO()
  control['output'] = output
  control['target'] = _testing_target

  tool = plisttool.PlistTool(control)
  tool.run()

  return plistlib.readPlistFromString(output.getvalue())
项目:alexa-hue-bridge    作者:IndigoDomotics    | 项目源码 | 文件源码
def _readPluginInfoFromArchive(self, zipfile):
        topdir = zipfile.namelist()[0]

        # read and the plugin info contained in the zipfile
        plistFile = os.path.join(topdir, self.path, 'Contents', 'Info.plist')
        self._debug('Reading plugin info: %s' % plistFile)

        plistData = zipfile.read(plistFile)
        if (plistData == None):
            raise Exception('Unable to read new plugin info')

        plist = plistlib.readPlistFromString(plistData)

        return self._buildPluginInfo(plist)

    #---------------------------------------------------------------------------
    # verifies the provided plugin info matches what we expect
项目:unearth    作者:chilcote    | 项目源码 | 文件源码
def fact():
    '''Returns the modification date of the gatekeeper package'''
    result = 'None'

    try:
        gkpkgs = subprocess.check_output(['/usr/sbin/pkgutil',
                                        '--pkgs=.*Gatekeeper.*'])
        dates = []
        for pkgid in gkpkgs.splitlines():
            pkginfo_plist = subprocess.check_output(['/usr/sbin/pkgutil',
                                                     '--pkg-info-plist', pkgid])
            pkginfo       = plistlib.readPlistFromString(pkginfo_plist)
            dates.append(pkginfo['install-time'])
        result = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(max(dates)))
    except (OSError, IOError, subprocess.CalledProcessError):
        pass

    return {factoid: result}
项目:unearth    作者:chilcote    | 项目源码 | 文件源码
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}
项目:unearth    作者:chilcote    | 项目源码 | 文件源码
def fact():
    '''Returns the keyboard localization'''
    result = ''

    try:
        proc = subprocess.Popen(['/usr/sbin/ioreg',
                                 '-rln',
                                 'AppleHIDKeyboardEventDriverV2',
                                 '-a'],
                                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output, _ = proc.communicate()
    except (IOError, OSError):
        result = 'Unknown'

    if output:
        result = plistlib.readPlistFromString(output)[0].get('KeyboardLanguage')

    return {factoid: result.strip()}
项目:unearth    作者:chilcote    | 项目源码 | 文件源码
def fact():
    '''Returns the battery health'''

    result = 'None'

    try:
        proc = subprocess.Popen(
                ['/usr/sbin/ioreg', '-r', '-c', 'AppleSmartBattery', '-a'],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
                )
        stdout, _ = proc.communicate()
        if stdout:
            d = plistlib.readPlistFromString(stdout)[0]
            result = 'Healthy' if not d['PermanentFailureStatus'] else 'Failing'
    except (IOError, OSError):
        pass

    return {factoid: result}
项目:unearth    作者:chilcote    | 项目源码 | 文件源码
def fact():
    '''Returns the last date mrt was updated'''
    result = 'None'

    try:
        cmd = ['/usr/sbin/pkgutil', '--pkgs=.*MRT.*']
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        (pkgs, stderr) = proc.communicate()

        if pkgs:
            dates = []
            for pkgid in pkgs.splitlines():
                pkginfo_plist = subprocess.check_output(['/usr/sbin/pkgutil',
                                                        '--pkg-info-plist',
                                                        pkgid])
                pkginfo = plistlib.readPlistFromString(pkginfo_plist)
                dates.append(pkginfo['install-time'])

            result = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(max(dates)))

    except (OSError, IOError):
        pass

    return {factoid: result}
项目:unearth    作者:chilcote    | 项目源码 | 文件源码
def fact():
    '''Returns the boot rom version'''

    result = 'None'

    try:
        proc = subprocess.Popen(
                ['/usr/sbin/system_profiler', 'SPHardwareDataType', '-xml'],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
                )
        stdout, _ = proc.communicate()
    except (IOError, OSError):
        stdout = None

    if stdout:
        d = plistlib.readPlistFromString(stdout.strip())
        result = d[0]['_items'][0]['boot_rom_version']

    return {factoid: result}
项目:unearth    作者:chilcote    | 项目源码 | 文件源码
def fact():
    '''Returns the boot drive medium'''
    result = 'None'

    try:
        proc = subprocess.Popen(
                ['/usr/sbin/diskutil', 'info', '-plist', '/'],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
                )
        stdout, _ = proc.communicate()
    except (IOError, OSError):
        stdout = None

    if stdout:
        d = plistlib.readPlistFromString(stdout.strip())
        if d.get('CoreStorageCompositeDisk', False):
            result = 'fusion'
        elif d.get('RAIDMaster', False):
            result = 'raid'
        else:
            result = 'ssd' if d.get('SolidState', False) else 'rotational'

    return {factoid: result}
项目:unearth    作者:chilcote    | 项目源码 | 文件源码
def fact():
    '''Returns the last date xprotect was updated'''

    result = 'None'

    try:
        cmd = ['/usr/sbin/pkgutil', '--pkgs=.*XProtect.*']
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        (pkgs, stderr) = proc.communicate()

        if pkgs:
            dates = []
            for pkgid in pkgs.splitlines():
                pkginfo_plist = subprocess.check_output(['/usr/sbin/pkgutil',
                                                        '--pkg-info-plist',
                                                        pkgid])
                pkginfo = plistlib.readPlistFromString(pkginfo_plist)
                dates.append(pkginfo['install-time'])

            result = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(max(dates)))
    except (OSError, IOError):
        pass

    return {factoid: result}
项目:unearth    作者:chilcote    | 项目源码 | 文件源码
def fact():
    '''Returns the boot volume'''
    result = 'None'

    try:
        proc = subprocess.Popen(
                ['/usr/sbin/diskutil', 'info', '-plist', '/'],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
                )
        stdout, _ = proc.communicate()
    except (IOError, OSError):
        stdout = None

    if stdout:
        d = plistlib.readPlistFromString(stdout.strip())
        result = d['VolumeName']

    return {factoid: result}
项目:unearth    作者:chilcote    | 项目源码 | 文件源码
def fact():
    '''Returns the battery cycle count'''

    result = 'None'

    try:
        proc = subprocess.Popen(
                ['/usr/sbin/ioreg', '-r', '-c', 'AppleSmartBattery', '-a'],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
                )
        stdout, _ = proc.communicate()
        if stdout:
            result = plistlib.readPlistFromString(stdout)[0]['CycleCount']
    except (IOError, OSError):
        pass

    return {factoid: result}
项目:unearth    作者:chilcote    | 项目源码 | 文件源码
def fact():
    '''Gets the home directories of all console users'''
    users = []
    homes = []

    excluded = ('root', 'daemon', 'nobody')
    cmd = ['/usr/bin/dscl', '.', 'list', '/Users']
    output = subprocess.check_output(cmd)
    for user in output.split():
        if user not in excluded and not user.startswith('_'):
            users.append(user)

    for user in users:
        cmd = ['/usr/bin/dscl', '-plist', '.', 'read', '/Users/' + user]
        output = subprocess.check_output(cmd)
        d = plistlib.readPlistFromString(output)
        homes.append(d['dsAttrTypeStandard:NFSHomeDirectory'][0])

    return {factoid: homes}
项目:unearth    作者:chilcote    | 项目源码 | 文件源码
def fact():
    '''Returns whether the boot drive is an ssd'''
    result = 'Unknown'

    try:
        proc = subprocess.Popen(
                ['/usr/sbin/diskutil', 'info', '-plist', '/'],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
                )
        stdout, _ = proc.communicate()
    except (IOError, OSError):
        stdout = None

    if stdout:
        d = plistlib.readPlistFromString(stdout.strip())
        if (
            not d.get('CoreStorageCompositeDisk', False) and
            not d.get('RAIDMaster', False)
           ):
            result = d.get('SolidState', False)

    return {factoid: result}
项目:mdmscripts    作者:erikng    | 项目源码 | 文件源码
def checkDEPEnrolledStatus(depProfileUuid):
    enrollment = False
    cmd = ['/usr/bin/profiles', '-L', '-o', 'stdout-xml']
    run = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, err = run.communicate()
    try:
        plist = plistlib.readPlistFromString(output)
    except:  # noqa
        plist = {'_computerlevel': []}
    for x in plist['_computerlevel']:
        try:
            profileUuid = x['ProfileUUID']
        except KeyError:
            profileUuid = ''
        if profileUuid == depProfileUuid:
            return True
    return enrollment
项目:managedmacadmin    作者:cabal95    | 项目源码 | 文件源码
def build_custom_preference_profile_pref(content, pref):
    plist = plistlib.readPlistFromString(pref.plist)

    for freq in ['Once', 'Often', 'Always']:
        if len(plist[freq]) == 0:
            continue

        data = dict()
        data['mcx_preference_settings'] = plist[freq]
        if freq == 'Once':
            data['mcx_data_timestamp'] = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
            key = 'Set-Once'
        elif freq == 'Often':
            key = 'Set-Once'
        else:
            key = 'Forced'

        if pref.identifier not in content:
            content[pref.identifier] = { }
        if key not in content[pref.identifier]:
            content[pref.identifier][key] = [ ]

        content[pref.identifier][key].append(data)
项目:pinpoint    作者:clburlison    | 项目源码 | 文件源码
def wireless_scan():
    """Scan for current networks and return a sorted list of dictionary
    objects."""
    ssid_scan = subprocess.check_output(
                    ['/System/Library/PrivateFrameworks/'
                     'Apple80211.framework/Versions/A/'
                     'Resources/airport', '-s', '--xml']
                     )
    ssid_scan = plistlib.readPlistFromString(ssid_scan)
    values = []
    for i, val in enumerate(ssid_scan):
        wifi_stats = {'RSSI': val.get('RSSI'),
                      'BSSID': val.get('BSSID'),
                      'SSID_STR': val.get('SSID_STR')
                      }
        values.append(wifi_stats)

    # Sort our values by RSSI to increase accuracy of location
    return sorted(values, key=lambda k: k['RSSI'], reverse=True)
项目:campies    作者:fgimian    | 项目源码 | 文件源码
def get_catalog(catalog_url):
    """Obtaines the Apple software catalog as a dict"""
    try:
        catalog_request = urlopen(catalog_url)
    except (IOError, URLError, HTTPError):
        raise CampiesError(
            'Unable to download catalog URL {catalog_url}'.format(
                catalog_url=catalog_url
            )
        )

    catalog_xml = catalog_request.read()
    try:
        catalog = loads_plist(catalog_xml)
    except xml.parsers.expat.ExpatError:
        raise CampiesError(
            'Unable to parse catalog XML to obtain software details'
        )
    return catalog
项目:LIFX_Controller    作者:autolog    | 项目源码 | 文件源码
def _readPluginInfoFromArchive(self, zipfile):
        topdir = zipfile.namelist()[0]

        # read and the plugin info contained in the zipfile
        plistFile = os.path.join(topdir, self.path, 'Contents', 'Info.plist')
        self._debug('Reading plugin info: %s' % plistFile)

        plistData = zipfile.read(plistFile)
        if (plistData == None):
            raise Exception('Unable to read new plugin info')

        plist = plistlib.readPlistFromString(plistData)

        return self._buildPluginInfo(plist)

    #---------------------------------------------------------------------------
    # verifies the provided plugin info matches what we expect
项目:yowsup    作者:colonyhq    | 项目源码 | 文件源码
def parse(self, xml, pvars):

        #tmp = minidom.parseString(xml)

        if sys.version_info >= (3, 0):
            pl = plistlib.readPlistFromBytes(xml.encode());
        else:
            pl = plistlib.readPlistFromString(xml);

        parsed= {}
        pvars = self.getVars(pvars)

        for k,v in pvars.items():
            parsed[k] = pl[k] if  k in pl else None

        return parsed;
项目:macholibre    作者:aaronst    | 项目源码 | 文件源码
def parse_entitlement(self, signature, offset):
        prev = self.f.tell()
        true_offset = signature.offset + offset
        self.f.seek(true_offset)
        magic = get_int(self.f)
        if magic != dictionary.signatures['ENTITLEMENT']:
            data = {
                'offset': true_offset,
                'magic': hex(magic),
                'expected': hex(dictionary.signatures['ENTITLEMENT'])
            }
            a = Abnormality(title='BAD MAGIC - ENTITLEMENT', data=data)
            self.add_abnormality(a)
            self.f.seek(prev)
            return
        size = get_int(self.f) - 8
        plist = plistlib.readPlistFromString(self.f.read(size))
        entitlement = Entitlement(size=size, plist=plist)
        signature.add_entitlement(entitlement)
        self.f.seek(prev)
项目:Indigo-August-Home    作者:mlamoure    | 项目源码 | 文件源码
def _readPluginInfoFromArchive(self, zipfile):
        topdir = zipfile.namelist()[0]

        # read and the plugin info contained in the zipfile
        plistFile = os.path.join(topdir, self.path, 'Contents', 'Info.plist')
        self.logger.debug('Reading plugin info: %s' % plistFile)

        plistData = zipfile.read(plistFile)
        if (plistData == None):
            raise Exception('Unable to read new plugin info')

        plist = plistlib.readPlistFromString(plistData)

        return self._buildPluginInfo(plist)

    #---------------------------------------------------------------------------
    # verifies the provided plugin info matches what we expect
项目:python-airplay    作者:cnelson    | 项目源码 | 文件源码
def do_POST(self):
        """Called when a new event has been received"""

        # make sure this is what we expect
        if self.path != '/event':
            raise RuntimeError('Unexpected path when parsing event: {0}'.format(self.path))

        # validate our content type
        content_type = self.headers.get('content-type', None)
        if content_type != 'text/x-apple-plist+xml':
            raise RuntimeError('Unexpected Content-Type when parsing event: {0}'.format(content_type))

        # and the body length
        content_length = int(self.headers.get('content-length', 0))
        if content_length == 0:
            raise RuntimeError('Received an event with a zero length body.')

        # parse XML plist
        self.event = plist_loads(self.rfile.read(content_length))
项目:precache_dev    作者:carlashley    | 项目源码 | 文件源码
def read_feed(self, url):
        '''Reads any of the Apple XML/plist feeds required for software updates or
        iOS updates'''
        return readPlistFromString(requests.get(url, headers={'user-agent': self.user_agent}, timeout=10).text)  # NOQA
项目:Bella    作者:Trietptm-on-Security    | 项目源码 | 文件源码
def dsid_factory(uname, passwd):
    resp = None
    req = urllib2.Request("https://setup.icloud.com/setup/authenticate/%s" % uname)
    req.add_header('Authorization', 'Basic %s' % base64.b64encode("%s:%s" % (uname, passwd)))
    req.add_header('Content-Type', 'application/json')
    try:
        resp = urllib2.urlopen(req)
    except urllib2.HTTPError as e:
        if e.code != 200:
            if e.code == 401:
                return (False, "HTTP Error 401: Unauthorized. Are you sure the credentials are correct?\n", False)
            elif e.code == 409:
                tokenLocal = tokenRead()
                if tokenLocal != False: #if we have token use it ... bc 2SV wont work with regular uname/passw                    
                    dsid = tokenLocal.split("\n")[1].split(":")[0]
                    tokz = tokenLocal.split("\n")[1].split(":")[1]
                    return (dsid, tokz, True)
                else:
                    return (False, "HTTP Error 409: Conflict. 2 Factor Authentication appears to be enabled. You cannot use this function unless you get your MMeAuthToken manually (generated either on your PC/Mac or on your iOS device).\n", False)
            elif e.code == 404:
                return (False, "HTTP Error 404: URL not found. Did you enter a username?\n", False)
            else:
                return (False, "HTTP Error %s." % e.code, False)
        else:
            return e
    content = resp.read()
    uname = plistlib.readPlistFromString(content)["appleAccountInfo"]["dsPrsID"] #stitch our own auth DSID
    passwd = plistlib.readPlistFromString(content)["tokens"]["mmeAuthToken"] #stitch with token
    return (uname, passwd, False) #third value is "usingToken?"
项目:Bella    作者:Trietptm-on-Security    | 项目源码 | 文件源码
def tokenFactory(authCode):
    #now that we have proper b64 encoded auth code, we will attempt to get all account tokens.
    try:
        req = urllib2.Request("https://setup.icloud.com/setup/get_account_settings")
        req.add_header('Authorization', 'Basic %s' % authCode)
        req.add_header('Content-Type', 'application/xml') #for account settings it appears we cannot use json. type must be specified.
        req.add_header('X-MMe-Client-Info', '<iPhone6,1> <iPhone OS;9.3.2;13F69> <com.apple.AppleAccount/1.0 (com.apple.Preferences/1.0)>') #necessary header to get tokens.
        resp = urllib2.urlopen(req)
        content = resp.read()
        tokens = []
        #staple it together & call it bad weather
        accountInfo = []
        accountInfo.append(plistlib.readPlistFromString(content)["appleAccountInfo"]["fullName"] + " | " + plistlib.readPlistFromString(content)["appleAccountInfo"]["appleId"] + " | " + plistlib.readPlistFromString(content)["appleAccountInfo"]["dsPrsID"])

        try:
            tokens.append(plistlib.readPlistFromString(content)["tokens"]["mmeAuthToken"])
        except:
            pass
        try:
            tokens.append(plistlib.readPlistFromString(content)["tokens"]["cloudKitToken"])
        except:
            pass
        try:
            tokens.append(plistlib.readPlistFromString(content)["tokens"]["mmeFMFAppToken"])
        except:
            pass
        try:
            tokens.append(plistlib.readPlistFromString(content)["tokens"]["mmeFMIPToken"])
        except:
            pass
        try:
            tokens.append(plistlib.readPlistFromString(content)["tokens"]["mmeFMFToken"])
        except:
            pass

        return (tokens, accountInfo)
    except Exception, e:
        return '%s' % e
项目:munki-enrollment-client    作者:gerritdewitt    | 项目源码 | 文件源码
def system_profiler_fetch_serial():
    '''Calls System Profiler to get the computer's hardware serial number.
        Returns an empty string if something bad happened.'''
    # Run command:
    try:
        output = subprocess.check_output(['/usr/sbin/system_profiler',
                                      'SPHardwareDataType',
                                      '-xml'])
    except subprocess.CalledProcessError:
        output = None
    # Try to get serial_number key:
    if output:
        try:
            output_dict = plistlib.readPlistFromString(output)
        except xml.parsers.expat.ExpatError:
            output_dict = {}
    if output_dict:
        try:
            serial_number = output_dict[0]['_items'][0]['serial_number']
        except KeyError:
            serial_number = ''
    # Log bad serial:
    if not serial_number:
        common.print_error("Failed to get the computer's hardware serial number.")
    # Return:
    return serial_number
项目:munki-enrollment-client    作者:gerritdewitt    | 项目源码 | 文件源码
def process_response_as_xml(given_server_response):
    '''Retrieves the main dictionary from given response.  If not possible, it 
        uses a blank dictionary.  Ensures that some essential keys are set in all cases.'''
    # Default:
    response_dict = {}
    # If response is not None:
    if given_server_response:
        common.print_info("Processing response for XML content.")
        try:
            response_dict = plistlib.readPlistFromString(given_server_response.read())
            common.print_info("Response is a valid XML property list.")
        except xml.parsers.expat.ExpatError, NameError:
            common.print_error("Response is not an XML property list!")
    # Return:
    return response_dict
项目:alfred-workflows    作者:arthurhammer    | 项目源码 | 文件源码
def read_plist(path):
    """Convert plist to XML and read its contents."""
    cmd = [b'plutil', b'-convert', b'xml1', b'-o', b'-', path]
    xml = subprocess.check_output(cmd)
    return plistlib.readPlistFromString(xml)
项目:nojs    作者:chrisdickinson    | 项目源码 | 文件源码
def LoadPlistFile(plist_path):
  """Loads property list file at |plist_path|.

  Args:
    plist_path: path to the property list file to load.

  Returns:
    The content of the property list file as a python object.
  """
  return plistlib.readPlistFromString(subprocess.check_output([
      'xcrun', 'plutil', '-convert', 'xml1', '-o', '-', plist_path]))
项目:nojs    作者:chrisdickinson    | 项目源码 | 文件源码
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]))
项目:ATX    作者:NetEaseGame    | 项目源码 | 文件源码
def info(self):
        return plistlib.readPlistFromString(idevice('info', '--xml', '--udid', self.udid))
项目:appleLoops    作者:carlashley    | 项目源码 | 文件源码
def get_feed(self, apple_url, fallback_url):
        '''Returns the feed as a dictionary from either the Apple URL or the fallback URL, pending result code.'''  # NOQA
        # Initalise request, and check for 404's
        apple_url_request = self.request.response_code(apple_url)
        fallback_url_request = self.request.response_code(fallback_url)
        if apple_url_request == 404:
            # Use fallback URL
            self.log.debug('Falling back to alternate feed: %s' % fallback_url)  # NOQA
            if fallback_url_request == 200:
                req = {
                    'app_feed_file': os.path.basename(fallback_url),
                    'result': readPlistFromString(self.request.read_data(fallback_url))  # NOQA
                }
                return req
            else:
                self.log.info('There was a problem trying to reach %s' % fallback_url)  # NOQA
                return Exception('There was a problem trying to reach %s' % fallback_url)  # NOQA
        elif apple_url_request == 200:
            # Use Apple URL
            req = {
                'app_feed_file': os.path.basename(apple_url),
                'result': readPlistFromString(self.request.read_data(apple_url))  # NOQA
            }
            return req
        else:
            self.log.info('There was a problem trying to reach %s' % apple_url)  # NOQA
            return Exception('There was a problem trying to reach %s' % apple_url)  # NOQA
项目:appleLoops    作者:carlashley    | 项目源码 | 文件源码
def space_available(self):
        cmd = ['/usr/sbin/diskutil', 'info', '-plist', '/']
        (result, error) = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()  # NOQA
        # Return an int
        return int(plistlib.readPlistFromString(result)['FreeSpace'])
项目:appleLoops    作者:carlashley    | 项目源码 | 文件源码
def loop_installed(self, pkg_id):
        '''Returns if a package is installed'''
        cmd = ['/usr/sbin/pkgutil', '--pkg-info-plist', pkg_id]
        (result, error) = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()  # NOQA

        if result:
            # need to use plistlib as this doesn't cause issues with tests
            _pkg_id = plistlib.readPlistFromString(result)['pkgid']
            if pkg_id in _pkg_id:
                return True
            else:
                return False
        else:
            return False
项目:chromium-build    作者:discordapp    | 项目源码 | 文件源码
def LoadPlistFile(plist_path):
  """Loads property list file at |plist_path|.

  Args:
    plist_path: path to the property list file to load.

  Returns:
    The content of the property list file as a python object.
  """
  return plistlib.readPlistFromString(subprocess.check_output([
      'xcrun', 'plutil', '-convert', 'xml1', '-o', '-', plist_path]))
项目:chromium-build    作者:discordapp    | 项目源码 | 文件源码
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]))
项目:AutomatorX    作者:xiaoyaojjian    | 项目源码 | 文件源码
def info(self):
        return plistlib.readPlistFromString(idevice('info', '--xml', '--udid', self.udid))
项目:iOS-private-api-checker    作者:NetEaseGame    | 项目源码 | 文件源码
def extract_info_plist_data(self):
        extract_info = self.get_filename_from_ipa('Info')
        zip_obj = extract_info['zip_obj']
        plist_filename = extract_info['filename']

        data = {}
        if plist_filename == '':
            if self.get_filename_from_ipa('Misnamed_Payload_Check')['filename'] != '':
                self.errors.append("Payload folder is misnamed 'payload' (lower-case p). Rename to 'Payload'")
            else:
                self.errors.append('Info.plist file not found in IPA')
        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)
                # pprint(cmd)

                os.system(cmd)
                data = plistlib.readPlist(fullpath_plist)
        # end if plist == ''

        self.info_plist_data = data
    # end extractPlist()
项目:gn_build    作者:realcome    | 项目源码 | 文件源码
def LoadPlistFile(plist_path):
  """Loads property list file at |plist_path|.

  Args:
    plist_path: path to the property list file to load.

  Returns:
    The content of the property list file as a python object.
  """
  return plistlib.readPlistFromString(subprocess.check_output([
      'xcrun', 'plutil', '-convert', 'xml1', '-o', '-', plist_path]))
项目:gn_build    作者:realcome    | 项目源码 | 文件源码
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]))
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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)