未加入域的机器如何获取Active Directory用户的域名?
未加入域的机器上通过SID提取AD用户域名的可行方案
在未加入域的机器上,我尝试用System.DirectoryServices从本地Active Directory获取用户信息,但原本在已加入域的机器上正常运行的域名提取代码失效了:
public static string GetDomainName(this SecurityIdentifier sid) { string? ntAccount = sid.Translate(typeof(NTAccount)).ToString(); return ntAccount.Split('\\')[0]; }
这段代码的逻辑是把SID转换为NTAccount格式后拆分出域名,但推测它依赖机器与域控制器的关联,所以在非域机器上无法工作。我需要提取MyDomain\myuser格式里的域名,求可行方案。
更新:验证有效的解决方案
尝试通过全局编录查询用户信息,初始代码如下:
var user = new DirectoryEntry($"GC://my.company.com:636/<SID={sid}>", "username", "password", AuthenticationTypes.Encryption);
但执行后返回“服务器返回了引用”的结果。通过ExtendedErrorMessage属性中的ref 1字段获取到正确的服务器地址后,修改为以下查询方式即可正常运行:
var user = new DirectoryEntry($"LDAP://other.my.company.com/<SID={sid}>", "username", "password", AuthenticationTypes.ServerBind);
修改要点:
- 协议从GC改为LDAP
- 移除端口号
- 将AuthenticationType改为ServerBind
内容的提问来源于stack exchange,提问作者NSouth
相关产品推荐
相关产品推荐

