Python-LDAP empty result in search_s - python

I've looked at a few examples and responses, however, I'm stumped. It worked a few minutes ago and now it's just not returning a result. No code change happened.
The test code I have pulls the members from a LDAP role group and prints the member DN's. It worked a few minutes ago, and now it keeps returning empty results. I also printed the ldap_result and it's empty too.
def ldapgroupmembers():
try:
username = str(raw_input('Email: '))
password = str(getpass.getpass())
l = ldap.initialize("ldap://company.co.za")
l.simple_bind_s(username, password)
myfilter = "(&DN=GROUP)(cn=My-RG-Group))"
ldap_result = l.search_s("OU=MyGroups,OU=Role Groups,OU=Groups,OU=CompanyOU,DC=company,DC=co,DC=za", ldap.SCOPE_SUBTREE, myfilter, ['member'])
for dn in ldap_result[0][1]['member']:
print dn
except ldap.INVALID_CREDENTIALS:
print "Invalid credentials"
return "Invalid credentials"
except ldap.SERVER_DOWN:
print "Server down"
return "Server down"
except ldap.LDAPError, e:
if type(e.message) == dict and e.message.has_key('desc'):
return "Other LDAP error: " + e.message['desc']
else:
print "Other LDAP error: "
return "Other LDAP error: " + e
finally:
l.unbind_s()
return "Succesfully authenticated"
Your help would be greatly appreciated.

I found the problem. Turns out I never closed the myfilter bracket and I removed the first bracket set where I filter on dn=GROUP

Related

LDAP: querying for all users in entire domain using sAMAccountName

I have modified this code python-paged-ldap-snippet.py from https://gist.github.com/mattfahrner/c228ead9c516fc322d3a
My problem is that when I change my SEARCHFILTER from '(&(objectCategory=person)(objectClass=user))' to '(&(objectCategory=person)(objectClass=user)(memberOf=CN=Users0,OU=Groups,DC=ad,DC=company,DC=com))'
it runs just fine.
If it is on SEARCHFILTER='(&(objectCategory=person)(objectClass=user))', I notice that the code is not entering the writeToFile function.
The objective of the code is to dump all the user information and parse the info into a file.
I tried running LDAPSEARCH against '(&(objectCategory=person)(objectClass=user))' and I manage to get the output .
Not sure what is wrong. Suggestions are greatly appreciated.
Thank you.
#!/usr/bin/python
import sys
import ldap
import os
LDAPSERVER='ldap://xxx.xxx.xxx.xxx:389'
BASEDN='dc=ad,dc=company,dc=com'
LDAPUSER = "CN=LDAPuser,OU=XXX,OU=Users,DC=ad,DC=company,DC=com"
LDAPPASSWORD = 'LDAPpassword'
PAGESIZE = 20000
ATTRLIST = ['sAMAccountName','uid']
SEARCHFILTER='(&(objectCategory=person)(objectClass=user))'
#SEARCHFILTER='(&(objectCategory=person)(objectClass=user)(memberOf=CN=Users0,OU=Groups,DC=ad,DC=company,DC=com))'
data = []
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
ldap.set_option(ldap.OPT_REFERRALS, 0)
l = ldap.initialize(LDAPSERVER)
l.protocol_version = 3 # Paged results only apply to LDAP v3
try:
l.simple_bind_s(LDAPUSER, LDAPPASSWORD)
print ' Login Done, Searching data'
except ldap.LDAPError as e:
exit('LDAP bind failed: %s' % e)
lc = ldap.controls.SimplePagedResultsControl(True,size=PAGESIZE,cookie='')
def writeToFile(data):
print ' Writing data to file'
#code to print all output into CVS file
while True:
try:
msgid = l.search_ext(BASEDN, ldap.SCOPE_SUBTREE, SEARCHFILTER, ATTRLIST, serverctrls=[lc])
except ldap.LDAPError as e:
sys.exit('LDAP search failed: %s' % e)
try:
rtype, rdata, rmsgid, serverctrls = l.result3(msgid)
except ldap.LDAPError as e:
sys.exit('Could not pull LDAP results: %s' % e)
for dn, attrs in rdata:
data.append(attrs)
pctrls = [
c for c in serverctrls if c.controlType == ldap.controls.SimplePagedResultsControl.controlType ]
if not pctrls:
print >> sys.stderr, 'Warning: Server ignores RFC 2696 control.'
break
cookie = pctrls[0].cookie
if not cookie:
writeToFile(data)
print 'Task Complete'
break
lc.controlValue = (PAGESIZE, cookie)
PAGESIZE = 20000
Lower your page size to a value <= 1000, since that's the max AD will give you at a time anyway. It's possible that it's waiting for 20000 records before requesting the next page and never getting it.

