def _ldap_connection(self):
"""
Context manager for ldap connections
"""
if self.no_verify:
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,
ldap.OPT_X_TLS_NEVER)
ldap_cxn = ldap.initialize('{0}'.format(self.uri))
ldap_cxn.protocol_version = 3
ldap_cxn.set_option(ldap.OPT_REFERRALS, 0)
if self.tls and not self.uri.startswith('ldaps'):
ldap_cxn.start_tls_s()
yield ldap_cxn
python类initialize()的实例源码
def get_custom_ldap_group_members(ldap_settings, group_name):
logger = utils.get_logger()
ldap_server = ldap_settings["server"]
ldap_base = ldap_settings["base"]
get_uid = lambda x: x[1]["uid"][0]
members = []
try:
conn = LDAP.initialize(ldap_server)
g_ldap_filter = ldap_settings[group_name]
logger.debug("Searching members for %s: %s" % (group_name,
g_ldap_filter))
items = conn.search_s(ldap_base, LDAP.SCOPE_SUBTREE,
attrlist=['uid'],
filterstr=g_ldap_filter)
members = map(get_uid, items)
except Exception, e:
logger.error("Error getting custom group %s from LDAP: %s" % (group_name, e))
return members
def get_ldap_group_members(ldap_settings, group_name):
# base:dc=example,dc=com
# filter:(&(objectClass=posixGroup)(cn={group_name}))
logger = utils.get_logger()
ldap_server = ldap_settings["server"]
ldap_base = ldap_settings["groups_base"]
ldap_filter = "(&%s(%s={group_name}))" % (ldap_settings["groups_filter"], ldap_settings["groups_id"])
get_uid = lambda x: x.split(",")[0].split("=")[1]
try:
ad_filter = ldap_filter.replace('{group_name}', group_name)
conn = LDAP.initialize(ldap_server)
logger.debug("Searching members for %s: %s - %s - %s" % (group_name,
ldap_server,
ldap_base,
ad_filter))
res = conn.search_s(ldap_base, LDAP.SCOPE_SUBTREE, ad_filter)
except Exception, e:
logger.error("Error getting group from LDAP: %s" % e)
return map(get_uid, res[0][1]['uniqueMember'])
def get_ldap_groups(ldap_settings):
'''Returns the a list of found LDAP groups filtered with the groups list in
the settings
'''
# filter:(objectClass=posixGroup)
# base:ou=Group,dc=example,dc=com
logger = utils.get_logger()
ldap_server = ldap_settings["server"]
ldap_base = ldap_settings["groups_base"]
ldap_filter = ldap_settings["groups_filter"]
ldap_groups = ldap_settings["groups"]
get_uid = lambda x: x[1]["cn"][0]
try:
conn = LDAP.initialize(ldap_server)
logger.debug("Searching groups: %s - %s - %s" % (ldap_server,
ldap_base,
ldap_filter))
res = conn.search_s(ldap_base, LDAP.SCOPE_SUBTREE, ldap_filter)
return filter((lambda x: x in ldap_groups), map(get_uid, res))
except Exception, e:
logger.error("Error getting groups from LDAP: %s" % e)
def authentication_ldap(self,username,password,returnObject=True):
cfg=r.table('config').get(1).run(db.conn)['auth']
try:
conn = ldap.initialize(cfg['ldap']['ldap_server'])
id_conn = conn.search(cfg['ldap']['bind_dn'],ldap.SCOPE_SUBTREE,"uid=%s" % username)
tmp,info=conn.result(id_conn, 0)
user_dn=info[0][0]
if conn.simple_bind_s(who=user_dn,cred=password):
'''
config/ldapauth.py has the function you can change to adapt to your ldap
'''
au=myLdapAuth()
newUser=au.newUser(username,info[0])
return User(newUser) if returnObject else newUser
else:
return False
except Exception as e:
log.error("LDAP ERROR:",e)
return False
def ldapAuthenticate(username, password):
if settings.AUTH_LDAP_SERVER_URI is None:
return False
if settings.AUTH_LDAP_USER_DN_TEMPLATE is None:
return False
try:
connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
connection.protocol_version = ldap.VERSION3
user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username}
connection.simple_bind_s(user_dn, password)
return True
except ldap.INVALID_CREDENTIALS:
return False
except ldap.SERVER_DOWN:
return False
def ldapAuthenticate(username, password):
if settings.AUTH_LDAP_SERVER_URI is None:
return False
if settings.AUTH_LDAP_USER_DN_TEMPLATE is None:
return False
try:
connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
connection.protocol_version = ldap.VERSION3
user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username}
connection.simple_bind_s(user_dn, password)
return True
except ldap.INVALID_CREDENTIALS:
return False
except ldap.SERVER_DOWN:
return False
def ldapAuthenticate(username, password):
if settings.AUTH_LDAP_SERVER_URI is None:
return False
if settings.AUTH_LDAP_USER_DN_TEMPLATE is None:
return False
try:
connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
connection.protocol_version = ldap.VERSION3
user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username}
connection.simple_bind_s(user_dn, password)
return True
except ldap.INVALID_CREDENTIALS:
return False
except ldap.SERVER_DOWN:
# TODO: Return error instead of none
return False
def ldapAuthenticate(username, password):
if settings.AUTH_LDAP_SERVER_URI is None:
return False
if settings.AUTH_LDAP_USER_DN_TEMPLATE is None:
return False
try:
connection = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
connection.protocol_version = ldap.VERSION3
user_dn = settings.AUTH_LDAP_USER_DN_TEMPLATE % {"user": username}
connection.simple_bind_s(user_dn, password)
return True
except ldap.INVALID_CREDENTIALS:
return False
except ldap.SERVER_DOWN:
return False
def updateuser(self, uid, modattrs):
l = ldap.initialize(self.config["server"])
l.simple_bind(self.config["admin"], self.config["password"])
dn = "uid=%s,%s" % (uid, self.config["memberdn"])
ldap_filter = "uid="+uid
result_id = l.search(self.config["memberdn"], ldap.SCOPE_SUBTREE, ldap_filter, None)
if result_id:
type, data = l.result(result_id, 0)
if data:
dn, attrs = data[0]
oldattrs = attrs
newattrs = attrs.copy()
newattrs.update(modattrs)
# now change it
newattrs.update(oldattrs)
ldif = modlist.modifyModlist(oldattrs, newattrs)
print ldif
l.modify_s(dn, ldif)
l.unbind_s()
return True
else:
return False
def check_credentials(self, username, password):
try:
ldap_client = ldap.initialize(self.config["server"])
ldap_client.set_option(ldap.OPT_REFERRALS,0)
ldap_client.simple_bind_s("uid=%s,%s" % (username, self.config["memberdn"]), password)
except ldap.INVALID_DN_SYNTAX:
ldap_client.unbind()
return False
except ldap.INVALID_CREDENTIALS:
ldap_client.unbind()
return False
except ldap.UNWILLING_TO_PERFORM:
ldap_client.unbind()
return False
except ldap.SERVER_DOWN:
ldap_client.unbind()
raise ServerDownException()
return False
ldap_client.unbind()
return True
def initialize(uri,trace_level=0,trace_file=sys.stdout,trace_stack_limit=None, bytes_mode=None):
"""
Return LDAPObject instance by opening LDAP connection to
LDAP host specified by LDAP URL
Parameters:
uri
LDAP URL containing at least connection scheme and hostport,
e.g. ldap://localhost:389
trace_level
If non-zero a trace output of LDAP calls is generated.
trace_file
File object where to write the trace output to.
Default is to use stdout.
bytes_mode
Whether to enable "bytes_mode" for backwards compatibility under Py2.
"""
return LDAPObject(uri,trace_level,trace_file,trace_stack_limit,bytes_mode)
def open(host,port=389,trace_level=0,trace_file=sys.stdout,trace_stack_limit=None,bytes_mode=None):
"""
Return LDAPObject instance by opening LDAP connection to
specified LDAP host
Parameters:
host
LDAP host and port, e.g. localhost
port
integer specifying the port number to use, e.g. 389
trace_level
If non-zero a trace output of LDAP calls is generated.
trace_file
File object where to write the trace output to.
Default is to use stdout.
bytes_mode
Whether to enable "bytes_mode" for backwards compatibility under Py2.
"""
import warnings
warnings.warn('ldap.open() is deprecated! Use ldap.initialize() instead.', DeprecationWarning,2)
return initialize('ldap://%s:%d' % (host,port),trace_level,trace_file,trace_stack_limit,bytes_mode)
def create_user_in_ldap(username, password, uidnumber):
# Open a connection
l = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
# Bind/authenticate with a user with apropriate rights to add objects
l.simple_bind_s(settings.AUTH_LDAP_BIND_DN, settings.AUTH_LDAP_BIND_PASSWORD)
# The dn of our new entry/object
dn="cn="+ username +",dc=ldap,dc=portal,dc=com"
#dn="cn=python_test,ou=People,dc=coegss,dc=hlrs,dc=de"
ctx = sha.new(password)
hash = "{SHA}" + b64encode(ctx.digest())
# A dict to help build the "body" of the object
attrs = {}
attrs['uid'] = [str(username)]
attrs['uidNumber'] = [str(uidnumber+500)]
attrs['gidNumber'] = ['100']
attrs['objectclass'] = ['inetOrgPerson','organizationalPerson','person','posixAccount','top']
attrs['cn'] = str(username)
attrs['sn'] = str(username)
attrs['userPassword'] = hash
#attrs['description'] = 'test_python_user'
attrs['homeDirectory'] = '/home/users/' + str(username)
# 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)
# Disconnect and free resources when done
l.unbind_s()
def ldap_initialize(module, server):
ldapmodule_trace_level = 1
ldapmodule_trace_file = sys.stderr
ldap._trace_level = ldapmodule_trace_level
try:
conn = ldap.initialize(
server,
trace_level=ldapmodule_trace_level,
trace_file=ldapmodule_trace_file
)
except ldap.LDAPError as e:
fail_msg = "LDAP Error initializing: {}".format(ldap_errors(e))
module.fail_json(msg=fail_msg)
return conn
def getDefaultNamingContext(self):
try:
newCon = ldap.initialize('ldap://{}'.format(self.dc_ip))
newCon.simple_bind_s('','')
res = newCon.search_s("", ldap.SCOPE_BASE, '(objectClass=*)')
rootDSE = res[0][1]
except ldap.LDAPError, e:
print "[!] Error retrieving the root DSE"
print "[!] {}".format(e)
sys.exit(1)
if not rootDSE.has_key('defaultNamingContext'):
print "[!] No defaultNamingContext found!"
sys.exit(1)
defaultNamingContext = rootDSE['defaultNamingContext'][0]
self.domainBase = defaultNamingContext
newCon.unbind()
return defaultNamingContext
def _connect_to_ldap(self):
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
connection = ldap.initialize(self.server_uri)
if self.start_tls:
try:
connection.start_tls_s()
except ldap.LDAPError:
e = get_exception()
self.module.fail_json(msg="Cannot start TLS.", details=str(e))
try:
if self.bind_dn is not None:
connection.simple_bind_s(self.bind_dn, self.bind_pw)
else:
connection.sasl_interactive_bind_s('', ldap.sasl.external())
except ldap.LDAPError:
e = get_exception()
self.module.fail_json(
msg="Cannot bind to the server.", details=str(e))
return connection
def connect(**kw):
# Sources order, see ldap.conf(3)
# variable $LDAPNOINIT, and if that is not set:
# system file /etc/ldap/ldap.conf,
# user files $HOME/ldaprc, $HOME/.ldaprc, ./ldaprc,
# system file $LDAPCONF,
# user files $HOME/$LDAPRC, $HOME/.$LDAPRC, ./$LDAPRC,
# user files <ldap2pg.yml>...
# variables $LDAP<uppercase option name>.
#
# Extra variable LDAPPASSWORD is supported.
options = gather_options(**kw)
logger.debug("Connecting to LDAP server %s.", options['URI'])
l = ldap.initialize(options['URI'])
if PY2: # pragma: nocover_py3
l = UnicodeModeLDAPObject(l)
l = LDAPLogger(l)
if options.get('USER'):
logger.debug("Trying SASL DIGEST-MD5 auth.")
auth = sasl.sasl({
sasl.CB_AUTHNAME: options['USER'],
sasl.CB_PASS: options['PASSWORD'],
}, 'DIGEST-MD5')
l.sasl_interactive_bind_s("", auth)
else:
logger.debug("Trying simple bind.")
l.simple_bind_s(options['BINDDN'], options['PASSWORD'])
return l
def __ldap_bind(self):
if not self.__ldap_conn:
l = ldap.initialize(self.ldapserver)
if self.ldaptls:
l.start_tls_s()
l.simple_bind_s(self.ldapbinddn, self.ldappasswd)
self.__ldap_conn = l
return self.__ldap_conn
def __init__(self, uri, cn, dc, secret):
self.conn = None
self.uri = uri
self.dc = dc
self.secret = secret
try:
self.conn = ldap.initialize(self.uri)
self.conn.protocol_version = ldap.VERSION3
self.conn.simple_bind_s(cn+","+self.dc,self.secret)
print("Connection established.")
except ldap.INVALID_CREDENTIALS:
print("Your username or password is incorrect.")
sys.exit()
except ldap.LDAPError as e:
if type(e.message) == dict and e.message.has_key('desc'):
print(e.message['desc'])
else: print(e)
sys.exit()
def login(username, password):
from tuckshop.core.config import Config
from tuckshop.app.models import User
if 'TUCKSHOP_DEVEL' in environ and environ['TUCKSHOP_DEVEL']:
# If tuckshop in development mode, match all passwords
# again 'password'
if password != 'password':
return False
else:
# Otherwise authenticate against LDAP server
ldap_obj = ldap.initialize('ldap://%s:389' % Config.LDAP_SERVER())
dn = 'uid=%s,%s' % (username, Config.LDAP_USER_BASE())
try:
# Attempt to bind to LDAP
ldap_obj.simple_bind_s(dn, password)
except:
# If the connection throws an exception, return False
return False
# Create user object for currently logged in user
user_object = User.objects.filter(uid=username)
# If a user object does not exist, create a new one
if (not len(user_object)):
user_object = User(uid=username)
user_object.save()
else:
user_object = user_object[0]
# Determine if the user account is a shared account.
# If it is, do not allow the user to login
if user_object.shared:
return False
# Return user object
return user_object
def __init__(
self,uri,
trace_level=0,trace_file=None,trace_stack_limit=5
):
self._trace_level = trace_level
self._trace_file = trace_file or sys.stdout
self._trace_stack_limit = trace_stack_limit
self._uri = uri
self._ldap_object_lock = self._ldap_lock()
self._l = ldap.functions._ldap_function_call(_ldap.initialize,uri)
self.timeout = -1
self.protocol_version = ldap.VERSION3
def reconnect(self,uri):
# Drop and clean up old connection completely
# Reconnect
reconnect_counter = self._retry_max
while reconnect_counter:
if __debug__ and self._trace_level>=1:
self._trace_file.write('*** Try %d. reconnect to %s...\n' % (
self._retry_max-reconnect_counter+1,uri
))
try:
# Do the connect
self._l = ldap.functions._ldap_function_call(_ldap.initialize,uri)
self._restore_options()
# StartTLS extended operation in case this was called before
if self._start_tls:
self.start_tls_s()
# Repeat last simple or SASL bind
self._apply_last_bind()
except ldap.SERVER_DOWN,e:
SimpleLDAPObject.unbind_s(self)
del self._l
if __debug__ and self._trace_level>=1:
self._trace_file.write('*** %d. reconnect to %s failed\n' % (
self._retry_max-reconnect_counter+1,uri
))
reconnect_counter = reconnect_counter-1
if not reconnect_counter:
raise
if __debug__ and self._trace_level>=1:
self._trace_file.write('=> delay %s...\n' % (self._retry_delay))
time.sleep(self._retry_delay)
else:
if __debug__ and self._trace_level>=1:
self._trace_file.write('*** %d. reconnect to %s successful, last operation will be repeated\n' % (
self._retry_max-reconnect_counter+1,uri
))
self._reconnects_done = self._reconnects_done + 1L
break
def __init__(
self,uri,
trace_level=0,trace_file=None,trace_stack_limit=5
):
self._trace_level = trace_level
self._trace_file = trace_file or sys.stdout
self._trace_stack_limit = trace_stack_limit
self._uri = uri
self._ldap_object_lock = self._ldap_lock()
self._l = ldap.functions._ldap_function_call(_ldap.initialize,uri)
self.timeout = -1
self.protocol_version = ldap.VERSION3
def reconnect(self,uri):
# Drop and clean up old connection completely
# Reconnect
reconnect_counter = self._retry_max
while reconnect_counter:
if __debug__ and self._trace_level>=1:
self._trace_file.write('*** Try %d. reconnect to %s...\n' % (
self._retry_max-reconnect_counter+1,uri
))
try:
# Do the connect
self._l = ldap.functions._ldap_function_call(_ldap.initialize,uri)
self._restore_options()
# StartTLS extended operation in case this was called before
if self._start_tls:
self.start_tls_s()
# Repeat last simple or SASL bind
self._apply_last_bind()
except ldap.SERVER_DOWN,e:
SimpleLDAPObject.unbind_s(self)
del self._l
if __debug__ and self._trace_level>=1:
self._trace_file.write('*** %d. reconnect to %s failed\n' % (
self._retry_max-reconnect_counter+1,uri
))
reconnect_counter = reconnect_counter-1
if not reconnect_counter:
raise
if __debug__ and self._trace_level>=1:
self._trace_file.write('=> delay %s...\n' % (self._retry_delay))
time.sleep(self._retry_delay)
else:
if __debug__ and self._trace_level>=1:
self._trace_file.write('*** %d. reconnect to %s successful, last operation will be repeated\n' % (
self._retry_max-reconnect_counter+1,uri
))
self._reconnects_done = self._reconnects_done + 1L
break
def adduser(self, attrs):
l = ldap.initialize(self.config["server"])
l.simple_bind(self.config["admin"], self.config["password"])
dn = "uid=%s,%s" % (attrs["uid"], self.config["memberdn"])
attrs["objectClass"] = ['top', 'account', 'simpleSecurityObject', 'xxPilot']
attrs["userPassword"] = self.makeSecret(attrs["userPassword"])
ldif = modlist.addModlist(attrs)
l.add_s(dn, ldif)
l.unbind_s()
def addgroup(self, attrs):
l = ldap.initialize(self.config["server"])
l.simple_bind(self.config["admin"], self.config["password"])
dn = "cn=%s,%s" % (attrs["cn"], self.config["groupdn"])
attrs["objectClass"] = ["groupofnames"]
ldif = modlist.addModlist(attrs)
print dn, ldif
l.add_s(dn, ldif)
l.unbind_s()
def deletegroup(self, group):
l = ldap.initialize(self.config["server"])
l.simple_bind(self.config["admin"], self.config["password"])
dn = "cn=%s,%s" % (str(group), self.config["groupdn"])
l.delete_s(dn)
l.unbind_s()
return True
def modts3id(self, uid, change, ts3id):
l = ldap.initialize(self.config["server"])
l.simple_bind(self.config["admin"], self.config["password"])
dn = "uid=%s,%s" % (uid, self.config["memberdn"])
l.modify_s(dn, [(change, 'ts3uid', ts3id)])
l.unbind_s()
return True
def modattr(self, uid, change, attr, value):
l = ldap.initialize(self.config["server"])
l.simple_bind(self.config["admin"], self.config["password"])
dn = "uid=%s,%s" % (uid, self.config["memberdn"])
l.modify_s(dn, [(change, str(attr), str(value))])
l.unbind_s()
return True