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 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 generate_bag(content, cert_file): content_plist = writePlistToString(content) bag = { 'bag': Data(content_plist), 'certs': [Data(der_cert_from_pem_file(cert_file))], 'signature': Data(sign_bag(content_plist, cert_file)), } return writePlistToString(bag)
def test_controlcharacters(self): for i in range(128): c = chr(i) testString = "string containing %s" % c if i >= 32 or c in "\r\n\t": # \r, \n and \t are the only legal control chars in XML plistlib.writePlistToString(testString) else: self.assertRaises(ValueError, plistlib.writePlistToString, testString)
def _collect_keys(self): self._seen_keys = [] self._libkeys = [] self._key_contents = {} self._key_sizes = {} if self._font is not None: # Font lib for k in self._font.lib.keys(): if not k in self._seen_keys: self._libkeys.append({ "Delete": False, "Description": self._known_keys.get(k, "(%s)" % k.split(".")[-1]), "Size": "? kB", "Key": k, "Location": "Font", }) self._seen_keys.append(k) self._key_contents[k] = "" self._key_contents[k] += writePlistToString(self._font.lib[k])[173:-9].decode("utf-8") self._key_sizes[k] = len(self._key_contents[k]) # Glyph libs for g in self._font: for k in g.lib.keys(): if not k in self._seen_keys: self._libkeys.append({ "Delete": False, "Description": self._known_keys.get(k, "(%s)" % k.split(".")[-1]), "Size": "? kB", "Key": k, "Location": "Glyph", }) self._seen_keys.append(k) self._key_contents[k] = "" self._key_contents[k] += writePlistToString(g.lib[k])[173:-9].decode("utf-8") self._key_sizes[k] = len(self._key_contents[k]) # Collect key sizes total_size = 0 for i in range(len(self._libkeys)): _key = self._libkeys[i] size = self._key_sizes[_key["Key"]] total_size += size if size < 1024: _key["Size"] = "%i B" % size else: _key["Size"] = "%0.1f kB" % (size / 1024) self.total_size = total_size
def update_report(self, base64bz2report): # Save report. try: base64bz2report = base64bz2report.replace(" ", "+") plist = self.b64bz_decode(base64bz2report) #self.report = base64bz2report self.report = plistlib.writePlistToString(plist) except: plist = None self.report = '' if plist is None: self.activity = None self.errors = 0 self.warnings = 0 self.console_user = "******" return # Check activity. activity = dict() for section in ("ItemsToInstall", "InstallResults", "ItemsToRemove", "RemovalResults", "AppleUpdates"): if (section in plist) and len(plist[section]): activity[section] = plist[section] if activity: #self.activity = self.encode(activity) self.activity = plistlib.writePlistToString(activity) else: self.activity = None # Check errors and warnings. if "Errors" in plist: self.errors = len(plist["Errors"]) else: self.errors = 0 if "Warnings" in plist: self.warnings = len(plist["Warnings"]) else: self.warnings = 0 # Check console user. self.console_user = "******" if "ConsoleUser" in plist: self.console_user = unicode(plist["ConsoleUser"])
def test_generateRecordsNonDefaultPatterns(self): """ L{LoadSimulator.fromCommandLine} takes an account loader from the config file and uses it to generate user records for use in the simulation. """ config = VALID_CONFIG.copy() config["accounts"] = { "loader": "contrib.performance.loadtest.sim.generateRecords", "params": { "count": 3, "uidPattern": "USER%03d", "passwordPattern": "PASSWORD%03d", "namePattern": "Test User %03d", "emailPattern": "*****@*****.**", }, } configpath = FilePath(self.mktemp()) configpath.setContent(writePlistToString(config)) sim = LoadSimulator.fromCommandLine(['--config', configpath.path], StringIO()) self.assertEqual(3, len(sim.records)) self.assertEqual(sim.records[0].uid, 'USER001') self.assertEqual(sim.records[0].password, 'PASSWORD001') self.assertEqual(sim.records[0].commonName, 'Test User 001') self.assertEqual(sim.records[0].email, '*****@*****.**') self.assertEqual(sim.records[2].uid, 'USER003') self.assertEqual(sim.records[2].password, 'PASSWORD003') self.assertEqual(sim.records[2].commonName, 'Test User 003') self.assertEqual(sim.records[2].email, '*****@*****.**')
def test_generateRecordsDefaultPatterns(self): """ L{LoadSimulator.fromCommandLine} takes an account loader from the config file and uses it to generate user records for use in the simulation. """ config = VALID_CONFIG.copy() config["accounts"] = { "loader": "contrib.performance.loadtest.sim.generateRecords", "params": { "count": 2 }, } configpath = FilePath(self.mktemp()) configpath.setContent(writePlistToString(config)) sim = LoadSimulator.fromCommandLine(['--config', configpath.path], StringIO()) self.assertEqual(2, len(sim.records)) self.assertEqual(sim.records[0].uid, 'user1') self.assertEqual(sim.records[0].password, 'user1') self.assertEqual(sim.records[0].commonName, 'User 1') self.assertEqual(sim.records[0].email, '*****@*****.**') self.assertEqual(sim.records[1].uid, 'user2') self.assertEqual(sim.records[1].password, 'user2') self.assertEqual(sim.records[1].commonName, 'User 2') self.assertEqual(sim.records[1].email, '*****@*****.**')
def test_loadDefaultAccountsFromFile(self): """ L{LoadSimulator.fromCommandLine} takes an account loader (with empty path)from the config file and uses it to create user records for use in the simulation. """ config = VALID_CONFIG.copy() config["accounts"] = { "loader": "contrib.performance.loadtest.sim.recordsFromCSVFile", "params": { "path": "" }, } configpath = FilePath(self.mktemp()) configpath.setContent(writePlistToString(config)) sim = LoadSimulator.fromCommandLine(['--config', configpath.path], StringIO()) self.assertEqual(99, len(sim.records)) self.assertEqual(sim.records[0].uid, 'user01') self.assertEqual(sim.records[0].password, 'user01') self.assertEqual(sim.records[0].commonName, 'User 01') self.assertEqual(sim.records[0].email, '*****@*****.**') self.assertEqual(sim.records[98].uid, 'user99') self.assertEqual(sim.records[98].password, 'user99') self.assertEqual(sim.records[98].commonName, 'User 99') self.assertEqual(sim.records[98].email, '*****@*****.**')
def test_loadAccountsFromFile(self): """ L{LoadSimulator.fromCommandLine} takes an account loader from the config file and uses it to create user records for use in the simulation. """ accounts = FilePath(self.mktemp()) accounts.setContent("foo,bar,baz,quux\nfoo2,bar2,baz2,quux2\n") config = VALID_CONFIG.copy() config["accounts"] = { "loader": "contrib.performance.loadtest.sim.recordsFromCSVFile", "params": { "path": accounts.path }, } configpath = FilePath(self.mktemp()) configpath.setContent(writePlistToString(config)) io = StringIO() sim = LoadSimulator.fromCommandLine(['--config', configpath.path], io) self.assertEquals(io.getvalue(), "Loaded 2 accounts.\n") self.assertEqual(2, len(sim.records)) self.assertEqual(sim.records[0].uid, 'foo') self.assertEqual(sim.records[0].password, 'bar') self.assertEqual(sim.records[0].commonName, 'baz') self.assertEqual(sim.records[0].email, 'quux') self.assertEqual(sim.records[1].uid, 'foo2') self.assertEqual(sim.records[1].password, 'bar2') self.assertEqual(sim.records[1].commonName, 'baz2') self.assertEqual(sim.records[1].email, 'quux2')
def pair(self): print "Creating host key & certificate" hostCertificate, hostPrivateKey, deviceCertificate = generateCertificates(self.devicePublicKey) pair_record = {'DevicePublicKey': plistlib.Data(self.devicePublicKey), 'DeviceCertificate': plistlib.Data(deviceCertificate), 'HostCertificate': plistlib.Data(hostCertificate), 'HostPrivateKey': plistlib.Data(hostPrivateKey), 'HostID': self.hostID, 'RootCertificate': plistlib.Data(hostCertificate), 'SystemBUID': '30142955-444094379208051516'} Pair = self.service.sendRequest({ 'Request': 'Pair', 'PairRecord': pair_record }) if self.osVersion[0] == '7' and Pair.get('Error') == 'PasswordProtected': raise NotTrustedError if Pair and Pair.get('Result') == 'Success' or 'EscrowBag' in Pair: if 'EscrowBag' in Pair: pair_record['EscrowBag'] = Pair['EscrowBag'] writeHomeFile(HOMEFOLDER, '%s.plist' % self.udid, plistlib.writePlistToString(pair_record)) else: raise PairingError
def main(argv): p = optparse.OptionParser() p.set_usage("""Usage: %prog [options]""") p.add_option("-v", "--verbose", action="store_true", help="Verbose output.") options, argv = p.parse_args(argv) if len(argv) != 3: print >>sys.stderr, p.get_usage() return 1 status = int(argv[1]) message = argv[2].decode("utf-8") sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) msg = plistlib.writePlistToString({ "DAFGUMigrationStatus": status, "DAFGUMigrationMessage": message, }) for item in os.listdir(SOCKET_DIR): if item.startswith(SOCKET_NAME): socket_path = os.path.join(SOCKET_DIR, item) print "Sending message to %s" % socket_path try: sock.sendto(msg, socket_path) except socket.error, e: if e[0] == errno.ECONNREFUSED: print "Removing stale socket %s" % (socket_path) os.unlink(socket_path) else: print "%s failed: %s" % (socket_path, e)
def read(cls, pathname): '''Reads a pkginfo file and returns the plist as text data''' manifest_path = os.path.join(REPO_DIR, 'manifests') filepath = os.path.join(manifest_path, pathname) if not os.path.exists(filepath): raise ManifestDoesNotExistError() default_items = { 'catalogs': [], 'included_manifests': [], 'managed_installs': [], 'managed_uninstalls': [], 'managed_updates': [], 'optional_installs': [], } try: plistdata = plistlib.readPlist(filepath) # define default fields for easier editing for item in default_items: if not item in plistdata: plistdata[item] = default_items[item] return plistlib.writePlistToString(plistdata) except: # just read and return the raw text try: with open(filepath) as FILEREF: pkginfo = FILEREF.read().decode('utf-8') return pkginfo except Exception, err: raise ManifestReadError(err)
def available(request, item_name=''): '''Returns license seat availability for item_name in plist format. Key is item_name, value is boolean. For use by Munki client to determine if a given item should be made available for optional install.''' output_style = request.GET.get('output_style', 'plist') item_names = [] if item_name: item_names.append(item_name) additional_names = request.GET.getlist('name') item_names.extend(additional_names) info = {} if item_names: for name in item_names: try: license = License.objects.get(item_name=name) info[name] = (license.available() > 0) except (License.DoesNotExist): pass else: # return everything licenses = License.objects.all() for license in licenses: info[license.item_name] = license.available() if output_style == 'json': return HttpResponse(json.dumps(info), mimetype='application/json') else: return HttpResponse(plistlib.writePlistToString(info), mimetype='application/xml')
def updateLayerContentList(self): if not self.ufoFontHashData: # isn't a UFO font. return if not self.ufoFontHashData.deletedGlyph: return # Get list of glif file names: fileList = os.listdir(self.ufoFontHashData.glyphLayerDir) fileDict = {} for fileName in fileList: if fileName.endswith(".glif"): fileDict[fileName] = 1 contentsPath = os.path.join(self.ufoFontHashData.glyphLayerDir, "contents.plist") try: contents = readPlist(contentsPath) except: raise focusFontError("The processed layer file %s could not be read." % path) contentItems = contents.items() for name, fileName in contentItems: if fileName not in fileDict: del contents[name] plist = writePlistToString(contents) f = open(contentsPath, "wb") f.write(plist) f.close() print "Updated plist"
def __str__(self): plist_str = plistlib.writePlistToString( self.__toDict__(strKeys=True, unicode=True) ) return re.sub('[\n\t]+', '', plist_str) if self._minified \ else plist_str
def mdm_vendor_sign(csr_text, mdm_vendor_certificate_der, mdm_vendor_certificate_passphrase, encode_xml=True): mdm_vendor_cert_info = \ _verify_and_read_mdm_vendor_certificate( mdm_vendor_certificate_der, mdm_vendor_certificate_passphrase) csr_der = _get_der_from_pem_csr(csr_text) csr_rows = csr_text.rstrip().split("\n") csr_rows_no_anchors = csr_rows[1:-1] csr_text_no_anchors = "\n".join(csr_rows_no_anchors) csr_signature = _sign_csr(csr_der, mdm_vendor_cert_info['private_key_pem']) ia_pem = _get_remote_cert(IA_CERT_URL) ca_pem = _get_remote_cert(CA_CERT_URL) _cert_chain = (mdm_vendor_cert_info['certificate_pem'] + ia_pem + ca_pem) _cert_sig = ''.join(_chunks(csr_signature)) plist_dict = dict( PushCertRequestCSR=csr_text_no_anchors, PushCertCertificateChain=_cert_chain.rstrip(), PushCertSignature=_cert_sig.rstrip()) plist_xml = writePlistToString(plist_dict) if encode_xml is False: return plist_xml encoded_plist = b64encode(plist_xml) return ''.join(_chunks(encoded_plist)).rstrip() + "\n"
def detail(request, pkginfo_path): '''Return detail for a specific pkginfo''' if request.method == 'GET': LOGGER.debug("Got read request for %s", pkginfo_path) try: plist = Plist.read('pkgsinfo', pkginfo_path) except FileDoesNotExistError: raise Http404("%s does not exist" % pkginfo_path) default_items = { 'display_name': '', 'description': '', 'category': '', 'developer': '', 'unattended_install': False, 'unattended_uninstall': False } for item in default_items: if not item in plist: plist[item] = default_items[item] pkginfo_text = plistlib.writePlistToString(plist) installer_item_path = plist.get('installer_item_location', '') icon_url = get_icon_url(plist) context = {'plist_text': pkginfo_text, 'pathname': pkginfo_path, 'installer_item_path': installer_item_path, 'icon_url': icon_url} return render(request, 'pkgsinfo/detail.html', context=context) if request.method == 'POST': return HttpResponse( json.dumps({'result': 'failed', 'exception_type': 'MethodNotSupported', 'detail': 'POST/PUT/DELETE should use the API'}), content_type='application/json', status=404)
def outPutJsonData(request): result={} stageScenceDiffcultList=StageScenceDiffcult.objects.all() for obj in stageScenceDiffcultList: result[obj.StageScenceDiffcult_Key]=[] stageScenceList = obj.stagescence_set.all() for scence in stageScenceList: j_scence={} j_scence["itemList"]=[] result[obj.StageScenceDiffcult_Key].append(j_scence) p_scence_array=json.loads(scence.StageScence_text) for item in p_scence_array: p_val_scence={} p_val_scence["type"]=item.has_key("type") and item["type"] or item["type"] p_val_scence["id"]=item.has_key("id") and item["id"] or item["id"] p_val_scence["coco2d_img"]=item.has_key("coco2d_img") and item["coco2d_img"] or item["coco2d_img"] p_val_scence["cocos2dX"]=item.has_key("cocos2dX") and item["cocos2dX"] or item["cocos2dX"] p_val_scence["cocos2dY"]=item.has_key("cocos2dY") and item["cocos2dY"] or item["cocos2dY"] p_val_scence["height"]=item.has_key("height") and item["height"] or item["height"] p_val_scence["width"]=item.has_key("width") and item["width"] or item["width"] p_val_scence["rotate"]=item.has_key("rotate") and item["rotate"] or 0 p_val_scence["scaleX"]=item.has_key("scaleX") and item["scaleX"] or 1 p_val_scence["scaleY"]=item.has_key("scaleY") and item["scaleY"] or 1 p_val_scence["skewX"]=item.has_key("skewX") and item["skewX"] or 0 p_val_scence["skewY"]=item.has_key("skewY") and item["skewY"] or 0 j_scence["itemList"].append(p_val_scence) pass pass pass return HttpResponse(writePlistToString(result).decode('utf8'))
def connectionMade(self): super(Manager, self).connectionMade() for record in self.loadsim.records: self.callRemote(Account, uid=record.uid, password=record.password, commonName=record.commonName, email=record.email) workerConfig = deepcopy(self.loadsim.configTemplate) # The list of workers is for the manager only; the workers themselves # know they're workers because they _don't_ receive this list. del workerConfig["workers"] # The manager loads the accounts via the configured loader, then sends # them out to the workers (right above), which look at the state at an # instance level and therefore don't need a globally-named directory # record loader. del workerConfig["accounts"] workerConfig["workerID"] = self.whichWorker workerConfig["workerCount"] = self.numWorkers workerConfig["observers"] = [] workerConfig.pop("accounts", None) plist = writePlistToString(workerConfig) self.output.write("Initiating worker configuration\n") def completed(x): self.output.write("Worker configuration complete.\n") (self.callRemote(Configure, plist=plist) .addCallback(completed))
def app_manifest(app_id): app_q = db_session.query(App).filter(App.id == app_id) app = app_q.one() config = db_session.query(MDMConfig).one() asset = { 'kind': 'software-package', 'md5-size': app.md5_chunk_size, 'md5s': app.md5_chunk_hashes.split(':'), 'url': '%s/app/%d/download/%s' % (config.base_url(), app_id, app.filename), } metadata = {'kind': 'software', 'title': app.filename, 'sizeInBytes': app.filesize} pkgs_ids = app.pkg_ids_json pkgs_bundles = [{'bundle-identifier': i[0], 'bundle-version': i[1]} for i in pkgs_ids] # if subtitle: # metadata['subtitle'] = subtitle metadata.update(pkgs_bundles[0]) if len(pkgs_bundles) > 1: metadata['items'] = pkgs_bundles download = {'assets': [asset, ], 'metadata': metadata} manifest = {'items': [download]} resp = make_response(plistlib.writePlistToString(manifest)) resp.headers['Content-Type'] = 'application/xml' return resp
def save(self, entry, with_location=True, debug=False): """Saves a DayOneEntry as a plist""" entry_dict = {} if isinstance(entry, DayOneEntry): # Get a dict of the DayOneEntry entry_dict = entry.as_dict() else: entry_dict = entry # Set the UUID entry_dict['UUID'] = uuid.uuid4().get_hex() if with_location and not entry_dict['Location']: entry_dict['Location'] = self.get_location() # Do we have everything needed? if not all ((entry_dict['UUID'], entry_dict['Time Zone'], entry_dict['Entry Text'])): print "You must provide: Time zone, UUID, Creation Date, Entry Text" return False if debug is False: file_path = self._file_path(entry_dict['UUID']) plistlib.writePlist(entry_dict, file_path) else: plist = plistlib.writePlistToString(entry_dict) print plist return True
def defaults(self): """Return a string containing the default preference values. Returns: ``str`` Examples: >>> preferences = Preferences() >>> preferences.defaults() # doctest:+NORMALIZE_WHITESPACE '{ latexAutoView = 1; latexDebug = 0; latexEngine = pdflatex; latexEngineOptions = ""; latexKeepLogWin = 1; latexUselatexmk = 0; latexVerbose = 0; latexViewer = TextMate;}' """ instr = writePlistToString(self.default_values) process = Popen('pl', shell=True, stdout=PIPE, stdin=PIPE, stderr=STDOUT, close_fds=True) process.stdin.write(instr) process.stdin.close() defstr = process.stdout.read() return defstr.replace('\n', '')
def writePlist(obj, path): if not os.path.isabs(path): path = storage(path) s = plistlib.writePlistToString(obj) with codecs.open(path, "w", "utf-8") as f: f.write(s)
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 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 wrapper(self, data, expires, contentType="application/xml"): import plistlib data_struct = runDas(self, func, data, expires) plist_str = plistlib.writePlistToString(data_struct) cherrypy.response.headers['ETag'] = data_struct['results'].__str__().__hash__() _setCherryPyHeaders(plist_str, contentType, expires) return plist_str
def pair(self): self.DevicePublicKey = self.getValue("", "DevicePublicKey") if self.DevicePublicKey == '': return print "Got device public key" print "Creating host key & certificate" certPem, privateKeyPem, DeviceCertificate = ca_do_everything(self.DevicePublicKey) pair_record = {"DevicePublicKey": plistlib.Data(self.DevicePublicKey), "DeviceCertificate": plistlib.Data(DeviceCertificate), "HostCertificate": plistlib.Data(certPem), "HostID": self.hostID, "RootCertificate": plistlib.Data(certPem), "SystemBUID": "30142955-444094379208051516" } Pair = {"Request": "Pair", "PairRecord": pair_record} self.c.sendPlist(Pair) Pair = self.c.recvPlist() if Pair and Pair.get("Result") == "Success" or Pair.has_key("EscrowBag"): #print "Pairing OK" pair_record["HostPrivateKey"] = plistlib.Data(privateKeyPem) if Pair.has_key("EscrowBag"): pair_record["EscrowBag"] = Pair["EscrowBag"] writeHomeFile(HOMEFOLDER, "%s.plist" % self.identifier, plistlib.writePlistToString(pair_record)) return True print "Pairing error", Pair return False
def TryPass(apple_id, password): url = "https://fmipmobile.icloud.com/fmipservice/device/" + apple_id + "/initClient" headers = {"User-Agent": "FindMyiPhone/376 CFNetwork/672.0.8 Darwin/14.0.0"} json = { "clientContext": { "appName": "FindMyiPhone", "osVersion": "7.0.4", "clientTimestamp": 429746389281, "appVersion": "3.0", # make it random! "deviceUDID": "0123456789485ef5b1e6c4f356453be033d15622", "inactiveTime": 1, "buildVersion": "376", "productType": "iPhone6,1", }, "serverContext": {}, } req_plist = plistlib.writePlistToString(json) req = urllib2.Request(url, req_plist, headers=headers) base64string = base64.encodestring("%s:%s" % (apple_id, password)).replace("\n", "") req.add_header("Authorization", "Basic %s" % base64string) try: resp = urllib2.urlopen(req) except urllib2.HTTPError, err: if err.code == 401: return False if err.code == 330: return True
def sendpacket(self, req, tag, payload={}): payload['ClientVersionString'] = 'usbmux.py by marcan' if isinstance(req, int): req = [self.TYPE_CONNECT, self.TYPE_LISTEN][req-2] payload['MessageType'] = req payload['ProgName'] = 'tcprelay' BinaryProtocol.sendpacket(self, self.TYPE_PLIST, tag, plistlib.writePlistToString(payload))
def pair(self): self.DevicePublicKey = self.getValue("", "DevicePublicKey") if self.DevicePublicKey == '': self.logger.error("Unable to retreive DevicePublicKey") return False self.logger.info("Creating host key & certificate") certPem, privateKeyPem, DeviceCertificate = ca_do_everything(self.DevicePublicKey) pair_record = {"DevicePublicKey": plistlib.Data(self.DevicePublicKey), "DeviceCertificate": plistlib.Data(DeviceCertificate), "HostCertificate": plistlib.Data(certPem), "HostID": self.hostID, "RootCertificate": plistlib.Data(certPem), "SystemBUID": "30142955-444094379208051516" } pair = {"Label": self.label, "Request": "Pair", "PairRecord": pair_record} self.c.sendPlist(pair) pair = self.c.recvPlist() print(pair) if pair: if pair.get("Result") == "Success" or pair.get("EscrowBag"): print("kikou") pair_record["HostPrivateKey"] = plistlib.Data(privateKeyPem) pair_record["EscrowBag"] = pair.get("EscrowBag") writeHomeFile(HOMEFOLDER, "%s.plist" % self.identifier, plistlib.writePlistToString(pair_record)) self.paired = True return True elif pair.get("Error") == "PasswordProtected": self.c.close() raise NotTrustedError else: self.logger.error(pair.get("Error")) self.c.close() raise PairingError
def usage(request, item_name=''): '''Returns license info for item_name in plist or json format.''' output_style = request.GET.get('output_style', 'plist') item_names = [] if item_name: item_names.append(item_name) additional_names = request.GET.getlist('name') item_names.extend(additional_names) info = {} for name in item_names: try: license = License.objects.get(item_name=name) info[name] = {'total': license.total, 'used': license.used()} # calculate available instead of hitting the db a second time info[name]['available'] = ( info[name]['total'] - info[name]['used']) except (License.DoesNotExist): info[name] = {} if output_style == 'json': return HttpResponse(json.dumps(info), mimetype='application/json') else: return HttpResponse(plistlib.writePlistToString(info), mimetype='application/xml')
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 RemoveProfile(self, ident): profiles = self.GetProfileList() if not profiles: return if not profiles["ProfileMetadata"].has_key(ident): print "Trying to remove not installed profile %s" % ident return meta = profiles["ProfileMetadata"][ident] pprint(meta) data = plistlib.writePlistToString({ "PayloadType": "Configuration", "PayloadIdentifier": ident, "PayloadUUID": meta["PayloadUUID"], "PayloadVersion": meta["PayloadVersion"] }) self.service.sendPlist({ "RequestType": "RemoveProfile", "ProfileIdentifier": plistlib.Data(data) }) return self.service.recvPlist()
def Brute(apple_id, password): url = 'https://fmipmobile.icloud.com/fmipservice/device/' + apple_id + '/initClient' headers = { 'User-Agent': 'FindMyiPhone/376 CFNetwork/672.0.8 Darwin/14.0.0', } json = { "clientContext": { "appName": "FindMyiPhone", "osVersion": "7.0.4", "clientTimestamp": 429746389281, "appVersion": "3.0", "deviceUDID": "0123456789485ef5b1e6c4f356453be033d15622", "inactiveTime": 1, "buildVersion": "376", "productType": "iPhone6,1" }, "serverContext": {} } req_plist = plistlib.writePlistToString(json) req = urllib2.Request(url, req_plist, headers=headers) base64string = base64.encodestring('%s:%s' % (apple_id, password)).replace( '\n', '') req.add_header("Authorization", "Basic %s" % base64string) try: resp = urllib2.urlopen(req) except urllib2.HTTPError, err: if err.code == 401: return False if err.code == 330: return True
debug = lambda s, *a: None error = info warn = info # debug = info log = Log() if sys.version_info[0] == 3: if not hasattr(plistlib, 'loads'): plistlib.loads = lambda data: plistlib.readPlistFromBytes(data) plistlib.dumps = lambda value: plistlib.writePlistToBytes(value) else: plistlib.loads = lambda data: plistlib.readPlistFromString(data) plistlib.dumps = lambda value: plistlib.writePlistToString(value) def write_package(path, content): rf = sublime.packages_path() + path try: os.makedirs(os.path.dirname(rf)) except OSError as e: if e.errno != errno.EEXIST: raise with open(rf, 'w') as f: f.write(content) def read_package(path): rf = sublime.packages_path() + path
def write_xattr_tags(file_path, tags): bpl_tags = plistlib.writePlistToString(tags) optional_tag = "com.apple.metadata:" map(lambda a: xattr.setxattr(file_path, optional_tag + a, bpl_tags), ["kMDItemFinderComment", "_kMDItemUserTags", "kMDItemOMUserTags"])
'/usr/bin/security', 'authorizationdb', 'read', 'system.services.systemconfiguration.network' ] task = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = task.communicate() formatted = plistlib.readPlistFromString(out) # If we're on 10.9 and the group doesn't match, we're going to correct it. if v >= 9: if formatted['group'] != group: formatted['group'] = group # Convert back to plist input_plist = plistlib.writePlistToString(formatted) # Write the plist back to the authorizationdb command = [ '/usr/bin/security', 'authorizationdb', 'write', 'system.services.systemconfiguration.network' ] task = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = task.communicate(input=input_plist) # If we're on 10.8 and the rule doesn't match, we're going to correct it. elif v <= 8: if formatted['rule'] != 'root-or-entitled-admin-or-app-specific-admin': formatted['rule'] = 'root-or-entitled-admin-or-app-specific-admin'
def serialize_plist(data): if sys.version_info >= (3, 4): return plistlib.dumps(data, fmt=plistlib.FMT_XML).decode('utf-8') else: return plistlib.writePlistToString(data)
'child' : {} } if options.encryption: params['ike']['EncryptionAlgorithm'] = options.encryption params['child']['EncryptionAlgorithm'] = options.encryption if options.child_encryption: params['child']['EncryptionAlgorithm'] = options.child_encryption if options.integrity: params['ike']['IntegrityAlgorithm'] = options.integrity params['child']['IntegrityAlgorithm'] = options.integrity if options.child_integrity: params['child']['IntegrityAlgorithm'] = options.child_integrity if options.dhgroup: params['ike']['DiffieHellmanGroup'] = options.dhgroup params['child']['DiffieHellmanGroup'] = options.dhgroup if options.child_dhgroup: params['child']['DiffieHellmanGroup'] = options.child_dhgroup netconfig.update_params(options.config_name, params) if options.dry_run: print plistlib.writePlistToString(netconfig.plist) sys.exit(0) plistlib.writePlist(netconfig.plist, options.file)
def to_raw(self): return plistlib.writePlistToString(self)
def test_appleformatting(self): pl = plistlib.readPlistFromString(TESTDATA) data = plistlib.writePlistToString(pl) self.assertEqual(data, TESTDATA, "generated data was not identical to Apple's output")
#!/usr/bin/python2.7 import os import plistlib d = { 'ApImg4Ticket': plistlib.Data(open('apticket.der', 'rb').read()), 'BBTicket': plistlib.Data(open('bbticket.der', 'rb').read()), } print plistlib.writePlistToString(d)
def sign(self, oldsig, cd_hashes): """ sign data, return string. Only modifies an existing CMS structure """ parsed_sig = asn1crypto.cms.ContentInfo.load(oldsig) with open(self.signer_cert_file, 'rb') as fh: _, _, der_bytes = asn1crypto.pem.unarmor(fh.read()) signer_cert = asn1crypto.x509.Certificate.load(der_bytes) # find all the serial numbers of certs that were used for signing (usually there's just one) signer_serials = [ signer_info['sid'].native['serial_number'] for signer_info in parsed_sig['content']['signer_infos'] ] # replace any certs used for signing with the new one for i, cert in enumerate(parsed_sig['content']['certificates']): if cert.chosen.serial_number in signer_serials: parsed_sig['content']['certificates'][ i] = asn1crypto.cms.CertificateChoices( "certificate", signer_cert) for signer_info in parsed_sig['content']['signer_infos']: # Update signer cert info signer_info['sid'] = asn1crypto.cms.SignerIdentifier( 'issuer_and_serial_number', asn1crypto.cms.IssuerAndSerialNumber( dict(issuer=signer_cert.issuer, serial_number=signer_cert.serial_number))) # Update signingTime signer_info['signed_attrs'][1][1][0] = asn1crypto.cms.Time( "utc_time", datetime.utcnow()) # Update messageDigest signer_info['signed_attrs'][2][1][0] = cd_hashes[0][ SHA256_HASHTYPE] # Update complete list of CodeDirectory hashes SHA1_OID = '1.3.14.3.2.26' SHA256_OID = '2.16.840.1.101.3.4.2.1' class HashEntry(asn1crypto.core.Sequence): _fields = [("ident", asn1crypto.core.ObjectIdentifier), ("value", asn1crypto.core.OctetString)] for i, entry in enumerate(signer_info['signed_attrs'][3][1]): parsed = entry.parse() if parsed[0].native == SHA1_OID: for cd_hash in cd_hashes: if cd_hash['hashType'] == SHA1_HASHTYPE: val = cd_hash[SHA1_HASHTYPE] elif parsed[0].native == SHA256_OID: for cd_hash in cd_hashes: if cd_hash['hashType'] == SHA256_HASHTYPE: val = cd_hash[SHA256_HASHTYPE] else: raise ValueError('unexpected entry %s' % parsed[0].native) signer_info['signed_attrs'][3][1][i] = asn1crypto.core.Any( HashEntry({ "ident": parsed[0], "value": asn1crypto.core.OctetString(val) })) # Update plist of truncated CodeDirectory hashes plist = plistlib.readPlistFromString( signer_info['signed_attrs'][4][1][0].native) plist['cdhashes'] = [ plistlib.Data(cd_hash[cd_hash['hashType']][:20]) for cd_hash in cd_hashes ] signer_info['signed_attrs'][4][1][0] = asn1crypto.core.Any( asn1crypto.core.OctetString( plistlib.writePlistToString(plist))) to_sign = signer_info['signed_attrs'].dump() to_sign = '1' + to_sign[ 1:] # change type from IMPLICIT [0] to EXPLICIT SET OF, per RFC 5652. pkcs1sig = self.signer.sign(to_sign) signer_info['signature'] = pkcs1sig return parsed_sig.dump()
def test_indentation_dict_mix(self): data = {'1': {'2': [{'3': [[[[[{'test': plistlib.Data(b'aaaaaa')}]]]]]}]}} self.assertEqual(plistlib.readPlistFromString(plistlib.writePlistToString(data)), data)
def test_indentation_array(self): data = [[[[[[[[{'test': plistlib.Data(b'aaaaaa')}]]]]]]]] self.assertEqual(plistlib.readPlistFromString(plistlib.writePlistToString(data)), data)
def generate(identifier, profile_uuid=None, **kwargs): ''' Generate a configuration profile. Intended to be used by other execution and state modules to prepare a profile for installation. Not really intended for CLI usage. As per the documentation, only the identifier and uuid are actually compulsory keys. It is possible to make a profile without anything else, however the profile will be downright useless. identifier The profile identifier, which is the primary key for identifying whether a profile is installed. profile_uuid Normally you would leave this blank, and the module will generate a UUID for you. However, if you specifically need to test with a fixed uuid, this can be set. Keyword arguments: description Description of the profile displayname The name of the profile shown to the user organization The organization issuing the profile content The payload content for the profile, as a hash removaldisallowed : False Whether removal of the profile will be allowed scope : System The scope of items to install, the default is system wide but may also be user. Note that only the System scope really makes sense in salt. removaldate The date on which the profile will be automatically removed. durationuntilremoval The number of seconds until profile is automatically removed, the smaller of this and removaldate will be used. consenttext : { "default": "message" } The warning/disclaimer shown when installing the profile interactively. ''' if not profile_uuid: profile_uuid = uuid.uuid4() log.debug("Creating new profile with UUID: {}".format(str(profile_uuid))) VALID_PROPERTIES = [ 'description', 'displayname', 'organization', 'content', 'removaldisallowed', 'scope', 'removaldate', 'durationuntilremoval', 'consenttext' ] log.debug('Looping through kwargs') validkwargs = { k: v for k, v in kwargs.iteritems() if k in VALID_PROPERTIES } document = { 'PayloadScope': 'System', 'PayloadUUID': str(profile_uuid), 'PayloadVersion': 1, 'PayloadType': 'Configuration', 'PayloadIdentifier': identifier } for k, v in validkwargs.items(): if k in ('__id__', 'fun', 'state', '__env__', '__sls__', 'order', 'watch', 'watch_in', 'require', 'require_in', 'prereq', 'prereq_in'): pass elif k == 'content': # As per managedmac for puppet, it's necessary to generate UUIDs for each payload based upon the content # in order to detect changes to the payload. # Transform a dict of { type: data } to { PayloadContent: data, } payload_content = _transform_content(kwargs['content'], identifier) document['PayloadContent'] = payload_content elif k == 'description': document['PayloadDescription'] = v elif k == 'displayname': document['PayloadDisplayName'] = v elif k == 'organization': document['PayloadOrganization'] = v elif k == 'removaldisallowed': document['PayloadRemovalDisallowed'] = (v is True) plist_content = plistlib.writePlistToString(document) return plist_content
def build_request(self, path, method, headers, content): content = writePlistToString(content) request = super(StreamsTestCase, self) \ .build_request(path, method, headers, content) return request
def encode(self, plist): string = plistlib.writePlistToString(plist) bz2data = bz2.compress(string) b64data = base64.b64encode(bz2data) return b64data
def to_plist_string(self): return plistlib.writePlistToString(self.root_dict)
def setUp(self): self.good_env = {"find_method": "glob", "pattern": "test"} self.bad_env = {"find_method": "fake"} self.input_plist = StringIO.StringIO(plistlib.writePlistToString(self.good_env)) self.processor = FileFinder(infile=self.input_plist)
if (not escrowBag): escrowBag = self.record['EscrowBag'] self.c.sendPlist({ "Label": self.label, "Request": "StartService", "Service": name, 'EscrowBag': escrowBag }) StartService = self.c.recvPlist() if not StartService or StartService.get("Error"): if StartService.get("Error", "") == 'PasswordProtected': raise StartServiceError( 'your device is protected with password, please enter password in device and try again' ) raise StartServiceError(StartService.get("Error")) return PlistService(StartService.get("Port"), self.udid) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) l = LockdownClient() if l: n = writeHomeFile(HOMEFOLDER, "%s_infos.plist" % l.udid, plistlib.writePlistToString(l.allValues)) logger.info("Wrote infos to %s", n) else: logger.error("Unable to connect to device")
def main(): description = "A python script to create nopkg-style files for installing printers onto client systems using Munki (https://github.com/munki/munki). Printers can be imported from a pre-existing XML plist file or can be created interactively. Unless a file path is specified with -o, the pkg file will be written to STDOUT. This script has been updated to ONLY support the new IPP - Internet Printing Protocol since Apple deprecated ppd files and drivers. PPD files and printer drivers are deprecated and will not be supported in a future version of CUPS." epilog = "To import printers into Munki, copy the output file to the pkgsinfo/ directory of your Munki repo and then re-run makecatalogs" o = argparse.ArgumentParser(description=description, epilog=epilog) o.add_argument( "-p", "--plist", help= "Path to an XML plist file containing key/value pairs for version, display_name, queue_name, ipp, location, and other options. See example-printer.plist for an example." ) o.add_argument( '-i', '--interactive', help= "Create pkginfo file in interactive mode rather than with a .plist file", action="store_true") o.add_argument('-o', '--outfile', help="Write pkginfo to plist file rather than STDOUT") o.add_argument( '-c', '--catalog', default='testing', help="Set Munki catalog (default without -c is \"testing\")") o.add_argument( '-v', '--version', default=0.1, help= "Set package version if creating an updated pkginfo file for an existing printer (default without -v is 0.1)", type=float) o.add_argument( '--prefix', help= "With -i, set prefix for printer name as it appears in Munki manifests" ) args = o.parse_args() if args.interactive and args.outfile is None: o.error( "Interactive mode (-i) requires output file to be specified with -o" ) if args.plist: plist_opts = plistInput(args.plist) elif args.interactive: plist_opts = interactiveInput() try: if args['version']: version = args['version'] else: version = plist_opts.getVersion() except: version = '0.1' options = plist_opts.getOptions() try: if args.catalog: catalog = args.catalog else: catalog = plist_opts.getDefaultCatalog() except: catalog = 'testing' developer = plist_opts.getDefaultDeveloper() category = plist_opts.getDefaultCategory() protocol = plist_opts.getProtocol() formatted_options = "" if options: for option in options: built = "-o " + option + " " formatted_options = formatted_options + built queue_name = plist_opts.getQueueName() name = plist_opts.getName() if args.prefix: name = args.prefix + name if len(queue_name) > 24: fail("Queue name is too long") display_name = plist_opts.getDisplayName() ipp = plist_opts['ipp'] location = plist_opts.getLocation() if queue_name: address = plist_opts.getAddress() + "/" + queue_name else: address = plist_opts.getAddress() # build the install check script install_check_content = """#!/bin/zsh # Based on 2010 Walter Meyer SUNY Purchase College (c) # Modified by Nick McSpadden, 2013 # Script to install and setup printers on a Mac OS X system in a "Munki-Friendly" way. # Make sure to install the required drivers first! # Variables. Edit these. printername="%s" location="%s" gui_display_name="%s" address="%s" driver_ipp="%s" # Populate these options if you want to set specific options for the printer. E.g. duplexing installed, etc. option_1="" option_2="" option_3="" currentVersion="%s" function exitWithStatus () { if [ $1 -eq 0 ]; then echo "INSTALL REQUIRED" else echo "NO INSTALL REQUIRED" fi echo "-------------------" echo "" exit $1 } echo "--------------------------------" echo "Checking $printername Printer... " echo "--------------------------------" ### Determine if receipt is installed ### printf "Receipt: " if [ -e "/private/etc/cups/deployment/receipts/$printername.plist" ]; then storedVersion=$(/usr/libexec/PlistBuddy -c "Print :version" "/private/etc/cups/deployment/receipts/$printername.plist") echo $storedVersion else echo "not stored." storedVersion="0" fi versionComparison=$(echo "$storedVersion < $currentVersion" | bc -l) # This will be 0 if the current receipt is greater than or equal to current version of the script printf "State: " ### Printer Install ### # If the queue already exists (returns 0), we don't need to reinstall it. LPSTATOUTPUT=$(/usr/bin/lpstat -p "$printername" 2>&1) if [ $? -eq 0 ]; then if [ "$versionComparison" -eq 0 ]; then # We are at the current or greater version echo "Configured." exitWithStatus 1 fi # We are of lesser version, and therefore we should delete the printer and reinstall. echo "Configured, but receipt version $storedVersion doesn't match $currentVersion." exitWithStatus 0 else # Not configured. For verbosity, say unconfigured and exit with status 0" echo "Unconfigured. $LPSTATOUTPUT" exitWithStatus 0 fi """ % (queue_name, location, display_name, address, ipp, version) postinstall_content = """#!/bin/zsh # Based on 2010 Walter Meyer SUNY Purchase College (c) # Modified by Nick McSpadden, 2013 # Script to install and setup printers on a Mac OS X system in a "Munki-Friendly" way. # Make sure to install the required drivers first! # Variables. Edit these. printername="%s" location="%s" gui_display_name="%s" address="%s" driver_ipp="%s" # Populate these options if you want to set specific options for the printer. E.g. duplexing installed, etc. option_1="" option_2="" option_3="" currentVersion="%s" protocol="%s" function exitWithStatus () { if [ $1 -eq 0 ]; then echo "INSTALL SUCCESSFUL" echo exit 0 fi echo "ERROR WITH INSTALL" echo exit 1 } ### Determine if receipt is installed ### if [ -e "/private/etc/cups/deployment/receipts/$printername.plist" ]; then storedVersion=$(/usr/libexec/PlistBuddy -c "Print :version" "/private/etc/cups/deployment/receipts/$printername.plist") else storedVersion="0" fi versionComparison=$(echo "$storedVersion < $currentVersion" | bc -l) # This will be 0 if the current receipt is greater than or equal to current version of the script ### Printer Install ### # If the queue already exists (returns 0), we don't need to reinstall it. LPSTATOUTPUT=$(/usr/bin/lpstat -p "$printername" 2>&1) if [ $? -eq 0 ]; then if [ "$versionComparison" -eq 0 ]; then # We are at the current or greater version exitWithStatus 0 fi # We are of lesser version, and therefore we should delete the printer and reinstall. printf "Newer install (${currentVersion})... removing existing printer ($printername)... " /usr/sbin/lpadmin -x "$printername" fi # Now we can install the printer. printf "Adding $printername... " /usr/sbin/lpadmin \ -p "$printername" \ -L "$location" \ -D "$gui_display_name" \ -v "${protocol}"://"${address}" \ -m "$driver_ipp" \ %s \ -o printer-is-shared=false \ -o printer-error-policy=abort-job \ -E if [ $? -ne 0 ]; then echo "Failed adding printer... Removing... " /usr/sbin/lpadmin -x "$printername" exitWithStatus 1 fi # Get list of configured printers CONFIGUREDPRINTERS=$(lpstat -p | grep -w "printer" | awk '{print$2}' | tr '\n' ' ') # Check if configured. if [ $(echo "$CONFIGUREDPRINTERS" | grep -w "$printername" | wc -l | tr -d ' ') -eq 0 ]; then echo "ERROR" echo "$printername not in lpstat list after being configured. Currently configured printers are: $CONFIGUREDPRINTERS" exitWithStatus 1 fi # Enable and start the printers on the system (after adding the printer initially it is paused). printf "Enabling... " /usr/sbin/cupsenable $CONFIGUREDPRINTERS # Create a receipt for the printer printf "Creating v${currentVersion} receipt... " mkdir -p /private/etc/cups/deployment/receipts PLISTBUDDYOUTPUT=$(/usr/libexec/PlistBuddy -c "Add :version string" "/private/etc/cups/deployment/receipts/$printername.plist" 2>&1) PLISTBUDDYOUTPUT+=$(/usr/libexec/PlistBuddy -c "Set :version $currentVersion" "/private/etc/cups/deployment/receipts/$printername.plist" 2>&1) # If problem setting version in receipt (above command), we tell user if [ $? -ne 0 ]; then echo "ERROR with receipt creation: $PLISTBUDDYOUTPUT" fi # Permission the directories properly. chown -R root:_lp /private/etc/cups/deployment chmod -R 700 /private/etc/cups/deployment echo "Complete!" echo "Current printers: $CONFIGUREDPRINTERS" exitWithStatus 0 """ % (queue_name, location, display_name, address, ipp, version, protocol, formatted_options) uninstall_content = """#!/bin/zsh printerName="%s" printf "Removing $printername... " /usr/sbin/lpadmin -x $printerName printf "Removing receipt... " rm -f /private/etc/cups/deployment/receipts/$printerName.plist echo "Uninstall complete." """ % (queue_name) # write the scripts to temp files tempdir = tempfile.mkdtemp() installcheck = os.path.join(tempdir, 'installcheck') f = open(installcheck, "w") f.write(install_check_content) f.close() installcheck_option = "--installcheck_script=%s" % installcheck postinstall = os.path.join(tempdir, 'postinstall') f = open(postinstall, "w") f.write(postinstall_content) f.close() postinstall_option = "--postinstall_script=%s" % postinstall uninstall = os.path.join(tempdir, 'uninstall') f = open(uninstall, "w") f.write(uninstall_content) f.close() uninstall_option = "--uninstall_script=%s" % uninstall catalog_opt = str('-c' + catalog) name_opt = '--name=%s' % name version_opt = '--pkgvers=%s' % version developer_opt = '--developer=%s' % developer category_opt = '--category=%s' % category displayname_opt = '--displayname=%s' % display_name # make pkg info cmd = [ makepkginfo, installcheck_option, postinstall_option, uninstall_option, name_opt, version_opt, catalog_opt, developer_opt, category_opt, displayname_opt, '--unattended_install', '--uninstall_method=uninstall_script', '--nopkg' ] task = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = task.communicate() pkginfo = plistlib.readPlistFromString(stdout) # read it back so we can add in the requires (if required, sic) # if args.plist and plist_opts['requires']: # requires = plist_opts.get('requires') # pkginfo['requires'] = requires # Add Uninstallable flag uninstallable = True pkginfo['uninstallable'] = uninstallable if args.outfile: plistlib.writePlist(pkginfo, args.outfile) else: print((plistlib.writePlistToString(pkginfo)))
xcTestFile.write(",\n".join(xctestInvocations)) xcTestFile.write("\n};") os.chmod(runAllScriptPath, 0755) runAllFilesInstallTarget = ninja.newTarget( "install", "$INSTALL_DIR/AppleInternal/CoreOS/tests/dyld/run_all_dyld_tests.sh" ) runAllFilesInstallTarget.addInput( "$DERIVED_FILES_DIR/run_all_dyld_tests.sh") masterInstallTarget.addInput(runAllFilesInstallTarget) batsFilePath = derivedFilesDir + "/dyld.plist" batsTests.sort(key=lambda test: test["TestName"]) with BufferedFile(batsFilePath) as batsFile: batsConfig = { "BATSConfigVersion": "0.1.0", "Project": "dyld_tests", "Tests": batsTests } if batsSuppressedCrashes: batsConfig["IgnoreCrashes"] = batsSuppressedCrashes batsFile.write(plistlib.writePlistToString(batsConfig)) os.system('plutil -convert binary1 ' + batsFilePath) # convert the plist in place to binary batsConfigInstallTarget = ninja.newTarget( "install", "$INSTALL_DIR/AppleInternal/CoreOS/BATS/unit_tests/dyld.plist") batsConfigInstallTarget.addInput(batsFilePath) batsConfigInstallTarget.addVariable("mode", "0644") masterInstallTarget.addInput(batsConfigInstallTarget) sys.stdout.write("DONE\n")
def _encode(self, obj, context): return plistlib.writePlistToString(obj)
def sendPlist(self, d): payload = plistlib.writePlistToString(d) #print '>>>>',payload l = struct.pack(">L", len(payload)) self.send(l + payload)
def test_indentation_dict(self): data = {'1': {'2': {'3': {'4': {'5': {'6': {'7': {'8': {'9': plistlib.Data(b'aaaaaa')}}}}}}}}} self.assertEqual(plistlib.readPlistFromString(plistlib.writePlistToString(data)), data)
def _make_plist(d): if hasattr(plistlib, 'dumps'): return plistlib.dumps(d) else: as_str = plistlib.writePlistToString(d) return bytes(as_str)
def render(self, *args, **kwargs): context = self.get_context(*args, **kwargs) if sys.version < '3': return plistlib.writePlistToString(context) return plistlib.writePlistToBytes(context).decode('unicode_escape')
def StringFromObject(obj): return plistlib.writePlistToString(obj)