Flask SQLAlchemy: filter_by() takes 1 positional argument but 2 were given

I have the following lines in my python api which deletes a function created by user from postgres db upon request.
#func_app.route("/delete", methods=["POST"])
def delete_func():
try:
JSON = request.get_json()
user_func = function_table.query.filter_by(
created_by=token_payload["email"], functionid=JSON["funcId"]
).all()
functionid=JSON["funcId"]
func_detail = function_table.query.filter_by(functionid).first()
user = users_table.query.filter_by(email=token_payload["username"]).first()
if len(user_func) == 0:
log_metric(g.request_id + " " + "No functions found")
return make_response(
jsonify("User does not have any functions. Please try again later."),
204,
)
else:
function_table.query.filter_by(functionid).delete()
db.session.commit()
except Exception as err:
db.session.rollback()
log_metric(g.request_id + " " + str(err))
return make_response(
jsonify(
"Unable to process your request at the moment. Please try again later."
),
400,
)
finally:
db.session.close()
I have used filter_by similarly before but there I didn't find any issue. Can anyone help me figure out what went wrong?
Thanks!
You need to define the column name with the value in filter_by, it take **kwargs arguments not *args type of input.
you need to change
func_detail = function_table.query.filter_by(functionid).first()
to
func_detail = function_table.query.filter_by(id = functionid).first()
considering id is column name.
For more information, see the sqlalchemy documentation.

Python Flask filter results in template depending on selected checkbox in form (wtf)

I have a database with a few rooms at the moment, a user can search on the indexpage for a room in a city by typing in a cityname. He will be redirected to the resultpage where he finds all rooms in this city.
In my database each rooms has a few boolean properties, f.e. "has_wlan" or "has_tv"
On this resultpage there should be a filter function, where you see all these properties and f.e. if you want to see all rooms which have tv, you check the checkbox has_tv and the results shall be reloaded where only rooms are shown with boolean value True for has_tv.
For this I crreated a new form (WTF-Forms) and I included it in my method which loads all results:
#app.route('/<findroomcity>', methods=["GET", "POST"])
def find_room(findroomcity):
form = FilterZimmerForm()
if form.validate_on_submit():
all_rooms_in_city = Zimmer.query.filter(Zimmer.haustiere_erlaubt.is_(False)).all()
else:
all_rooms_in_city = Zimmer.query.order_by(desc("stadt")).all()
try:
location = geolocator.geocode(findroomcity)
#location2 = geolocator.geocode("Dortmund" + " Am Hombruchsfeld")
mymap = Map(
identifier="view-side",
lat=location.latitude,
lng=location.longitude,
markers=[(location.latitude, location.longitude)],
zoom = 12
)
sleep(1)
markerlist = []
for room in all_rooms_in_city:
if room.stadt == findroomcity.lower():
try:
location2 = geolocator.geocode(room.stadt + " " + room.strasse + " " + room.hausnr)
markerlist.append((location2.latitude, location2.longitude))
except GeocoderTimedOut as e:
print "in der schleife timeout", e
except AttributeError as e:
print "in der schleife attributeerror", e
mymap.markers['//maps.google.com/mapfiles/ms/icons/red-dot.png'] = markerlist
except AttributeError as e:
flash("Ort nicht gefunden")
print e
return redirect(url_for('index'))
except GeocoderTimedOut as e:
print e
sleep(1)
return render_template('zimmer_gefunden.html', mymap=mymap, all_rooms_in_city=all_rooms_in_city, findroomcity=findroomcity, form=form)
The result page also loads a google map with markers, but this works well. The question is how do I reload the results where only rooms are shown with checked items from the checkboxlist?
So this is the relevant piece of code:
if form.validate_on_submit():
all_rooms_in_city = Zimmer.query.filter(Zimmer.haustiere_erlaubt.is_(False)).all()
else:
all_rooms_in_city = Zimmer.query.order_by(desc("stadt")).all()
At this moment I just try to filter for all rooms where "haustiere_erlaubt" is false this is just for testing but not even this works. The plan is to replace the False with form.haustiere_erlaubt.datafor all other boolean values aswell.

