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))
python类readPlistFromString()的实例源码
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
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?"
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
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
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
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)
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]))
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 info(self):
return plistlib.readPlistFromString(idevice('info', '--xml', '--udid', self.udid))
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
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'])
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
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]))
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 info(self):
return plistlib.readPlistFromString(idevice('info', '--xml', '--udid', self.udid))
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()
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]))
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 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)