MacOS Monterey配置Google安全LDAP时Python脚本报错求助
解决Google安全LDAP配置脚本中的TypeError: Expecting byte-buffer, got str
你遇到的错误核心原因是:NSData.dataWithBytes_length_方法要求接收字节缓冲区(bytes类型),但你读取配置文件后得到的CONFIG是字符串(str类型),类型不匹配触发了报错。
以下是两种直接可行的修复方案,任选其一即可:
方案1:以二进制模式读取配置文件
修改文件读取逻辑,用"rb"(二进制只读)模式打开配置文件,这样读取到的内容直接是bytes类型,无需额外转换:
# Reading plist GOOGLELDAPCONFIGFILE = open(sys.argv[1], "rb") # 将"r"替换为"rb" CONFIG = GOOGLELDAPCONFIGFILE.read() GOOGLELDAPCONFIGFILE.close()
方案2:将字符串编码为字节
如果保持文本模式读取,在传入NSData.dataWithBytes_length_前,把字符串编码为UTF-8格式的字节数据:
request.appendData_(NSData.dataWithBytes_length_(CONFIG.encode('utf-8'), len(CONFIG)))
encode('utf-8')会把Unicode字符串转换成符合标准的二进制字节流,满足API的参数要求。
修复后的完整脚本示例(采用方案1)
#!/usr/bin/python from OpenDirectory import ODNode, ODSession, kODNodeTypeConfigure from Foundation import NSMutableData, NSData import os import sys # Reading plist (二进制模式读取) GOOGLELDAPCONFIGFILE = open(sys.argv[1], "rb") CONFIG = GOOGLELDAPCONFIGFILE.read() GOOGLELDAPCONFIGFILE.close() # Write the plist od_session = ODSession.defaultSession() od_conf_node, err = ODNode.nodeWithSession_type_error_(od_session, kODNodeTypeConfigure, None) request = NSMutableData.dataWithBytes_length_(b'\x00'*32, 32) request.appendData_(NSData.dataWithBytes_length_(CONFIG, len(CONFIG))) response, err = od_conf_node.customCall_sendData_error_(99991, request, None) # Edit the default search path and append the new node to allow for login os.system("dscl -q localhost -append /Search CSPSearchPath /LDAPv3/ldap.google.com") os.system("bash -c 'echo -e \"TLS_IDENTITY\tLDAP Client\" >> /etc/openldap/ldap.conf' ")
补充说明
Python中,字符串(str)是用于表示文本的Unicode序列,而字节(bytes)是计算机底层直接处理的二进制数据。Apple的Foundation框架绑定(比如NSData)底层操作的是二进制数据,因此必须传递bytes类型参数,不能直接使用字符串。
内容的提问来源于stack exchange,提问作者Dominik Jaro
相关产品推荐
相关产品推荐

