前一段时间做了一个从SHR系统 同步用户、组织的小程序,现在分享给大家;
废话不多说,直接上代码。
首先引用:using System.DirectoryServices;
定义基本连接属性:
private string RootPath = "OU=TestOU,DC=ittest,DC=com"; //根路径
private string ADPath = "LDAP://10.10.9.230/" ; //主机地址
private string ADUser = "sunlizhen"; //登录账户
//AD管理员密码
private string ADPasssWord = "abc123";//密码
获取DirectoryEntry 对象
private DirectoryEntry GetDirectoryObject(string path ="")
{
//path LDAP://10.10.9.230/OU=TestOU,DC=ittest,DC=com
DirectoryEntry entry = null;
try
{ if (path == "")
{
entry = new DirectoryEntry(ADPath + RootPath, ADUser, ADPasssWord, AuthenticationTypes.Secure);
}
else
{
entry = new DirectoryEntry(path, ADUser, ADPasssWord, AuthenticationTypes.Secure);
string newguid = entry.Guid.ToString();
}
}
catch (Exception ex)
{
entry = null;
}
return entry;
}
获取用户对象
/// <summary>
/// 根据用户公共名称取得用户的 对象
/// </summary>
/// <param name="commonName">用户公共名称</param>
/// <returns>如果找到该用户则返回用户的对象,否则返回 null</returns>
public DirectoryEntry GetUserEntry(string commonName)
{
DirectoryEntry de = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName.Replace("\\", "") + "))";
deSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = deSearch.FindOne();
if (result == null)
return null;
//de = new DirectoryEntry(result.Path);
de = GetDirectoryObject(result.Path);
return de;
}
catch (Exception ex)
{
return null;
}
}
获取组织对象
/// <summary>
// 获取组织单位
/// </summary>
/// <param name="ouname">组织名称</param>
/// <returns></returns>
public DirectoryEntry GetOU(string ouname)
{
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.Filter = string.Format("(&(objectClass=organizationalUnit) (OU={0}))", ouname);
SearchResult results = deSearch.FindOne();
if (results != null)
{
return results.GetDirectoryEntry();
}
else
{
return null;
}
}
获取group对象
/// <summary>
/// 根据组名获取组织对象
/// </summary>
/// <param name="commonName">组名</param>
/// <returns>如果找到该用户则返回用户的对象,否则返回 null</returns>
public DirectoryEntry GetGroupEntry(string commonName)
{
DirectoryEntry de = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.Filter = "(&(objectClass=group)(cn=" + commonName + "))";
deSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = deSearch.FindOne();
if (result == null)
return null;
// de = new DirectoryEntry(result.Path);
de = GetDirectoryObject(result.Path);
return de;
}
catch (Exception ex)
{
return null;
}
}
获取用户列表
/// <summary>
/// 获取用户信息转换成Datatable
/// </summary>
public void GetUserList()
{
DirectoryEntry de = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.Filter = "(objectClass=user)";
//deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName.Replace("\\", "") + "))";
SearchResultCollection searchResultCollection = deSearch.FindAll();
string[] DirectoryList = new string[searchResultCollection.Count];
//string[] Columns = config.AppSettings.Settings["UserColumn"].Value.Split(",".ToCharArray());
//deSearch.PropertiesToLoad.AddRange(Columns);
deSearch.PropertiesToLoad.AddRange(new string[] { "name", "Path"});
SearchResult sr = deSearch.FindOne();
UserTable = new DataTable();
// GroupTable.Columns.Add("CN");
System.Collections.ICollection propColls = sr.Properties.PropertyNames;
foreach (object item in propColls)
{
// 创建datatable的列
UserTable.Columns.Add(item.ToString());
}
foreach (SearchResult item in searchResultCollection)
{
DataRow dr = UserTable.NewRow();
foreach (object item02 in propColls)
{ try
{
dr[item02.ToString()] = item.Properties[item02.ToString()][0].ToString();
}
catch
{
}
}
UserTable.Rows.Add(dr);
}
}
新建用户 或更新用户信息
/// <summary>
///
/// </summary>
/// <param name="login">用户ID</param>
/// <param name="pareapath">组织路径</param>
/// <param name="PropertyVlues">属性结合,可自行查询属性名</param>
public void CreateNewUser(string login, string pareapath, Dictionary<string, string> PropertyVlues)
{
//如果用户信息存在,就变为更新
pareapath = GetFullPathName(pareapath);
//Catalog catalog = new Catalog();
DirectoryEntry de = GetOrgEntry(pareapath);
if (de == null)
{
Common.Sys.Record("---warning---");
Common.Sys.Record(login + " " + pareapath + "找不到对应的组织数据");
Common.Sys.Record("---warning---");
// 找不到组织
return;
}
//遍历key 判断账户是否禁用
bool DisableState = true;
foreach (string key in PropertyVlues.Keys)
{
if (key == "DisableState")
{
if (PropertyVlues[key] == "0")
{
DisableState = false;
}
break;
}
}
/// 1. Create user account
DirectoryEntries users = de.Children;
DirectoryEntry newuser = users.Add("CN=" + login, "user");
DirectoryEntry olduser = GetUserEntry(login);
if (olduser != null)
{
Common.Sys.Record(login + " " + pareapath + "用户信息已经存在,开始更新信息");
// 找不到组织
if (DisableState)
{
DisableAccount(olduser);
Common.Sys.Record(login + "账户禁用");
return;
}
newuser = olduser;
if (de.Path != olduser.Parent.Path)
{
newuser.MoveTo(de);
Common.Sys.Record(login + " 组织由" + olduser.Parent.Path + "变更为" + de.Path);
}
}
else
{
if (DisableState)
{
Common.Sys.Record(login + "离职,无须新建");
return;
}
newuser.CommitChanges();
/// 3. Set password
newuser.AuthenticationType = AuthenticationTypes.Secure;
object[] password = new object[] { ADHelper.SetSecurePassword() };
object ret = newuser.Invoke("SetPassword", password);
newuser.CommitChanges();
Common.Sys.Record(login + " " + pareapath + "密码设置成功");
/// 4. Enable account
EnableAccount(newuser);
Common.Sys.Record(login + " " + pareapath + "账户启用");
}
/// 2. Set properties
//遍历key
foreach (string key in PropertyVlues.Keys)
{
if (key == "DisableState") // 账户禁用跳过
{
continue;
}
if (key == "manager")
{
DirectoryEntry manger = GetUserEntry(PropertyVlues[key]);
if (manger != null)
{
newuser.Properties["manager"].Value = manger.Properties["distinguishedName"].Value;
newuser.CommitChanges();
Common.Sys.Record(login + " " + "管理者更新完毕");
}
continue;
}
else
{
ADHelper.SetProperty(newuser, key, PropertyVlues[key]);
}
newuser.CommitChanges();
}
//newuser.CommitChanges();
Common.Sys.Record(login + " " + "属性更新完毕");
/// 5. Add user account to groups
AddUserToGroup(de, newuser, de.Name.Replace("OU=",""));
/// 6. Create a mailbox in Microsoft Exchange
//GenerateMailBox(login);
newuser.Close();
de.Close();
}
/// <summary>
/// 设置指定的属性值
/// </summary>
/// <param name="de"></param>
/// <param name="propertyName">属性名称?</param>
/// <param name="propertyValue">属性值</param>
public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue)
{
if (de.Properties.Contains(propertyName))
{
if (String.IsNullOrEmpty(propertyValue))
{
de.Properties[propertyName].RemoveAt(0);
}
else
{
de.Properties[propertyName][0] = propertyValue;
}
}
else
{
if (!String.IsNullOrEmpty(propertyValue))
{
de.Properties[propertyName].Add(propertyValue);
}
}
}
/// <summary>
/// 生成随机密码
/// </summary>
/// <returns></returns>
public static string SetSecurePassword()
{
//RandomPassword rp = new RandomPassword();
// config.AppSettings.Settings["UserColumn"].Value.Split(",".ToCharArray());
return config.AppSettings.Settings["ADPassWord"].Value.ToString();
}
/// <summary>
/// 设置用户新密码
/// </summary>
/// <param name="path"></param>
public static void SetPassword(DirectoryEntry newuser)
{
newuser.AuthenticationType = AuthenticationTypes.Secure;
object[] password = new object[] { SetSecurePassword() };
object ret = newuser.Invoke("SetPassword", password);
newuser.CommitChanges();
newuser.Close();
}
/// <summary>
/// 启用用户帐号
/// </summary>
/// <param name="de"></param>
private static void EnableAccount(DirectoryEntry de)
{
de.Properties["userAccountControl"].Value = 544;
de.CommitChanges();
}
/// <summary>
/// 禁用用户帐号
/// </summary>
/// <param name="de"></param>
private static void DisableAccount(DirectoryEntry de)
{
de.Properties["userAccountControl"].Value = 546;
de.CommitChanges();
}
添加用户到组
/// <summary>
/// 添加用户到组
/// </summary>
/// <param name="de"></param>
/// <param name="deUser"></param>
/// <param name="GroupName"></param>
public void AddUserToGroup(DirectoryEntry de, DirectoryEntry deUser, string GroupName)
{
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
// deSearch.Filter = "(&(objectClass=group) (cn=" + GroupName + "))";
deSearch.Filter = "(objectClass=group)";
SearchResultCollection results = deSearch.FindAll();
bool isGroupMember = false;
object userADGroups = deUser.Invoke("groups",null);
//string[] groups = (string[])deUser.Properties["memberOf"].Value;
string groupName = "";
if (results.Count > 0)
{
DirectoryEntry group = GetDirectoryObject(results[0].Path.ToString());
groupName = group.Properties["distinguishedName"][0].ToString();
//item.Properties["distinguishedName"][0].ToString()
}
if (results.Count > 0)
{
DirectoryEntry group = GetDirectoryObject(results[0].Path.ToString());
object members = group.Invoke("Members", null);
foreach (object member in (IEnumerable)members)
{
DirectoryEntry x = new DirectoryEntry(member);
if (x.Name != deUser.Name)
{
isGroupMember = false;
}
else
{
isGroupMember = true;
break;
}
}
if (!isGroupMember)
{
group.Invoke("Add", new object[] { deUser.Path.ToString() });
Common.Sys.Record("组"+groupName + "添加用户:" + deUser.Name + "完毕");
}
group.Close();
}
// 删除用户不同组织下的组
foreach (string groupDN in deUser.Properties["memberOf"])
{
if (groupDN != groupName)
{
DirectoryEntry group = GetDirectoryObject(ADPath + groupDN);
group.Invoke("Remove", new object[] { deUser.Path.ToString() });
Common.Sys.Record("组" + group.Name + "删除用户:" + deUser.Name + "完毕");
}
}
return;
}
添加OU 组织
/// <summary>
///
/// </summary>
/// <param name="ouname">组织名称</param>
/// <param name="DisplayName">显示名称</param>
/// <param name="pareapath">父路径</param>
// OU=TestOU,DC=ittest,DC=com
public void AddOU(string ouname,string DisplayName,string pareapath)
{
if (pareapath == "")
{
pareapath = RootPath;
}
else
{
pareapath = pareapath +","+ RootPath;
}
try
{
DirectoryEntry pare = GetOrgEntry(pareapath);
//pare.Rename("OU=" + "MIS004");
DirectoryEntry newadd = pare.Children.Add("OU=" + ouname, "organizationalUnit");
// DirectoryEntry newadd = pare.Children.Add("CN=" + ouname, "user");
// 判断是否存在
DirectoryEntry oldord = GetDirectoryObject(newadd.Path);
if (oldord!=null)
{
Common.Sys.Record(ouname + " "+ DisplayName + " " + pareapath + "组织存在,开始更新");
newadd = oldord;
}
ADHelper.SetProperty(newadd, "displayName", DisplayName);
ADHelper.SetProperty(newadd, "description", DisplayName);
newadd.CommitChanges();
Common.Sys.Record(ouname + " " + DisplayName + " " + pareapath + "组织更新完毕");
}
catch
{
}
}
/// 删除ou
public void ReMoveOU(string ouname)
{
DirectoryEntry OUEntry = GetOrgEntry(ouname);
DirectoryEntry OUParent = OUEntry.Parent;
OUParent.Children.Remove(OUEntry);
OUParent.CommitChanges();
}
添加 组
/// <summary>
///
/// </summary>
/// <param name="ouname"></param>
/// <param name="DisplayName"></param>
/// <param name="pareapath"></param>
public void AddGroup(string ouname, string DisplayName, string pareapath)
{
if (pareapath == "")
{
pareapath = RootPath;
}
else
{
pareapath = pareapath + "," + RootPath;
}
try
{
DirectoryEntry pare = GetOrgEntry(pareapath);
//pare.Rename("OU=" + "MIS004");
DirectoryEntry newadd = pare.Children.Add("CN=" + ouname, "group");
// DirectoryEntry newadd = pare.Children.Add("CN=" + ouname, "user");
// 判断是否存在
DirectoryEntry oldord = GetGroupEntry(ouname);
if (oldord != null)
{
if (pare.Path != oldord.Parent.Path)
{
oldord.MoveTo(pare);
Common.Sys.Record(ouname + " 组移动");
}
Common.Sys.Record(ouname + " " + DisplayName +" " +pareapath + "组存在,开始更新");
newadd = oldord;
}
ADHelper.SetProperty(newadd, "displayName", DisplayName);
ADHelper.SetProperty(newadd, "description", DisplayName);
ADHelper.SetProperty(newadd, "sAMAccountName", ouname);
ADHelper.SetProperty(newadd, "groupType", "-2147483640");
newadd.CommitChanges();
Common.Sys.Record(ouname + " " + DisplayName + " " + pareapath + "组更新完毕");
}
catch
{
}
}