LDAP Query in Python3 - python-3.x

I have an LDAP Query which is running perfectly fine in my terminal
ldapsearch -h ldap.mygreatcompany.com -D user#mygreatcompany.COM -w "$ldappassword" -b "DC=abc,DC=mygreatcompany,DC=com" -s sub "(mail=user1#mygreatcompany.COM)" sAMAccountName
I want to run this command in python3, I followed other answers from StackOverflow and wrote something like this,
import ldap
l = ldap.initialize('ldap://ldap.mygreatcompany.com')
binddn = "user#mygreatcompany.COM"
pw = #ldappassword
basedn = "DC=abc,DC=mygreatcompany,DC=com"
searchAttribute = ["sAMAccountName"]
searchFilter = "(&(mail=user1#mygreatcompany.COM')(objectClass=*))"
searchScope = ldap.SCOPE_SUBTREE
l.simple_bind_s(binddn, pw)
ldap_result_id = l.search_s(basedn, searchScope, searchFilter, searchAttribute)
#Get result
l.unbind_s()
But Here I am not getting the result from ldap_result_id. Can anybody help what is the correct way to do this query?
Thanks

It turns out that I was not using connection.set_option(ldap.OPT_REFERRALS, 0) in the code and there is some issue in LDAP which automatically chases the referrals internally with anonymous access which fails.
Here is the working code:
def get_user_id(email):
# Seach fiter for user mail
searchFilter = "mail={}".format(email)
try:
# binding to ldap server
connection = ldap.initialize('ldap://yourcompanyhost')
connection.set_option(ldap.OPT_REFERRALS, 0)
connection.protocol_version = ldap.VERSION3
connection.simple_bind_s(binddn, pwd)
# get result
ldap_result_id = connection.search_s(basedn, searchScope, searchFilter, searchAttribute)
# extract the id
saMAccount = ldap_result_id[0][1]["sAMAccountName"][0].decode('utf-8')
except ldap.INVALID_CREDENTIALS:
print("Your username or password is incorrect.")
except ldap.LDAPError as e:
print(e)
except:
print("Data doesn't exist for this user")
connection.unbind_s()
print(get_user_id("user1#mygreatcompany.COM"))

Related

Execute customized script when launching instance using openstacksdk

I'm new to Openstack and I'm trying to create a tool so that I can launch any number of instances in an Openstack cloud. This was easily done using the nova-client module of openstacksdk.
Now the problem is that I want to make the instances execute a bash script as they are created by adding it as a userdata file, but it doesn't execute. This is confusing because I don't any error or warning message. Does anyone know what could it be?
Important parts of the code
The most important parts of the Python program are the function which gets the cloud info, the one that creates the instances and the main function, . I'll post them here as #Corey told.
"""
Function that allow us to log at cloud with all the credentials needed.
Username and password are not read from env.
"""
def get_nova_credentials_v2():
d = {}
user = ""
password = ""
print("Logging in...")
user = input("Username: ")
password = getpass.getpass(prompt="Password: ", stream=None)
while (user == "" or password == ""):
print("User or password field is empty")
user = input("Username: ")
password = getpass.getpass(prompt="Password: ", stream=None)
d['version'] = '2.65'
d['username'] = user
d['password'] = password
d['project_id'] = os.environ['OS_PROJECT_ID']
d['auth_url'] = os.environ['OS_AUTH_URL']
d['user_domain_name'] = os.environ['OS_USER_DOMAIN_NAME']
return d
Then we have the create_server function:
"""
This function creates a server using the info we got from JSON file
"""
def create_server(server):
s = {}
print("Creating "+server['compulsory']['name']+"...")
s['name'] = server['compulsory']['name']
s['image'] = server['compulsory']['os']
s['flavor'] = server['compulsory']['flavor']
s['min_count'] = server['compulsory']['copyNumber']
s['max_count'] = server['compulsory']['copyNumber']
s['userdata'] = server['file']
s['key_name'] = server['compulsory']['keyName']
s['availability_zone'] = server['compulsory']['availabilityZone']
s['nics'] = server['compulsory']['network']
print(s['userdata'])
if(exists("instalacion_k8s_docker.sh")):
print("Exists")
s['userdata'] = server['file']
nova.servers.create(**s)
And now the main function:
"""
Main process: First we create a connection to Openstack using our credentials.
Once connected we cal get_serverdata function to get all instance objects we want to be created.
We check that it is not empty and that we are not trying to create more instances than we are allowed.
Lastly we create the instances and the program finishes.
"""
credentials = get_nova_credentials_v2()
nova = client.Client(**credentials)
instances = get_serverdata()
current_instances = len(nova.servers.list())
if not instances:
print("No instance was writen. Check instances.json file.")
exit(3)
num = 0
for i in instances:
create_server(i)
exit(0)
For the rest of the code you can access to this public repo on github.
Thanks a lot!
Problem solved
The problem was the content of the server['file'] as #Corey said. It cannot be the Path to the file where you wrote the data but the content of it or a file type object. In the case of OpenstackSDK it must be base64 encoded but it is not the case in Novaclient.
Thanks a lot to #Corey for all the help! :)

