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;
python类readPlistFromString()的实例源码
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)
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
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
read_launch_plists.py 文件源码
项目:macOS-Security-and-Privacy-Guide
作者: ManuGutierrez
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
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
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
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
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
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())
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
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}
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 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()}
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}
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}
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}
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}
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}
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}
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}
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}
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}
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
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)
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)
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
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
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;
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)
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