Python LDAP3 Search in multiple search_base at once - python

I have a code like this:
from ldap3 import Server, Connection
uri = 'ldaps://ca1.ad.xxx.com:123'
bind_user = 'CN=svc_bind_user,OU=Service Accounts,DC=subdomain1,DC=ad,DC=xxx,DC=com'
bind_password = 'svc_bind_p4$$'
server = Server(uri)
conn = Connection(server, bind_user, bind_password)
conn.bind()
user_filter = 'objectClass=*'
user_name_attr = 'sAMAccountName'
search_scope = 'SUBTREE'
I can successfully search for user1 user1#subdomain1.ad.xxx.com like this
username = 'user1'
search_base= 'DC=subdomain1,DC=ad,DC=xxx,DC=com'
search_filter = "(&({0})({1}={2}))".format(
user_filter,
user_name_attr,
username
)
res = conn.search(search_base,
search_filter,
search_scope)
as well as user2 user2#subdomain2.ad.xxx.com like this
username = 'user2'
search_base= 'DC=subdomain2,DC=ad,DC=xxx,DC=com'
search_filter = "(&({0})({1}={2}))".format(
user_filter,
user_name_attr,
username
)
res = conn.search(search_base,
search_filter,
search_scope)
As you can see codes above are tailored for each user to look into different search_base : subdomain1 and subdomain2 accordingly
I tired to search for both user1 and user2 in a code like this with a higher level search_base= 'DC=ad,DC=xxx,DC=com' :
username = 'user1'
search_base= 'DC=ad,DC=xxx,DC=com'
search_filter = "(&({0})({1}={2}))".format(
user_filter,
user_name_attr,
username
)
res = conn.search(search_base,
search_filter,
search_scope)
but the code above doesn't find the user, only returns a list of subdomains
So the question is, if I am not doing anything wrong here, is there a way to search within multiple domains, by having a perhaps search_base with special syntax that combines multiple subdomains?
I don't want to do multiple searches and also as I mentioned the SUBTREE/higher level serach_base does not seem to work for me either
Thanks

Related

Python Ldap module limits search for 1000 users, how to use simple search?

I am using Ldap3 module in python to query AD, however i get result if the ad account is in first 1000 searches, i have more than 25000 + user ids in AD, how i can change my code here into simple page search, Please help me.
''''
import sys
from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, AUTO_BIND_NO_TLS, SUBTREE
from ldap3.core.exceptions import LDAPCursorError
server = Server('bluepedia.com',get_info=ALL)
conn = Connection(server, user='bluepedia\\administrator', password='Vihaan#2016', authentication=NTLM)
conn.bind()
fusers = ['vihaan','phani','rammohan','raja','bindu','MA977956', 'MA625841','gopal','govind','MA177397','MA259156']
status = ''
usermail= ''
format_string = '{:25} {:21} {}'
print(format_string.format('User ID', 'Account Status', 'E-mail Address'))
conn.search('dc=bluepedia,dc=com', '(objectclass=person)',attributes=['sAMAccountName', 'mail'])
for x in fusers:
for e in conn.entries:
usermail = e.mail
if x in e.sAMAccountName:
# status = 'active' +"\t\t\t\t"+ str(usermail)
status = 'active'
break
else:
status = "Not Active"
usermail = ''
print(format_string.format(str(x),str(status),str(usermail)))
''''
My required result is i want to search user id from a list using Ldap3 module, and i have 10000 users in list.

Unable to check for already existing usernames google app engine

Here is my code to check for already existing usernames :
def post(self):
have_error = False
username = self.request.get('username')
password = self.request.get('password')
verify = self.request.get('verify')
email = self.request.get('email')
params = dict(username= username,
email = email)
usernames = db.GqlQuery(' select * from Users where username = :1 ', username)
if not valid_username(username):
params['username_error'] = "Invalid username"
have_error = True
if usernames :
params['username_error'] = 'Username already exists'
have_error = True
With this code my form displays Username already exists for every username.
When the params['username_error'] = 'Username already exists' is changed to
params['username_error'] = usernames ,
the message displayed in the username_error field is :
<google.appengine.ext.db.GqlQuery object at 0x10a4e030>
I'd change your check to:
query = db.GqlQuery(' select * from Users where username = :1 ', username)
usernames = query.count(limit=2)
Now, the if usernames: guard will have the effect you desire.
The reason is simple: in your code, you build a query object, which you call usernames, but you never actually run that query -- you check the object for truthiness, which happens to hold (as does for almost all Python objects except empty containers and strings, None, zero numbers) but signifies nothing.
Here, I run the query in the simplest way -- just count how many items it would return (just-counting is a bit faster than actually fetching them:-) and with a very low limit (since we only care about counts of 0, which is correct, and 1, which means a duplicate).
Now usernames is a number counting how many other times that user name appears in the datastore (with 1 standing for "once or more":-) and the rest of your logic becomes accurate.