sudo as user within a python program

I am trying to sudo as another user which is generic account in shell , however userid is still same after su , any idea on how to fix it ?
import os,glob,pwd,subprocess,pexpect,getpass
print(getpass.getuser())
try:
var_command = "su user"
var_child = pexpect.spawn(var_command)
i = var_child.expect(["Password:", pexpect.EOF])
if i==0: # send password
print('Login SusccessFul' )
var_child.sendline("password")
var_child.expect(pexpect.EOF)
elif i==1:
print("Got the key or connection timeout")
pass
except Exception as e:
print("Oops Something went wrong buddy")
print(e)
print(getpass.getuser())

Update PostgreSQL user credentials using variables in Python

I'm trying to update user credentials for PostgreSQL db user using Python. I've tried referring to the following thread but that doesn't seem to solve my issue unfortunately:
How to change password of a newly created user using variable in postgresql 9.5 SP
Here's my code:
con = p.connect(database="mydB", user="abc", password="testing", host="127.0.0.1", port="5432")
cur = con.cursor()
uid = "adi"
pwd = "test6"
statement = statement = '''CREATE or REPLACE FUNCTION add_user ({}, {}) RETURNS void AS $$ EXECUTE ALTER USER ' || $1 || ' WITH PASSWORD || $2||'''.format(uid,pwd)
cur.execute( statement)
cur.execute('''COMMIT''')
I get the following error:
ProgrammingError: syntax error at or near "'adi'"
Please help or refer me to a thread with a better solution. Thanks in advance, everyone!
error image
I was able to solve this successfully.
import psycopg2 as p
con = p.connect(database="mydB", user="adi", password="xxxx", host="127.0.0.1", port="5432")
cur = con.cursor()
uid = "adi"
pwd = "test"
statement = '''ALTER USER {} WITH PASSWORD %s '''.format(uid)
cur.execute(statement, [pwd])
cur.execute('''COMMIT''')
Try to give the username and password in the actual statement and try executing.
First try removing the extra quotation before ALTER USER and execute.
If doesn't work try this:
statement = '''CREATE or REPLACE FUNCTION add_user ({}, {}) RETURNS void AS $$ EXECUTE 'ALTER USER ' || $1 || ' WITH PASSWORD || $2||'''.format(uid,pwd)
cur.execute(statement)

Problem reading sql query in python 3 with pandas

Good morning.
I'm trying to read a SQL query with pandas through a SSH tunnel. It worked fine in python 2.7, but now, with python 3.7, it seems like the process paused when executing pd.read_sql_query. My code is the following:
def conect(lista, names):
# Block of code where I set used variables below.
while not success and retries < max_retries:
try:
print('Trying to connect ({n})...'.format(n = retries + 1))
with SSHTunnelForwarder((REMOTE_SERVER, 22),
ssh_username = user_name,
ssh_pkey = ssh_pkey,
ssh_private_key_password= password,
remote_bind_address=(str_number, PUERTO),
local_bind_address=('', PUERTO)) as tunnel:
engine = sqlalchemy.create_engine("postgresql+psycopg2://{user}:{passw}#{host}:{port}/{db}".format(
user = user_name,
passw = long_pass,
host = tunnel.local_bind_host,
port = tunnel.local_bind_port,
db = db))
dic_df = {name: pd.read_sql_query(query, engine) for query, name in zip(lista, names)}
return dic_df
except Exception as e:
print('Error...')
print(e)
retries += 1
I don't know if the problem comes from the engine or from the function pd.read_sql_query itself...
Many thanks in advance!!

How to authenticate LDAP properly?

I am working on a project that must use LDAP authentication. I am using the server at ldap.forumsys.com after finding the link on Stack Overflow to practice before adding to my Flask application.
If I run the ldapsearch bash command inside of my python code I get a whole bunch of usernames (Tesla etc...) and their associated data (there are no password hashes though). I am able to extract the usernames/user-data as shown here:
username = request.form['username']
password = request.form['password']
cmd = "ldapsearch -h ldap.forumsys.com -D cn=read-only-admin,dc=example,dc=com -w" + os.environ['LDAP_PWD'] + " -b dc=example,dc=com"
ldap_query = os.popen(cmd).read()
user_str = re.sub("\n", "", ldap_query)
users = user_str.split("#")
user_data = ""
for line in users:
if username in line:
user_data = line
break
But then I realized that I LDAP is not the same as a database. I was hoping to find password hashes that I could use to authenticate a user's login information.
So then I tried the python-ldap3 module:
>>> conn = Connection(server, 'uid=tesla,dc=example,dc=com', 'password', auto_bind=True)
>>> conn.bound
True
>>> conn.entries
[]
Unfortunately I can't seem to get any data returned in the list after calling conn.entries.
I can see that the ldap3 module binded the connection. Does the ldapsearch command bind as well? If there are no password hashes, how should I authenticate the username/password entered by the user on the client side?
Thank you all very much.
If the statement...
conn.bound == True
Then the connection has been authenticated via LDAP

Resources