python3 - imaplib: randomly(?) can' fetch received email

def get_email_body(self, email):
user = self.email_usr
password = self.app_email_pwd
connection = imaplib.IMAP4_SSL('imap.gmail.com')
connection.login(user, password)
connection.list()
connection.select('"INBOX"')
time.sleep(5)
result_search, data_search = connection.search(None, 'TO', email, 'SUBJECT', '"some subject"')
required_email = data_search[0]
result_fetch, data_fetch = connection.fetch(required_email, '(RFC822)')
email_body_string = data_fetch[0][1].decode('utf-8')
confirmation_link = self.parse_confirmation_link(email_body_string)
return confirmation_link
This function works like 2 times of 4 runs. Usually it fails with:
self = <imaplib.IMAP4_SSL object at 0x7fa853614b00>, name = 'FETCH'
tag = b'JAAL5'
def _command_complete(self, name, tag):
# BYE is expected after LOGOUT
if name != 'LOGOUT':
self._check_bye()
try:
typ, data = self._get_tagged_response(tag)
except self.abort as val:
raise self.abort('command: %s => %s' % (name, val))
except self.error as val:
raise self.error('command: %s => %s' % (name, val))
if name != 'LOGOUT':
self._check_bye()
if typ == 'BAD':
raise self.error('%s command error: %s %s' % (name, typ, data))
E imaplib.error: FETCH command error: BAD [b'Could not parse command']
/usr/lib/python3.4/imaplib.py:964: error
My suggestion was that sometimes email isn't delivered at the moment of .search that's why I added time.sleep (I'm searching for the email immediately after it was sent).
Else I did try search while result_fetch is not 'OK' but is also didn't help.
Any other suggestions?
oooops, my suggestion was correct, but time.sleep was in the incorrect place. Moved sleep before connection and all go smooth

Verify if a topic exists based on topic name

I'm trying to verify if a topic exists based on topic name.
Do you know if this is possible?
For example I want to verify if topic with name "test" already exist.
Below is what I'm trying but doesn't work because topicsList contains topicArns and not topicNames...
topics = sns.get_all_topics()
topicsList = topics['ListTopicsResponse']['ListTopicsResult'['Topics']
if "test" in topicsList:
print("true")
This code will work if you have more than 100 topics
def get_topic(token=None):
topics = self.sns.get_all_topics(token)
next_token = topics['ListTopicsResponse']['ListTopicsResult']['NextToken']
topic_list = topics['ListTopicsResponse']['ListTopicsResult']['Topics']
for topic in topic_list:
if "your_topic_name" in topic['TopicArn'].split(':')[5]:
return topic['TopicArn']
else:
if next_token:
get_topic(next_token)
else:
return None
What if you try to catch An error occurred (NotFound) when calling the GetTopicAttributes operation: Topic does not exist exception?
from botocore.exceptions import ClientError
topic_arn = "arn:aws:sns:us-east-1:999999999:neverFound"
try:
response = client.get_topic_attributes(
TopicArn=topic_arn
)
print "Exists"
except ClientError as e:
# Validate if is this:
# An error occurred (NotFound) when calling the GetTopicAttributes operation: Topic does not exist
print "Does not exists"
This is kind of a hack but it should work:
topics = sns.get_all_topics()
topic_list = topics['ListTopicsResponse']['ListTopicsResult']['Topics']
topic_names = [t['TopicArn'].split(':')[5] for t in topic_list]
if 'test' in topic_names:
print(True)

Categories