Logging into google plus with google account in python

I want to be able to use urllib2.urlopen() or requests.get() with http://plus.google.com/* url's.
Using python, how would I go about doing that? I need to login first, but how?
The following code returns something along the lines of:
"Your browser's cookie functionality is turned off. Please turn it on."
Well, the cookie itself is created and, and I tested robots.txt, there are no diallows... I also tried switching user agents, no luck.
cookie_filename = "google.cookie"
email = raw_input("Enter your Google username: ")
password = getpass.getpass("Enter your password: ")
self.cj = cookielib.MozillaCookieJar(cookie_filename)
self.cj.load()
self.opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel = 0),
urllib2.HTTPSHandler(debuglevel = 0),
urllib2.HTTPCookieProcessor(self.cj)
)
urllib2.install_opener(self.opener)
login_page_url = 'https://www.google.com/accounts/ServiceLogin?passive=true&service=grandcentral'
authenticate_url = 'https://www.google.com/accounts/ServiceLoginAuth?service=grandcentral'
gv_home_page_url = 'https://www.google.com/voice/#inbox'
# Load sign in page
login_page_contents = self.opener.open(login_page_url).read()
# Find GALX value
galx_match_obj = re.search(r'name="GALX"\s*value="([^"]+)"', login_page_contents, re.IGNORECASE)
galx_value = galx_match_obj.group(1) if galx_match_obj.group(1) is not None else ''
# Set up login credentials
login_params = urllib.urlencode( {
'Email' : email,
'Passwd' : password,
'continue' : 'https://www.google.com/voice/account/signin',
'GALX': galx_value
})
# Login
resp = self.opener.open(authenticate_url, login_params).readlines()
print resp
self.opener.open(authenticate_url, login_params).readlines()
self.cj.save()
# Open GV home page
gv_home_page_contents = self.opener.open(gv_home_page_url).read()
print gv_home_page_contents

what is the url to get the number of friends a user has by user ID by graph api or FQL

Hi this is my piece of code to get the number of friends a user has by python . It returns nothing. Can anyone tell me which access privilege should i grant or anything wrong what i have done so far?
friend_count = 0
q = urllib.urlencode({'SELECT friend_count FROM user WHERE uid': 784877761})
url = 'https://api.facebook.com/method/fql.query?query=' + q
request = urllib2.Request(url)
data = urllib2.urlopen(request)
doc = parse(data)
friend_count_node = doc.getElementsByTagName("friend_count")
test = friend_count_node[0].firstChild.nodeValue
logging.info(test)
Try replacing your code with this:
q = urllib.urlencode({'SELECT friend_count FROM user WHERE uid = 784877761'})
url = 'https://graph.facebook.com/fql?q=' + q
You should not need an access token to get the friend_count.

Last.FM cannot return more than 500 records when using pylast program

I use pylast to get information from Last.fm API.
When I use the code below:
#!/usr/bin/env python
import pylast
API_KEY = "############################"
API_SECRET = "##############################"
###### In order to perform a write operation you need to authenticate yourself
username = "########"
password_hash = pylast.md5("###########")
network = pylast.LastFMNetwork(api_key = API_KEY, api_secret = API_SECRET, username = username, password_hash = password_hash)
## _________INIT__________
COUNTRY = "United Kingdom"
#---------------------- Get Geo Country --------------------
geo_country = network.get_country(COUNTRY)
print "The country we are digging is", geo_country
#---------------------- Get artist --------------------
top_artists_of_country = geo_country.get_top_artists(limit = 1000)
top_artists_of_country_file = open('test_artist_number.txt', 'w+')
print >> top_artists_of_country_file, top_artists_of_country
top_artists_of_country_file.close()
I found that I cannot get, for instance, 1000 records when I call
geo_country.get_top_artists(limit = 1000)
I just want to know, is this limitation caused by Last.fm's API setings or by pylast?
Any help would be great:)
It is a limitation of Last.fm.

Categories

Resources