I'm trying to add entries with python ldap. I'm getting a naming convention error. My code is
import ldap
import ldap.modlist as modlist
LOGIN = ""
PASSWORD = ''
LDAP_URL = "ldap://127.0.0.1:389"
user='grant'
l = ldap.initialize(LDAP_URL)
l.bind(LOGIN, PASSWORD)
dn="ou=Enki Users,dc=enki,dc=local"
attrs = {}
attrs['objectclass'] = ['top','organizationalRole','simpleSecurityObject']
attrs['cn'] = 'test'
attrs['userPassword'] = 'test'
attrs['description'] = 'User object for replication using slurpd'
# Convert our dict to nice syntax for the add-function using modlist-module
ldif = modlist.addModlist(attrs)
# Do the actual synchronous add-operation to the ldapserver
l.add_s(dn,ldif)
# Its nice to the server to disconnect and free resources when done
l.unbind_s()
The error is:
ldap.NAMING_VIOLATION: {'info': "00002099: NameErr: DSID-0305109C, problem 2005 (NAMING_VIOLATION), data 0, best match of:\n\t'dc=enki,dc=local'\n", 'desc': 'Naming violation'}
The code that runs but doesn't insert the user into the correc organizational unit is the following code. However even though it runs I can't find the user in active directory. Please help me find whats wrong. I'm basically making a django webform for user management.
import ldap
import ldap.modlist as modlist
LOGIN = ""
PASSWORD = ''
LDAP_URL = "ldap://127.0.0.1:389"
user='grant'
l = ldap.initialize(LDAP_URL)
l.bind(LOGIN, PASSWORD)
dn="cn=test,ou=Enki Users,dc=enki,dc=local"
attrs = {}
attrs['objectclass'] = ['top','organizationalRole','simpleSecurityObject']
attrs['cn'] = 'test'
attrs['userPassword'] = 'test'
attrs['description'] = 'User object for replication using slurpd'
# Convert our dict to nice syntax for the add-function using modlist-module
ldif = modlist.addModlist(attrs)
# Do the actual synchronous add-operation to the ldapserver
l.add_s(dn,ldif)
# Its nice to the server to disconnect and free resources when done
l.unbind_s()
I speculate (but have not tested to prove it) that the root cause of your error is that your entry does not contain a "naming attribute" that matches the leftmost attribute in the DN of your entry, which in your case is ou=Enki Users. To add this naming attribute to the entry, you can add the following line in the part of your code that populates the attrs dict.
attrs['ou'] = 'Enki Users'
Related
I am able successfully connect using LDAP3 and retrieve my LDAP group members as below.
from ldap3 import Server, Connection, ALL, SUBTREE
from ldap3.extend.microsoft.addMembersToGroups import ad_add_members_to_groups as addMembersToGroups
>>> conn = Connection(Server('ldaps://ldap.****.com:***', get_info=ALL),check_names=False, auto_bind=False,user="ANT\*****",password="******", authentication="NTLM")
>>>
>>> conn.open()
>>> conn.search('ou=Groups,o=****.com', '(&(cn=MY-LDAP-GROUP))', attributes=['cn', 'objectclass', 'memberuid'])
it returns True and I can see members by printing
conn.entries
>>>
The above line says MY-LDAP-GROUP exists and returns TRUE while searching but throws LDAP group not found when I try to an user to the group as below
>>> addMembersToGroups(conn, ['myuser'], 'MY-LDAP-GROUP')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/****/anaconda3/lib/python3.7/site-packages/ldap3/extend/microsoft/addMembersToGroups.py", line 69, in ad_add_members_to_groups
raise LDAPInvalidDnError(group + ' not found')
ldap3.core.exceptions.LDAPInvalidDnError: MY-LDAP-GROUP not found
>>>
The above line says MY-LDAP-GROUP exists and returns TRUE
Returning True just means that the search succeeded. It doesn't mean that anything was found. Is there anything in conn.entries?
But I suspect your real problem is something different. If this is the source code for ad_add_members_to_groups, then it is expecting the distinguishedName of the group (notice the parameter name group_dn), but you're passing the cn (common name). For example, your code should be something like:
addMembersToGroups(conn, ['myuser'], 'CN=MY-LDAP-GROUP,OU=Groups,DC=example,DC=com')
If you don't know the DN, then ask for the distinguishedName attribute from the search.
A word of warning: that code for ad_add_members_to_groups retrieves all the current members before adding the new member. You might run into performance problems if you're working with groups that have large membership because of that (e.g. if the group has 1000 members, it will load all 1000 before adding anyone). You don't actually need to do that (you can add a new member without looking at the current membership). I think what they're trying to avoid is the error you get when you try to add someone who is already in the group. But I think there are better ways to handle that. It might not matter to you if you're only working with small groups.
After so many trial and errors, I got frustrated and used the older python-ldap library to add existing users. Now my code is a mixture of ldap3 and ldap.
I know this is not what the OP has desired. But this may help someone.
Here the user Dinesh Kumar is already part of a group group1. I am trying to add him
to another group group2 which is successful and does not disturb the existing group
import ldap
import ldap.modlist as modlist
def add_existing_user_to_group(user_name, user_id, group_id):
"""
:return:
"""
# ldap expects a byte string.
converted_user_name = bytes(user_name, 'utf-8')
converted_user_id = bytes(user_id, 'utf-8')
converted_group_id = bytes(group_id, 'utf-8')
# Add all the attributes for the new dn
ldap_attr = {}
ldap_attr['uid'] = converted_user_name
ldap_attr['cn'] = converted_user_name
ldap_attr['uidNumber'] = converted_user_id
ldap_attr['gidNumber'] = converted_group_id
ldap_attr['objectClass'] = [b'top', b'posixAccount', b'inetOrgPerson']
ldap_attr['sn'] = b'Kumar'
ldap_attr['homeDirectory'] = b'/home/users/dkumar'
# Establish connection to server using ldap
conn = ldap.initialize(server_uri, bytes_mode=False)
bind_resp = conn.simple_bind_s("cn=admin,dc=testldap,dc=com", "password")
dn_new = "cn={},cn={},ou=MyOU,dc=testldap,dc=com".format('Dinesh Kumar','group2')
ldif = modlist.addModlist(ldap_attr)
try:
response = conn.add_s(dn_new, ldif)
except ldap.error as e:
response = e
print(" The response is ", response)
conn.unbind()
return response
Learning python (was chosen for its ldap module) for a new script that has been tossed my way. I'm getting a sytntax error when I try using a ldif. I was getting Syntax errors on the attrs I was trying to assign until I moved it further up the script to near the search fields. I'm not exactly sure why I am getting the syntax error:
File "UserGroupModify.py", line 66
attrs = {}
^
SyntaxError: invalid syntax
~/Scripts/Termination-Script$ python2 UserGroupModify.py
File "UserGroupModify.py", line 69
ldif = modlist.addModlist(attrs)
^
SyntaxError: invalid syntax
The code currently looks like the following (including previous things I had tried all with syntax errors of their own when I tried to use them). Getting it to log in and search for the user was easy enough, but modifying the user is where I am having a hard time. The current code is uncommented and is from an example I found online.
#!/usr/bin/env python2
import ldap
import getpass
import ldap.modlist as modlist
## first you must open a connection to the server
try:
#Ignore self signed certs
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
username = raw_input("LDAP Login: ")
passwd = getpass.getpass()
userlook = raw_input("User to lookup: ")
l = ldap.initialize("ldaps://ldap.example.com:636/")
# Bind/authenticate with a user with apropriate rights to add objects
l.simple_bind_s("uid="+username+",ou=people,dc=example,dc=com", ""+passwd+"")
except ldap.LDAPError, e:
print(e)
# The dn of our existing entry/object
dn = "ou=People,dc=example,dc=com"
searchScope = ldap.SCOPE_SUBTREE
searchAttribute = ["uid"]
#retrieveAttributes = ["ou=Group"]
retrieveAttributes = ["ou"]
#searchFilter = "uid=*"
searchFilter = "(uid="+userlook+")"
#mod_attrs = [(ldap.MOD_REPLACE, 'ou', 'former-people' )]
attrs = {}
attrs['member'] = ['uid="+userlook+",ou=former-people,dc=example,dc=com']
try:
#ldap_result_id = l.search(dn, searchScope, searchFilter, retrieveAttributes)
ldap_result_id = l.search(dn, searchScope, searchFilter, retrieveAttributes)
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
## here you don't have to append to a list
## you could do whatever you want with the individual entry
## The appending to list is just for illustration.
if result_type == ldap.RES_SEARCH_ENTRY:
print(result_data)
# Some place-holders for old and new values
#old={'Group':'l.result(ldap_result_id, 0)'}
#new={'Group':'uid="+userlook+",ou=former-people,dc=example,dc=com'}
#newsetting = {'description':'I could easily forgive his pride, if he had not mortified mine.'}
#print(old)
#print(new)
# Convert place-holders for modify-operation using modlist-module
#ldif = modlist.modifyModlist(old,new)
# Do the actual modification
#l.modify_s(dn,ldif)
#l.modify_s('uid="+userlook+,ou=People,dc=example,dc=com', mod_attrs)
#l.modify_s('uid="+userlook+",ou=People', mod_attrs)
#moved up due to SyntaxError
#attrs = {}
#attrs['member'] = ['uid="+userlook+",ou=former-people,dc=example,dc=com']
# Convert our dict to nice syntax for the add-function using modlist-module
ldif = modlist.addModlist(attrs)
# Do the actual synchronous add-operation to the ldapserver
l.add_s(dn,ldif)
# Its nice to the server to disconnect and free resources when done
l.unbind_s()
except ldap.LDAPError, e:
print(e)
Any direction pointing on what's causing the error would be greatly appreciated. Thanks
It's a syntax error to have try without except. Because there's a whole lot of unindented code before the except, Python doesn't see it as part of the try. Make sure everything between try and except is indented.
You haven't ended your try block by the time you reach this line
ldif = modlist.addModlist(attrs)
since the accompanying except is below. However, you reduced the indentation level and this is causing the syntax error since things in the same block should have the same indentation.
If you delete an user or group in windows AD, it will in "DElETE objects".
I want to use python ldap lib to get them.
Code:
<code>
import ldap
uri = "ldap://10.64.74.17"
user = "XXXXXXXXXX"
password = "XXXXXXXXXXXX"
ldap.set_option(ldap.OPT_REFERRALS, 0)
ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, 5)
ldap.protocol_version = 3
ldapClient = ldap.initialize(uri)
ldapClient.simple_bind_s(user, password)
filter = "(&(objectclass=person)(isDeleted=true)(!(objectclass=computer)))"
results = ldapClient.search_s("DC=xx,DC=com", ldap.SCOPE_SUBTREE,filter)
for result in results:
print result
ldapClient.unbind_s()
</code>
It can't show deleted objects.
What's wrong with this code?
You need to add an ldap control to your search : create the request control for the particular operation, and then pass a collection of controls to your search request as an optional parameter.
In your case, this OID for AD is 1.2.840.113556.1.4.417.
LDAP_SERVER_SHOW_DELETED_OID : 1.2.840.113556.1.4.417
Used with an LDAP operation to specify that tombstones and deleted-objects are visible to the operation.
tombstone_control = ('1.2.840.113556.1.4.417',criticality=1)
results = ldapClient.search_s("DC=xx,DC=com", ldap.SCOPE_SUBTREE,filter, [tombstone_control])
You can also scope your search base to CN=Deleted Objects, DC=xx,DC=com as this is where all deleted objects end up. You should make sure your deleted objects are there first. You can use ldp.exe to check.
I have app written in TG 2.2.2 with default authentication. Last days, I have problem with logging in and out. In safari, two authtkt cookies are created, one as "beta.domain.com", other ".beta.domain.com". After calling /logout_handler, cookie for domain "beta.domain.com" is deleted only but for wild domain remains. So after reloading page, user is still logged in. Problem is occuring on localhost as well on production.
Interesting is that other application on same lib version works normally, as well in other browsers, no virtualenv used.
I really don't know where the problem is so I will include any config file when requested. At beggining, app_config is included.
app_cfg.py
# -*- coding: utf-8 -*-
from tg.configuration import AppConfig
import cafeteria
from cafeteria import model
from cafeteria.lib import app_globals, helpers
base_config = AppConfig()
base_config.renderers = []
base_config.prefer_toscawidgets2 = True
base_config.package = cafeteria
base_config.renderers.append('json')
base_config.renderers.append('mako')
base_config.default_renderer = 'mako'
base_config.use_sqlalchemy = True
base_config.model = cafeteria.model
base_config.DBSession = cafeteria.model.DBSession
# Configure the authentication backend
# YOU MUST CHANGE THIS VALUE IN PRODUCTION TO SECURE YOUR APP
base_config.sa_auth.cookie_secret = "SOMESECRET"
base_config.auth_backend = 'sqlalchemy'
from tg.configuration.auth import TGAuthMetadata
# This tells to TurboGears how to retrieve the data for your user
class ApplicationAuthMetadata(TGAuthMetadata):
def __init__(self, sa_auth):
self.sa_auth = sa_auth
def get_user(self, identity, userid):
return self.sa_auth.dbsession.query(self.sa_auth.user_class).filter_by(user_name = userid).first()
def get_groups(self, identity, userid):
return (identity['user'].group.name,) if identity['user'].group_id else []
def get_permissions(self, identity, userid):
return [p.name for p in identity['user'].group.permissions] if identity['user'].group_id else []
base_config.sa_auth.dbsession = model.DBSession
base_config.sa_auth.user_class = model.User
# base_config.sa_auth.group_class = model.Group
# base_config.sa_auth.permission_class = model.Permission
base_config.sa_auth.translations.group_name = 'name'
base_config.sa_auth.translations.permission_name = 'name'
base_config.sa_auth.authmetadata = ApplicationAuthMetadata(base_config.sa_auth)
# base_config.sa_auth.authenticators = [('myauth', SomeAuthenticator()]
# base_config.sa_auth.mdproviders = [('myprovider', SomeMDProvider()]
base_config.sa_auth.form_plugin = None
base_config.sa_auth.charset = 'utf-8'
base_config.sa_auth.post_login_url = '/post_login'
base_config.sa_auth.post_logout_url = '/post_logout'
Remove all cookies of your domain. when you change your domain old cookies still remains and could cause this issue.
Why do you use both beta.domain.com and .beta.domain.com? if you don't need to use this cookie in subdomains remove the 2nd one else just use the .beta.domain.com.
If this doesn't help please attach the request and response header.
I am trying to access the library class of pylast, but must be doing something wrong. I can get most other features to work. The following is a code example which just takes the standard working example and adds what I believe to be the correct way of adding an album to my last.fm library:
import pylast
# You have to have your own unique two values for API_KEY and API_SECRET
# Obtain yours from http://www.last.fm/api/account for Last.fm
API_KEY = "80a1c765efb52869575821c03d93a30e" # this is a sample key
API_SECRET = "2ba567f5b0d74c6cc6a8d07ef2cbc2d"
# In order to perform a write operation you need to authenticate yourself
username = "astroid0"
password_hash = pylast.md5("xxx")
network = pylast.LastFMNetwork(api_key = API_KEY, api_secret =
API_SECRET, username = username, password_hash = password_hash)
# now you can use that object every where
artist = network.get_artist("System of a Down")
artist.shout("<3")
track = network.get_track("Iron Maiden", "The Nomad")
track.love()
track.add_tags(("awesome", "favorite"))
## This is the area causing trouble
library1 = pylast.Library(user = "astroid0", network = "LastFM")
album1 = network.get_album("The Rolling Stones", "Sticky Fingers")
library1.add_album(album1)
ss the library class of pylast, but must be doing something wrong. I can get most other features to work. The following is a code example which just takes the standard working example and adds what I believe to be the correct way of adding an album to my last.fm library:
library1 = pylast.Library(user = "astroid0", network = "LastFM")
album1 = network.get_album("The Rolling Stones", "Sticky Fingers")
library1.add_album(album1)
I am new to python, so I am sorry if this is obvious, I have just been stuck for days now, and decided to ask.
It's a bug in pylast.
Line 1957 (from trunk) should be:
params["artist"] = album.get_artist().get_name()
instead of:
params["artist"] = album.get_artist.get_name()
You can report the issue to the author here.
The answer by miles82 shows the bug and it's been reported to pylast.
Unfortunately there's been no updates in a few years so I've fixed this in my fork of pylast.