一个简单的python模块,用于常见的active directory身份验证和查找任务

easyad的Python项目详细描述


一个简单的python模块,用于常见的active directory身份验证和查找任务

Copyright 2016 Sean Whalen

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

为什么?

大多数针对python和/或flask的ldap解决方案的重点是成为通用ldap 接口。这取决于开发人员理解并围绕 活动目录的怪癖。该模块旨在降低复杂性。 以及python驱动的安全应用程序的开发时间 与活动目录的接口。

功能

  • python 2和3支持
  • Unicode支持
  • 通过直接绑定验证用户凭据
  • 快速测试用户是否是组(包括嵌套组)的成员
  • 查询用户和组属性
  • 简单的用户和组搜索
  • 获取用户所属的所有组,包括嵌套组
  • 获取所有组成员用户的列表,包括来自嵌套组的用户
  • 为json安全自动将二进制数据转换为base64的选项 输出

安装

首先,安装系统依赖项

$ sudo apt-get install libsasl2-dev python3-dev python3-pip libldap2-dev libssl-dev

然后

$ sudo pip3 install -U easyad

示例使用

from __future__ import unicode_literals, print_function

from getpass import getpass
from json import dumps

from easyad import EasyAD

# Workaround to make input() return a string in Python 2 like it does in Python 3
# It's 2016...you should really be using Python 3
try:
    input = raw_input
except NameError:
        pass

# Set up configuration. You could also use a Flask app.config
config = dict(AD_SERVER="ad.example.net",
              AD_DOMAIN="example.net",
              CA_CERT_FILE="myrootca.crt")

# Initialize all the things!
ad = EasyAD(config)

# Authenticate a user
username = input("Username: ")
password = getpass("Password: ")

local_admin_group_name = "LocalAdministrators"

user = ad.authenticate_user(username, password, json_safe=True)

if user:
    # Successful login! Let's print your details as JSON
    print(dumps(user, sort_keys=True, indent=2, ensure_ascii=False))

    # Lets find out if you are a member of the "LocalAdministrators" group
    print(ad.user_is_member_of_group(user, local_admin_group_name))
else:
    print("Those credentials are invalid. Please try again.")
    exit(-1)

# You can also add service account credentials to the config to do lookups without
# passing in the credentials on every call
ad.config["AD_BIND_USERNAME"] = "SA-ADLookup"
ad.config["AD_BIND_PASSWORD"] = "12345LuggageAmazing"

user = ad.get_user("maurice.moss", json_safe=True)
print(dumps(user, sort_keys=True, indent=2, ensure_ascii=False))

group = ad.get_group("helpdesk", json_safe=True)
print(dumps(user, sort_keys=True, indent=2, ensure_ascii=False))

print("Is Jen a manager?")
print(ad.user_is_member_of_group("jen.barber", "Managers"))

# The calls below can be taxing on an AD server, especially when used frequently.
# If you just need to check if a user is a member of a group use
# EasyAD.user_is_member_of_group(). It is *much* faster.

# I wonder who all is in the "LocalAdministrators" group? Let's run a
# query that will search in nested groups.
print(dumps(ad.get_all_users_in_group(local_admin_group_name, json_safe=True)))

# Let's see all of the groups that Moss in in, including nested groups
print(dumps(ad.get_all_user_groups(user), indent=2, ensure_ascii=False))

简易方法

转换时间戳(时间戳,json安全=false)

Converts a LDAP timestamp to a datetime or a human-readable string

Args:
    timestamp: the LDAP timestamp
    json_safe: If true, return a a human-readable string instead of a datetime

Returns:
    A datetime or a human-readable string

增强用户(user,json-safe=false)

Adds computed attributes to AD user results

Args:
    user: A dictionary of user attributes
    json_safe: If true, converts binary data into base64,
    And datetimes into human-readable strings

Returns:
    An enhanced dictionary of user attributes

处理LDAP结果(结果,JSON安全=false)

Converts LDAP search results from bytes to a dictionary of UTF-8 where possible

Args:
    results: LDAP search results
    json_safe: If true, convert binary data to base64 and datetimes to human-readable strings

Returns:
    A list of processed LDAP result dictionaries.

简易adconnection

A LDAP configuration abstraction class

Attributes:
    config: The configuration dictionary
    ad:The LDAP interface instance

ADconnection.\uu init(自我,配置)

