.NET 版 和 PYThon 操作LDAP

24 篇文章 0 订阅
string strOperatorName = ds.Tables["employee"].Rows[0]["strOperatorName"].ToString();
string DomainName = "buynow";
string FilterStr = "(samAccountName=" + strOperatorName + ")";
System.DirectoryServices.DirectorySearcher FindMe = new System.DirectoryServices.DirectorySearcher(DomainName);
FindMe.Filter = FilterStr;
System.DirectoryServices.SearchResult FindRes = FindMe.FindOne();
string strpath = FindRes.Path;
System.DirectoryServices.DirectoryEntry tempEntry = new System.DirectoryServices.DirectoryEntry(strpath, userName, password);


//帐号禁用
string userDN = tempEntry.Properties["distinguishedName"].Value.ToString();
tempEntry.UsePropertyCache = true;
tempEntry.Properties["userAccountControl"].Value = 546;

tempEntry.CommitChanges();


//2移除该员工在group的组,所有group组
foreach (object moveGroup in tempEntry.Properties["memberOf"])
{
    string strGroup = "LDAP://" + moveGroup.ToString();
    System.DirectoryServices.DirectoryEntry oGrp = new System.DirectoryServices.DirectoryEntry(strGroup, userName, password);
    oGrp.Properties["member"].Remove(tempEntry.Properties["distinguishedName"].Value.ToString());
    oGrp.CommitChanges();
}

在来个python版的

# -*- coding: utf-8 -*-
# https://www.python-ldap.org/doc/html/index.html
import ldap

from ldapTest import Config


class LdapHelper:
    def __init__(self, base_dn=Config.ldap_base_dn):
        self.host = Config.ldap_host
        self.user = Config.ldap_user
        self.pwd = Config.ldap_pwd
        self.base_dn = base_dn
        self.conn = self.get_conn()

    def get_conn(self):
        # 不加这个访问不到MS的服务
        ldap.set_option(ldap.OPT_REFERRALS, 0)
        conn = ldap.initialize('ldap://{0}'.format(self.host))
        conn.protocol_version = ldap.VERSION3
        conn.simple_bind_s(self.user, self.pwd)
        return conn

    def replace_OperatorName(self, strOperatorName):
        strOperatorName = strOperatorName.replace('(', '\28')
        strOperatorName = strOperatorName.replace(')', '\29')
        strOperatorName = strOperatorName.replace('&', '\26')
        strOperatorName = strOperatorName.replace('|', '\7c')

        return strOperatorName

    def get_user_info(self, strOperatorName):
        filter = '(samAccountName={0})'.format(self.replace_OperatorName(strOperatorName))
        searchScope = ldap.SCOPE_SUBTREE

        result = self.conn.search_s(self.base_dn, searchScope, filter, None)

        for i in result:
            if i[0] and i[1]:
                return [i[0], i[1]]

        return None


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值