Python Forum

Full Version: Ldap Search for finding user Groups
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to do ldap search for finding users groups.

I have this. I doesnt totally give me the result that i want but it works. If you have a query that more useful please inform me.

ldapsearch -x -H "ldap://192.168.1.240:3268" -D "Administrator@myserver" -w "mypassword" -b "dc=my,dc=server" '(sAMAccountName=user1)'
I want to run this command in my python code. I have the code

import os

cmd = ' ldapsearch -x -H "ldap://192.168.1.240:3268" -D "Administrator@myserverl" -w "mypassword" -b "dc=my, dc=server" '(sAMAccountName=user1)' '


print(os.system(cmd))
It gives me the error


^
SyntaxError: invalid syntax
You can use shlex.split to split the str, like the shell does it.
The SyntaxError is raised because the quotes are wrong. If you have mixed single quotes and double quotes in one string,
you can use triple single quotes or triple double quotes. Example with triple double quotes:
name = """This "is" " ' A ' Test''' """
But this does not address the problem itself. The use of os.system should be avoided.


import shlex


command = shlex.split("""   censored   '""")

print(command)
Output:
['ldapsearch', ...]
os.system should not be used because it's limited (stdout does not return) and it has security issues.

Instead, use subprocess.Popen or subprocess.check_output. subprocess.check_output
raises a CalledProcessError if the called process returns with non-zero. If the program was not found, a FileNotFoundError is raised. If the program exists, but you're not allowed to run the program (missing execute permission), a PermissionError is raised.



from subprocess import CalledProcessError, check_output


def search():
    cmd = [
        'ldapsearch',
        ...
    ]
    try:
        return check_output(cmd, encoding="utf8")
    except CalledProcessError:
        pass
    except FileNotFoundError:
        raise RuntimeError("The program `ldapsearch` is not installed.")
Then you can use the function also to submit different addresses to your ldapsearch.

from subprocess import CalledProcessError, check_output


def search(ip, port=3268):
    cmd = [
        'ldapsearch',
        '-H',
        f'ldap://{ip}:{port}',
        ...,
    ]
    try:
        return check_output(cmd, encoding="utf8")
    except CalledProcessError:
        pass
    except FileNotFoundError:
        raise RuntimeError("The program `ldapsearch` is not installed.")