Initializes an ADConnection object

 Args:
    config: A dictionary of configuration settings
        Required:
            AD_SERVER: The hostname of the Active Directory Server
        Optional:
            AD_REQUIRE_TLS: Require a TLS connection. True by default.
            AD_CA_CERT_FILE: The path to the root CA certificate file
            AD_PAGE_SIZE: Overrides the default page size of 1000
            AD_OPTIONS: A dictionary of other python-ldap options

adconnection.bind(self,credentials=none)

Attempts to bind to the Active Directory server

Args:
    credentials: A optional dictionary of the username and password to use.
    If credentials are not passed, the credentials from the initial EasyAD configuration are used.

Returns:
    True if the bind was successful

Raises:
    ldap.LDAP_ERROR

adconnection.unbind(自身)

Unbind from the Active Directory server

容易。容易

A high-level class for interacting with Active Directory

Attributes:
    user_attributes: A default list of attributes to return from a user query
    group_attributes: A default list of attributes to return from a user query

简易初始化(自我,配置)

Initializes an EasyAD object

 Args:
    config: A dictionary of configuration settings
        Required:
            AD_SERVER: the hostname of the Active Directory Server
            AD_DOMAIN: The domain to bind to, in TLD format
        Optional:
            AD_REQUIRE_TLS: Require a TLS connection. True by default.
            AD_CA_CERT_FILE: the path to the root CA certificate file
            AD_BASE_DN: Overrides the base distinguished name. Derived from AD_DOMAIN by default.

easyad.authenticate_user(self,username,password,base=none,attributes=none,json_safe=false)

Test if the given credentials are valid

Args:
    username: The username
    password: The password
    base: Optionally overrides the base object DN
    attributes: A list of user attributes to return
    json_safe: Convert binary data to base64 and datetimes to human-readable strings

Returns:
    A dictionary of user attributes if successful, or False if it failed

Raises:
    ldap.LDAP_ERROR

easyad.get_all_用户组(self,user,base=none,credentials=none,json_safe=false)

Returns a list of all group DNs that a user is a member of, including nested groups

Args:
    user: A username, distinguishedName, or a dictionary containing a distinguishedName
    base: Overrides the configured base object dn
    credentials: An optional dictionary of the username and password to use
    json_safe: If true, convert binary data to base64 and datetimes to human-readable strings

Returns:
    A list of group DNs that the user is a member of, including nested groups

Raises:
    ldap.LDAP_ERROR

Notes:
    This call can be taxing on an AD server, especially when used frequently.
    If you just need to check if a user is a member of a group,
    use EasyAD.user_is_member_of_group(). It is *much* faster.

easyad.get_组中的所有用户(self,group,base=none,credentials=none,json_safe=false)

Returns a list of all user DNs that are members of a given group, including from nested groups

Args:
   group: A group name, cn, or dn
   base: Overrides the configured base object dn
   credentials: An optional dictionary of the username and password to use
   json_safe: If true, convert binary data to base64 and datetimes to human-readable strings

Returns:
   A list of all user DNs that are members of a given group, including users from nested groups

Raises:
    ldap.LDAP_ERROR

Notes:
   This call can be taxing on an AD server, especially when used frequently.
   If you just need to check if a user is a member of a group,
   use EasyAD.user_is_member_of_group(). It is *much* faster.

easyad.get_group(self,group_string,base=none,credentials=none,attributes=none,json_safe=false)

Searches for a unique group object and returns its attributes

Args:
    group_string: A group name, cn, or dn
    base: Optionally override the base object dn
    credentials: A optional dictionary of the username and password to use.
    If credentials are not passed, the credentials from the initial EasyAD configuration are used.
    attributes: An optional list of attributes to return. Otherwise uses self.group_attributes.
    To return all attributes, pass an empty list.
    json_safe: If true, convert binary data to base64 and datetimes to human-readable strings

Returns:
    A dictionary of group attributes

Raises:
    ValueError: Query returned no or multiple results
    ldap.LDAP_ERROR: An LDAP error occurred

easyad.get_user(self,user_string,json_safe=false,credentials=none,attributes=none)

Searches for a unique user object and returns its attributes

Args:
    user_string: A userPrincipalName, sAMAccountName, or distinguishedName
    json_safe: If true, convert binary data to base64 and datetimes to human-readable strings
    credentials: A optional dictionary of the username and password to use.
    If credentials are not passed, the credentials from the initial EasyAD configuration are used.
    attributes: An optional list of attributes to return. Otherwise uses self.user_attributes.
    To return all attributes, pass an empty list.

Returns:
    A dictionary of user attributes

Raises:
    ValueError: query returned no or multiple results

easyad.resolve_group_dn(self,group,base=none,credentials=none,json_safe=false)

