python3 以安全的方式检查 ldap 用户名和密码

python3 check ldap username and password in a safe way

如何检查python3用户名和密码是否有效?

我已经要求用户提供用户名和密码:

import getpass
import sys

sys.stdout.write("- Enter your (LDAP) username : ")
    username = input().lower()
password=getpass.getpass("- Enter your (LDAP) password : ")

我知道我可以使用 ldapwhoami 来检查有效性,例如:

import subprocess

subprocess.run(['ldapwhoami', '-h', 'ldap-server', '-D', '{}@domain'.format(username)', '-x', 
                '-w', password], check=True)

但随后会生成一个进程,在该进程中可以看到密码。那么我怎样才能以安全的方式检查这些凭据呢?使用 python 库或类似的东西隐藏密码?

您可以使用 python-ldap 库获取它,因此不会产生单独的进程。

import ldap
try:
    # build a client
    ldap_client = ldap.initialize("ldap://ldap-server.domain")
    # perform a synchronous bind
    ldap_client.set_option(ldap.OPT_REFERRALS, 0)
    ldap_client.simple_bind_s("{}@domain".format(username), password)
    print("LDAP credentials were good!")
except ldap.INVALID_CREDENTIALS:
    ldap_client.unbind()
    print("LDAP credentials incorrect!")