本文整理汇总了Python中ldap3.SYNC属性的典型用法代码示例。如果您正苦于以下问题:Python ldap3.SYNC属性的具体用法?Python ldap3.SYNC怎么用?Python ldap3.SYNC使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类ldap3
的用法示例。
在下文中一共展示了ldap3.SYNC属性的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SYNC [as 别名]
def setUp(self):
ldap3mock.setLDAPDirectory(LDAPDirectory)
host = "localhost"
u = "manager"
p = "ldaptest"
self.base = "o=test"
srv = ldap3.Server(host, port=389, use_ssl=False, connect_timeout=5)
self.c = ldap3.Connection(srv, user=u, password=p,
auto_referrals=False,
client_strategy=ldap3.SYNC, check_names=True,
authentication=ldap3.SIMPLE, auto_bind=False)
self.c.open()
self.c.bind()
示例2: ldap_query
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SYNC [as 别名]
def ldap_query(self, query):
if not self.ldap_enabled:
return None
from ldap3 import Server, Connection, SIMPLE, SYNC, ASYNC, SUBTREE, ALL, ALL_ATTRIBUTES
import json
try:
logging.debug("connecting to ldap server {} on port {}".format(self.ldap_server, self.ldap_port))
with Connection(
Server(self.ldap_server, port = self.ldap_port, get_info = ALL),
auto_bind = True,
client_strategy = SYNC,
user=self.ldap_bind_user,
password=self.ldap_bind_password,
authentication=SIMPLE,
check_names=True) as c:
logging.debug("running ldap query for ({})".format(query))
c.search(self.ldap_base_dn, '({})'.format(query), SUBTREE, attributes = ALL_ATTRIBUTES)
# a little hack to move the result into json
response = json.loads(c.response_to_json())
result = c.result
if len(response['entries']) < 1:
return None
# XXX not sure about the 0 here, I guess only if we only looking for one thing at a time
return response['entries'][0]['attributes']
except Exception as e:
logging.warning("failed ldap query {}: {}".format(query, e))
return None
示例3: tivoli_ldap_query
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SYNC [as 别名]
def tivoli_ldap_query(self, query):
if not self.tivoli_ldap_enabled:
return None
from ldap3 import Server, Connection, SIMPLE, SYNC, ASYNC, SUBTREE, ALL, ALL_ATTRIBUTES
import json
try:
logging.debug("connecting to tivoli ldap server {} on port {}".format(self.tivoli_server, self.tivoli_ldap_port))
with Connection(
Server(self.tivoli_server, port = self.tivoli_ldap_port , get_info = ALL),
auto_bind = False,
client_strategy = SYNC,
user=self.tivoli_bind_user,
password=self.tivoli_bind_password,
authentication=SIMPLE,
check_names=True) as c:
logging.debug("running tivoli ldap query for ({})".format(query))
c.search(self.tivoli_base_dn, '({})'.format(query), SUBTREE, attributes = ALL_ATTRIBUTES)
# a little hack to move the result into json
response = json.loads(c.response_to_json())
result = c.result
if len(response['entries']) < 1:
return None
# XXX not sure about the 0 here, I guess only if we only looking for one thing at a time
return response['entries'][0]['attributes']
except Exception as e:
logging.warning("failed tivoli ldap query {}: {}".format(query, e))
return None
示例4: ldap_authenticate
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SYNC [as 别名]
def ldap_authenticate(request,username,password,groups_allowed=True):
#change these values to what is appropriate for your environment
id_name="uid"
ldap_host="192.168.0.2"
ldap_port="389"
bind_dn="cn=Manager,dc=bbotte,dc=com"
bind_pass="123456"
user_base="ou=People,dc=bbotte,dc=com"
#bind with service account
s = Server(ldap_host, port=int(ldap_port), get_info=ALL)
c = Connection(
s,
authentication=SIMPLE,
user=bind_dn,
password=bind_pass,
check_names=True,
lazy=False,
client_strategy=SYNC,
raise_exceptions=False)
c.open()
c.bind()
if c.bound:
#once bound, check username provided and get cn, memberOf list and mail
# get cn_name
c.search(user_base,'(%s=%s)'%(id_name,username),attributes=['cn','mail'])
c.unbind
try:
cn_name=c.entries[0].cn
except:
print("user cn cannot be found")
auth_logger.error("user cn cannot be found")
session['username']=username
return True
else:
auth_logger.debug('ldap bind failed')
c.unbind()
return False
示例5: _make_connection
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SYNC [as 别名]
def _make_connection(
self, bind_user=None, bind_password=None, contextualise=True, app=None, **kwargs
):
"""
Make a connection.
Args:
bind_user (str): User to bind with. If `None`, AUTH_ANONYMOUS is
used, otherwise authentication specified with
config['LDAP_BIND_AUTHENTICATION_TYPE'] is used.
bind_password (str): Password to bind to the directory with
contextualise (bool): If true (default), will add this connection to the
appcontext so it can be unbound upon app_teardown.
Returns:
ldap3.Connection: An unbound ldap3.Connection. You should handle exceptions
upon bind if you use this internal method.
"""
if app is None:
app = current_app._get_current_object()
authentication = ldap3.ANONYMOUS
if bind_user:
authentication = getattr(
ldap3, current_app.config.get("LDAP_BIND_AUTHENTICATION_TYPE")
)
log.debug(
"Opening connection with bind user '{}'".format(bind_user or "Anonymous")
)
connection = ldap3.Connection(
server=app.ldap3_login_manager_server_pool,
read_only=current_app.config.get("LDAP_READONLY"),
user=bind_user,
password=bind_password,
client_strategy=ldap3.SYNC,
authentication=authentication,
check_names=current_app.config["LDAP_CHECK_NAMES"],
raise_exceptions=True,
**kwargs
)
if contextualise:
self._contextualise_connection(connection)
return connection
示例6: init_app
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SYNC [as 别名]
def init_app(self, app):
ssl_defaults = ssl.get_default_verify_paths()
# Default config
app.config.setdefault('LDAP_SERVER', 'localhost')
app.config.setdefault('LDAP_PORT', 389)
app.config.setdefault('LDAP_BINDDN', None)
app.config.setdefault('LDAP_SECRET', None)
app.config.setdefault('LDAP_CONNECT_TIMEOUT', 10)
app.config.setdefault('LDAP_READ_ONLY', False)
app.config.setdefault('LDAP_VALID_NAMES', None)
app.config.setdefault('LDAP_PRIVATE_KEY_PASSWORD', None)
app.config.setdefault('LDAP_RAISE_EXCEPTIONS', False)
app.config.setdefault('LDAP_CONNECTION_STRATEGY', SYNC)
app.config.setdefault('LDAP_USE_SSL', False)
app.config.setdefault('LDAP_USE_TLS', True)
app.config.setdefault('LDAP_TLS_VERSION', ssl.PROTOCOL_TLSv1)
app.config.setdefault('LDAP_REQUIRE_CERT', ssl.CERT_REQUIRED)
app.config.setdefault('LDAP_CLIENT_PRIVATE_KEY', None)
app.config.setdefault('LDAP_CLIENT_CERT', None)
app.config.setdefault('LDAP_CA_CERTS_FILE', ssl_defaults.cafile)
app.config.setdefault('LDAP_CA_CERTS_PATH', ssl_defaults.capath)
app.config.setdefault('LDAP_CA_CERTS_DATA', None)
app.config.setdefault('FORCE_ATTRIBUTE_VALUE_AS_LIST', False)
self.tls = Tls(
local_private_key_file=app.config['LDAP_CLIENT_PRIVATE_KEY'],
local_certificate_file=app.config['LDAP_CLIENT_CERT'],
validate=app.config['LDAP_REQUIRE_CERT'],
version=app.config['LDAP_TLS_VERSION'],
ca_certs_file=app.config['LDAP_CA_CERTS_FILE'],
valid_names=app.config['LDAP_VALID_NAMES'],
ca_certs_path=app.config['LDAP_CA_CERTS_PATH'],
ca_certs_data=app.config['LDAP_CA_CERTS_DATA'],
local_private_key_password=app.config['LDAP_PRIVATE_KEY_PASSWORD']
)
self.ldap_server = Server(
host=app.config['LDAP_SERVER'],
port=app.config['LDAP_PORT'],
use_ssl=app.config['LDAP_USE_SSL'],
connect_timeout=app.config['LDAP_CONNECT_TIMEOUT'],
tls=self.tls,
get_info=ALL
)
# Store ldap_conn object to extensions
app.extensions['ldap_conn'] = self
# Teardown appcontext
app.teardown_appcontext(self.teardown)
示例7: login
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SYNC [as 别名]
def login(username: str, password: str) -> tuple:
try:
if SERVER.lower().startswith("ldaps://"):
server = Server(SERVER, port = PORT, get_info = NONE, use_ssl = True)
else:
server = Server(SERVER, port = PORT, get_info = NONE, use_ssl = False) # define an unsecure LDAP server, requesting info on DSE and schema
c = None
if BIND_DN is not None and BIND_DN != '':
c = Connection(server, auto_bind = True, client_strategy = SYNC, user=BIND_DN, password=BIND_PASSWORD, authentication=SIMPLE, check_names=True)
else:
c = Connection(server, auto_bind = True, client_strategy = SYNC, user=None, password=None, authentication=ANONYMOUS, check_names=True)
except Exception as e:
error = "Error connecting to LDAP server: %s" % e
raise LDAPLoginError({"error_message": error})
try:
if(SEARCH_SUFFIX is not None and SEARCH_SUFFIX != ''):
search_filter = '(%s=%s)' % (SEARCH_PROPERTY, username + SEARCH_SUFFIX)
else:
search_filter = '(%s=%s)' % (SEARCH_PROPERTY, username)
if SEARCH_FILTER:
search_filter = '(&%s(%s))' % (search_filter, SEARCH_FILTER)
c.search(search_base = SEARCH_BASE,
search_filter = search_filter,
search_scope = SUBTREE,
attributes = [EMAIL_PROPERTY,FULL_NAME_PROPERTY],
paged_size = 5)
if len(c.response) > 0:
dn = c.response[0].get('dn')
user_email = c.response[0].get('raw_attributes').get(EMAIL_PROPERTY)[0].decode('utf-8')
full_name = c.response[0].get('raw_attributes').get(FULL_NAME_PROPERTY)[0].decode('utf-8')
user_conn = Connection(server, auto_bind = True, client_strategy = SYNC, user = dn, password = password, authentication = SIMPLE, check_names = True)
return (user_email, full_name)
raise LDAPLoginError({"error_message": "Username or password incorrect"})
except Exception as e:
error = "LDAP account or password incorrect: %s" % e
raise LDAPLoginError({"error_message": error})
示例8: bind_ldap_user
# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import SYNC [as 别名]
def bind_ldap_user(self, username, password):
"""
Attempts to bind the specified username and password and returns
an LDAPUser object representing the user.
Returns None if the bind was unsuccessful.
This implements direct binding.
"""
# Construct the user to bind as
if settings.BIND_TEMPLATE:
# Full CN
ldap_bind_user = settings.BIND_TEMPLATE.format(username=username,
base_dn=settings.BASE_DN)
elif settings.USERNAME_PREFIX:
# Prepend a prefix: useful for DOMAIN\user
ldap_bind_user = settings.USERNAME_PREFIX + username
elif settings.USERNAME_SUFFIX:
# Append a suffix: useful for user@domain
ldap_bind_user = username + settings.USERNAME_SUFFIX
logger.debug('Attempting to authenticate to LDAP by binding as ' + ldap_bind_user)
try:
c = ldap3.Connection(self.backend,
read_only=True,
lazy=False,
auto_bind=True,
client_strategy=ldap3.SYNC,
authentication=ldap3.SIMPLE,
user=ldap_bind_user,
password=password)
except ldap3.core.exceptions.LDAPSocketOpenError as e:
logger.error('LDAP connection error: ' + str(e))
return None
except ldap3.core.exceptions.LDAPBindError as e:
if 'invalidCredentials' in str(e):
# Invalid bind DN or password
return None
else:
logger.error('LDAP bind error: ' + str(e))
return None
except Exception as e:
logger.exception('Caught exception when trying to connect and bind to LDAP')
raise
# Search for the user using their full DN
search_filter = '({}={})'.format(settings.UID_ATTRIB, username)
attributes = self.search_ldap(c, search_filter, attributes=LDAPUser._attrib_keys, size_limit=1)
if not attributes:
logger.error('LDAP search error: no results for ' + search_filter)
return None
# Construct an LDAPUser instance for this user
return LDAPUser(c, attributes)