Returns a group's DN when given a principalAccountName, sAMAccountName, email, or DN

Args:
    group: A group name, CN, or DN, or a dictionary containing a DN
    base: Optionally overrides the base object DN
    credentials: An optional dictionary of the username and password to use
    json_safe: If true, convert binary data to base64 and datetimes to human-readable strings

Returns:
    The groups's DN

Raises:
    ldap.LDAP_ERROR

easyad.resolve_user_dn(self,user,base=none,credentials=none,json_safe=false)

Returns a user's DN when given a principalAccountName, sAMAccountName, email, or DN

Args:
    user: A principalAccountName, sAMAccountName, email, DN, or a dictionary containing a DN
    base: Optionally overrides the base object DN
    credentials: An optional dictionary of the username and password to use
    json_safe: If true, convert binary data to base64 and datetimes to human-readable strings

Returns:
    The user's DN

Raises:
    ldap.LDAP_ERROR
搜索(self,base=none,scope=ldap.scope_subtree,filter_string=”(objectClass=*)”,凭证=none,
属性=无,json安全=假,页面大小=无)
Run a search of the Active Directory server, and get the results

Args:
    base: Optionally override the DN of the base object
    scope: Optional scope setting, subtree by default.
    filter_string: Optional custom filter string
    credentials: Optionally override the bind credentials
    attributes: A list of attributes to return. If none are specified, all attributes are returned
    json_safe: If true, convert binary data to base64, and datetimes to human-readable strings
    page_size: Optionally override the number of results to return per LDAP page

Returns:
    Results as a list of dictionaries

Raises:
    ldap.LDAP_ERROR

Notes:
    Setting a small number of search_attributes and return_attributes reduces server load and bandwidth
    respectively
搜索组(self,group_string,base=none,search_attributes=none,return_attributes=none,
凭据=无,json安全=假)
Returns matching group objects as a list of dictionaries

Args:
    group_string: The substring to search for
    base: Optionally override the base object's DN
    search_attributes: The attributes to search through, with binary data removed
    easyad.EasyAD.group_attributes by default
    return_attributes: A list of attributes to return. easyad.EasyAD.group_attributes by default
    credentials: Optionally override the bind credentials
    json_safe: If true, convert binary data to base64 and datetimes to human-readable strings

Returns:
    Results as a list of dictionaries

Raises:
    ldap.LDAP_ERROR

Notes:
    Setting a small number of search_attributes and return_attributes reduces server load and bandwidth
    respectively
搜索用户(self,user_string,base=none,search_attributes=none,return_attributes=none,credentials=none,
json_safe=false)
Returns matching user objects as a list of dictionaries

Args:
    user_string: The substring to search for
    base: Optionally override the base object's DN
    search_attributes: The attributes to search through, with binary data removed
    easyad.EasyAD.user_attributes by default
    return_attributes: A list of attributes to return. easyad.EasyAD.user_attributes by default
    credentials: Optionally override the bind credentials
    json_safe: If true, convert binary data to base64 and datetimes to human-readable strings

Returns:
    Results as a list of dictionaries

Raises:
    ldap.LDAP_ERROR

Notes:
    Setting a small number of search_attributes and return_attributes reduces server load and bandwidth
    respectively

用户是组的成员(self,user,group,base=none,credentials=none)

Tests if a given user is a member of the given group

Args:
    user: A principalAccountName, sAMAccountName, email, or DN
    group: A group name, cn, or dn
    base: An optional dictionary of the username and password to use
    credentials: An optional dictionary of the username and password to use

Raises:
ldap.LDAP_ERROR

Returns:
    A boolean that indicates if the given user is a member of the given group

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java无法使用JSF访问托管bean方法   java是制作具有多值类型的HashMap的正确方法   javafx中TicTacToe的java更新UI   windows Java文件。getCanonicalFile()无法处理冒号“:”   java在一个布局屏幕中创建多个(26)按钮   java Android Studio:Gradle构建完成,有251个错误   我们如何在Java上为callfireapiclient编写单元/集成测试?   java无法将1715UTC转换为本地/gmt类型   具有已定义的数字序列的JAVA循环   Java程序正在netbeans中编译,但未在CMD中编译,包不存在   java Android构造函数和onCreate()之间有什么区别?   java配置弹性搜索结果评分   java LibGDX纹理是否可绘制?   java如何在Android中设置应用程序默认打开pdf   java是否有一种创造性的方法将多个参数传递给contentEquals()方法?   java在Android上存储Ed25519私钥