How can I check in python3 whether the username and password are valid?
I already ask the user for username and password:
import getpass
import sys
sys.stdout.write("- Enter your (LDAP) username : ")
username = input().lower()
password=getpass.getpass("- Enter your (LDAP) password : ")
I know I could use ldapwhoami
to check the validity, something like:
import subprocess
subprocess.run(['ldapwhoami', '-h', 'ldap-server', '-D', '{}@domain'.format(username)', '-x',
'-w', password], check=True)
but then a process would be spawned in which the password would be visible. So how could I check these credentials in a safe way? Either hiding the password, either using a python library or something like that?
You can obtain this using the python-ldap
library, thus no separate process is spawned.
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!")