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