如何在C#中获取含登录工作站的Active Directory用户
获取Active Directory用户的LogOnTo(登录工作站)字段方法
Active Directory中用户的LogOnTo字段对应的LDAP属性是userWorkstations,你可以通过System.DirectoryServices直接读取这个属性值,以下是两种常见实现方式:
1. 使用DirectorySearcher批量查询用户
using System.DirectoryServices; // 初始化AD搜索器 DirectorySearcher adSearcher = new DirectorySearcher(); // 过滤仅用户对象 adSearcher.Filter = "(objectClass=user)"; // 指定需要加载的属性,减少查询开销 adSearcher.PropertiesToLoad.AddRange(new string[] { "samAccountName", "userWorkstations" }); // 遍历查询结果 foreach (SearchResult userResult in adSearcher.FindAll()) { string userName = userResult.Properties["samAccountName"][0].ToString(); // 检查是否存在登录工作站限制 if (userResult.Properties.Contains("userWorkstations")) { // 属性值为逗号分隔的工作站名称列表 string allowedWorkstations = userResult.Properties["userWorkstations"][0].ToString(); Console.WriteLine($"用户 {userName} 允许登录的工作站: {allowedWorkstations}"); } else { Console.WriteLine($"用户 {userName} 无登录工作站限制"); } }
2. 使用DirectoryEntry获取单个用户属性
如果你已经获取到目标用户的DirectoryEntry对象,可以直接读取属性:
using System.DirectoryServices; // 替换为目标用户的LDAP路径 DirectoryEntry userEntry = new DirectoryEntry("LDAP://CN=示例用户,OU=员工,DC=yourdomain,DC=com"); if (userEntry.Properties.Contains("userWorkstations")) { string allowedWorkstations = userEntry.Properties["userWorkstations"][0].ToString(); Console.WriteLine($"允许登录的工作站: {allowedWorkstations}"); } else { Console.WriteLine("该用户无登录工作站限制"); }
注意事项
userWorkstations属性仅在用户设置了登录工作站限制时才会存在,未设置时不会返回该属性,因此读取前必须先判断属性是否存在。- 属性值以逗号分隔多个工作站名称,可根据需求拆分处理。
内容的提问来源于stack exchange,提问作者Sina Akbari
相关产品推荐
相关产品推荐

