[英]C# ActiveDirectory - How do I add a local user account remotely from a domain-joined machine to a non-domain machine
我正在尝试在非域加入的计算机上添加本地用户帐户。 我已经尝试了几乎所有我能想到的东西。 我在同一个域中的机器上工作,但不在域外机器上工作。 我可以ping和TS到这个服务器,但似乎无法添加管理员。
是否可以使用DirectoryEntry执行此操作?
这是我当前拥有的代码(为便于阅读而略作更改):
private string AddLocalAdmin_NonDomain(string ComputerName)
{
StartImpersonation(); //Uses advapi32.dll->LogonUser()
string ErrMsg = "";
const int ADS_UF_DONT_EXPIRE_PASSWD = 0x10000;
DirectoryEntry AD = new DirectoryEntry("WinNT://" + ComputerName + ",computer", ComputerName + "\\" + UserCredentials.Username, UserCredentials.Password);
object n = AD.NativeObject;
DirectoryEntry NewUser = AD.Children.Add(Username, "user");
NewUser.Invoke("SetPassword", new object[] { Password });
if (!PasswordExpires)
{
int val = ADS_UF_DONT_EXPIRE_PASSWD;
NewUser.InvokeSet("userFlags", new object[] { val });
}
NewUser.CommitChanges();
DirectoryEntry grp;
grp = AD.Children.Find("Administrators", "group");
if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); }
EndImpersonation(); //Ends the impersonation
return ErrMsg; //returns "Access Denied"
}
您可以使用
System.DirectoryServices.AccountManagement
并实现以下代码
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine);
//Create New User
UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext, "Your UserName", "Your Password", true /*Enabled or not*/);
oUserPrincipal.UserPrincipalName = "Your UserName";
oUserPrincipal.GivenName = "Given Name";
oUserPrincipal.Surname = "Surname";
oUserPrincipal.Save();
//Add User to Group
GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, "Your Group Name");
oGroupPrincipal.Members.Add(oUserPrincipal);
oGroupPrincipal.Save();
有关完整实施的信息,请访问http://anyrest.wordpress.com/2010/06/28/active-directory-c/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.