以下是我的代码,用于在虚拟环境中使用python3在LDAP中添加用户,但收到此错误
('Tuple_to_LDAPMod((:列表中应为字节字符串','inetOrgPerson'(">
import ldap
con = ldap.initialize('ldap://127.0.0.1')
ldap_base = "dc=example,dc=com"
dn = "uid=hasnain,ou=Users,dc=example,dc=com"
modlist = {
"objectClass": ["inetOrgPerson", "posixAccount", "shadowAccount"],
"uid": ["hasnain"],
"sn": ["Hasnain"],
"givenName": ["Muhammad"],
"mail": ["hasnain@example.com"],
"cn": ["Muhammad Hasnain"],
"displayName": ["Muhammad Hasnain"],
"gecos": ["Muhammad Hasnain"],
"uidNumber": ["10001"],
"gidNumber": ["5001"],
"loginShell": ["/bin/bash"],
"homeDirectory": ["/home/hasnain"]
}
result = con.add_s(dn, ldap.modlist.addModlist(modlist))
你能帮我怎么解决这个吗
答案就在错误消息中:您需要使用字节字符串。
在Python3中创建字节字符串的两种方法是:
1:从一开始就将字符串创建为字节字符串
example_bytestring = b"Foo Bar"
2:对现有字符串进行编码以获得字节字符串
example_bytestring = some_string.encode("utf-8")
因此,在您的情况下,只需执行:
modlist = {
"objectClass": [b"inetOrgPerson", b"posixAccount", b"shadowAccount"],
"uid": [b"hasnain"],
"sn": [b"Hasnain"],
"givenName": [b"Muhammad"],
"mail": [b"hasnain@example.com"],
"cn": [b"Muhammad Hasnain"],
"displayName": [b"Muhammad Hasnain"],
"gecos": [b"Muhammad Hasnain"],
"uidNumber": [b"10001"],
"gidNumber": [b"5001"],
"loginShell": [b"/bin/bash"],
"homeDirectory": [b"/home/hasnain"]
}
或者把它放在你的modlist之后,将所有v的值编码为utf-8:
modlist = {key:[v.encode("utf-8") for v in values] for key, values in modlist.items()}
但是,如果其中一个值已经是字节字符串,则此操作将失败。如果你想处理这个问题,请使用:
modlist = {key:[v.encode("utf-8") if type(v) == str else v for v in values] for key, values in modlist.items()}
更多详细信息
Python使用unicode字符串表示。LDAP需要字节字符串,这意味着您需要从一开始就将字符串定义为字节字符串,或者在使用它们之前需要对它们进行转换。
正如您所看到的,标准字符串的类型为str
:
>>type("foo")
str
而字节字符串的类型为bytes
:
>>type(b"foo")
bytes