Skip to main content
 首页 » 编程设计

python之如何在不使用 Python 在本地保存文件的情况下,将使用 urllib2.urlopen 检索到的二进制 plist 操作为可读的 xml plist

2025年05月04日10zhenyulu

我们使用 Python 脚本与我们的 Deploy Studio 服务器通信,以使用 Deploy Studio 的 Web 访问 URL 自动更新用户和计算机信息。由于最近的变化,他们现在以二进制 plist 格式而不是 XML 存储计算机的 Plist。

这是当前适用于旧版 DS 的内容(来源:http://macops.ca/interfacing-with-deploystudio-using-http/):

#!/usr/bin/python 
 
import urllib2 
import plistlib 
from random import randrange 
 
host = 'https://my.ds.repo:60443' 
adminuser = 'testdsuser' 
adminpass = '12345' 
 
 
def setupAuth(): 
    """Install an HTTP Basic Authorization header globally so it's used for 
every request.""" 
    auth_handler = urllib2.HTTPBasicAuthHandler() 
    auth_handler.add_password(realm='DeployStudioServer', 
                              uri=host, 
                              user=adminuser, 
                              passwd=adminpass) 
    opener = urllib2.build_opener(auth_handler) 
    urllib2.install_opener(opener) 
 
 
def getHostData(machine_id): 
    """Return the full plist for a computer entry""" 
    machine_data = urllib2.urlopen(host + '/computers/get/entry?id=%s' % machine_id) 
    plist = plistlib.readPlistFromString(machine_data.read()) 
    # if id isn't found, result will be an empty plist 
    return plist 
 
 
def updateHostProperties(machine_id, properties, key_mac_addr=False, create_new=False): 
    """Update the computer at machine_id with properties, a dict of properties and 
values we want to set with new values. Return the full addinfourl object or None 
if we found no computer to update and we aren't creating a new one. Set create_new 
to True in order to enable creating new entries.""" 
    found_comp = getHostData(machine_id) 
 
    # If we found no computer and we don't want a new record created 
    if not found_comp and not create_new: 
        return None 
 
    new_data = {} 
    if found_comp: 
        # Computer data comes back as plist nested like: {'SERIALNO': {'cn': 'my-name'}} 
        # DeployStudioServer expects a /set/entry POST like: {'cn': 'my-new-name'} 
        # so we copy the keys up a level 
        update = dict((k, v) for (k, v) in found_comp[machine_id].items()) 
        new_data = update.copy() 
    else: 
        # No computer exists for this ID, we need to set up two required keys: 
        # 'dstudio-host-primary-key' and one of 'dstudio-host-serial-number' 
        # or 'dstudio-mac-addr' is required, otherwise request is ignored 
        # - IOW: you can't only rely on status codes 
        # - primary key is a server-level config, but we seem to need this per-host 
        if key_mac_addr: 
            new_data['dstudio-host-primary-key'] = 'dstudio-mac-addr' 
        else: 
            new_data['dstudio-host-primary-key'] = 'dstudio-host-serial-number' 
        new_data[new_data['dstudio-host-primary-key']] = machine_id 
 
    for (k, v) in properties.items(): 
        new_data[k] = v 
    plist_to_post = plistlib.writePlistToString(new_data) 
    result = urllib2.urlopen(host + '/computers/set/entry?id=' + machine_id, 
                            plist_to_post) 
    return result 
 
 
def main(): 
    setupAuth() 
 
    # Update HOWSANNIE with a new computer name (assuming this entry already exists) 
    random_name = 'random-id-' + str(randrange(100)) 
    result = updateHostProperties('HOWSANNIE', {'cn': random_name, 
                                            'dstudio-hostname': random_name}) 
 
    # Update DOUGLASFIRS with a new computername and custom properties, or create 
    # it if it doesn't already exist 
    random_name = 'random-id-' + str(randrange(100)) 
    updateHostProperties('DOUGLASFIRS', 
                    {'cn': random_name, 
                    'dstudio-hostname': random_name, 
                    'dstudio-custom-properties': [{ 
                        'dstudio-custom-property-key': 'ASSET_TAG', 
                        'dstudio-custom-property-label': 'My Great Asset Tag', 
                        'dstudio-custom-property-value': 'BL4CKL0DG3'}] 
                    }, 
                    create_new=True) 
 
if __name__ == "__main__": 
    main() 

我们将其与自主开发的网络界面结合使用,以便我们的技术人员在重新成像机器时输入信息,并自动更新我们 DS 数据库中的信息。

我试过使用诸如 biplist 之类的库无济于事。我宁愿不必将文件本地存储在服务器上,然后使用 bash 命令转换它 plutil .无论如何我可以操纵存储信息的变量吗?在这种情况下,它将是“machine_data”。

我已经成功地使用带有 -o 标志的 bash 命令 curl 来指示将文件保存为 .plist 文件,但如前所述,我希望尽可能不在本地保存文件。

部署可用的 Studio Web 服务: .

请您参考如下方法:

只需将@martijn-pieters 的所有评论汇总成一个答案:

pip 安装 biplist

import urllib2 
import io 
import biplist 
 
sock = urllib2.urlopen('https://cfpropertylist.googlecode.com/svn/trunk/examples/sample.binary.plist' ) 
buf = io.BytesIO(sock.read()) 
xml = biplist.readPlist(buf) 
print xml 

输出:

{'Pets Names': [], 'Name': 'John Doe', 'Picture': '<B\x81\xa5\x81\xa5\x99\x81B<', 'Year Of Birth': 1965, 'Date Of Graduation': datetime.datetime(2004, 6, 22, 19, 23, 43), 'City Of Birth': 'Springfield', 'Kids Names': ['John', 'Kyra']}