<p>Within c#, I need to be able to</p>

<ul>
<li>Connect to a remote system, specifying username/password as appropriate</li>
<li>List the members of a localgroup on that system</li>
<li>Fetch the results back to the executing computer</li>
</ul>

<p>So for example I would connect to \SOMESYSTEM with appropriate creds, and fetch back a list of local administrators including SOMESYSTEM\Administrator, SOMESYSTEM\Bob, DOMAIN\AlanH, "DOMAIN\Domain Administrators".</p>

<p>I've tried this with system.directoryservices.accountmanagement but am running into problems with authentication. Sometimes I get:</p>

<p><em>Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again. (Exception from HRESULT: 0x800704C3)</em></p>

<p>The above is trying because there will be situations where I simply cannot unmap existing drives or UNC connections.</p>

<p>Other times my program gets UNKNOWN ERROR and the security log on the remote system reports an error 675, code 0x19 which is KDC_ERR_PREAUTH_REQUIRED.</p>

<p>I need a simpler and less error prone way to do this!</p>

[{'answer_id': 21534, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 0, 'selected': False, 'text': "<p>You should be able to do this with System.DirectoryServices.DirectoryEntry.  If you are having trouble running it remotely, maybe you could install something on the remote machines to give you your data via some sort of RPC, like remoting or a web service.  But I think what you're trying should be possible remotely without getting too fancy.</p>\n"}, {'answer_id': 21543, 'author': 'Nick', 'author_id': 1490, 'author_profile': 'https://Stackoverflow.com/users/1490', 'pm_score': 0, 'selected': False, 'text': "<p>If Windows won't let you connect through it's login mechanism, I think your only option is to run something on the remote machine with an open port (either directly or through remoting or a web service, as mentioned).</p>\n"}, {'answer_id': 21546, 'author': 'dguaraglia', 'author_id': 2384, 'author_profile': 'https://Stackoverflow.com/users/2384', 'pm_score': 2, 'selected': True, 'text': '<p>This should be easy to do using WMI. Here you have a pointer to some docs:</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/aa394507.aspx" rel="nofollow noreferrer">WMI Documentation for Win32_UserAccount</a></p>\n\n<p>Even if you have no previous experience with WMI, it should be quite easy to turn that VB Script code at the bottom of the page into some .NET code.</p>\n\n<p>Hope this helped!</p>\n'}, {'answer_id': 21584, 'author': 'Scott Wisniewski', 'author_id': 1737192, 'author_profile': 'https://Stackoverflow.com/users/1737192', 'pm_score': 1, 'selected': False, 'text': '<p>I would recommend using the Win32 API function <a href="http://msdn.microsoft.com/en-us/library/aa370601.aspx" rel="nofollow noreferrer">NetLocalGroupGetMembers</a>. It is much more straight forward than trying to figure out the crazy LDAP syntax, which is necessary for some of the other solutions recommended here. As long as you impersonate the user you want to run the check as by calling "LoginUser", you should not run into any security issues.</p>\n\n<p>You can find sample code for doing the impersonation <a href="http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx" rel="nofollow noreferrer">here</a>.</p>\n\n<p>If you need help figuring out how to call "NetLocalGroupGetMembers" from C#, I reccomend that you checkout Jared Parson\'s PInvoke assistant, which you can <a href="http://www.codeplex.com/clrinterop" rel="nofollow noreferrer">download</a> from codeplex.</p>\n\n<p>If you are running the code in an ASP.NET app running in IIS, and want to impersonate the user accessing the website in order to make the call, then you may need to grant "Trusted for Delegation" permission to the production web server. </p>\n\n<p>If you are running on the desktop, then using the active user\'s security credentials should not be a problem.</p>\n\n<p>It is possible that you network admin could have revoked access to the "Securable Object" for the particular machine you are trying to access. Unfortunately that access is necessary for all of the <a href="http://msdn.microsoft.com/en-us/library/aa370675.aspx" rel="nofollow noreferrer">network management api</a> functions to work. If that is the case, then you will need to grant access to the "Securable Object" for whatever users you want to execute as. With the default windows security settings all authenticated users should have access, however.</p>\n\n<p>I hope this helps.</p>\n\n<p>-Scott</p>\n'}, {'answer_id': 24075, 'author': 'quux', 'author_id': 2383, 'author_profile': 'https://Stackoverflow.com/users/2383', 'pm_score': 2, 'selected': False, 'text': '<p>davidg was on the right track, and I am crediting him with the answer.</p>\n\n<p>But the WMI query necessary was a little less than straightfoward, since I needed not just a list of users for the whole machine, but the subset of users <em>and groups</em>, whether local or domain, that were members of the local Administrators group. For the record, that WMI query was:</p>\n\n<pre><code>SELECT PartComponent FROM Win32_GroupUser WHERE GroupComponent = "Win32_Group.Domain=\'thehostname\',Name=\'thegroupname\'"\n</code></pre>\n\n<p>Here\'s the full code snippet:</p>\n\n<pre><code>public string GroupMembers(string targethost, string groupname, string targetusername, string targetpassword)\n        {\n            StringBuilder result = new StringBuilder(); \n            try\n            {\n                ConnectionOptions Conn = new ConnectionOptions();\n                if (targethost != Environment.MachineName) //WMI errors if creds given for localhost\n                {\n                    Conn.Username = targetusername; //can be null\n                    Conn.Password = targetpassword; //can be null\n                }\n                Conn.Timeout = TimeSpan.FromSeconds(2);\n                ManagementScope scope = new ManagementScope("\\\\\\\\" + targethost + "\\\\root\\\\cimv2", Conn);\n                scope.Connect();\n                StringBuilder qs = new StringBuilder();\n                qs.Append("SELECT PartComponent FROM Win32_GroupUser WHERE GroupComponent = \\"Win32_Group.Domain=\'");\n                qs.Append(targethost);\n                qs.Append("\',Name=\'");\n                qs.Append(groupname);\n                qs.AppendLine("\'\\"");\n                ObjectQuery query = new ObjectQuery(qs.ToString());\n                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);\n                ManagementObjectCollection queryCollection = searcher.Get();\n                foreach (ManagementObject m in queryCollection)\n                {\n                    ManagementPath path = new ManagementPath(m["PartComponent"].ToString());                                        \n                    { \n                        String[] names = path.RelativePath.Split(\',\');\n                        result.Append(names[0].Substring(names[0].IndexOf("=") + 1).Replace("\\"", " ").Trim() + "\\\\"); \n                        result.AppendLine(names[1].Substring(names[1].IndexOf("=") + 1).Replace("\\"", " ").Trim());                    \n                    }\n                }\n                return result.ToString();\n            }\n            catch (Exception e)\n            {\n                Console.WriteLine("Error. Message: " + e.Message);\n                return "fail";\n            }\n        }\n</code></pre>\n\n<p>So, if I invoke Groupmembers("Server1", "Administrators", "myusername", "mypassword"); I get a single string returned with:  </p>\n\n<p>SERVER1\\Administrator<br>\nMYDOMAIN\\Domain Admins  </p>\n\n<p>The actual WMI return is more like this:</p>\n\n<p>\\\\SERVER1\\root\\cimv2:Win32_UserAccount.Domain="SERVER1",Name="Administrator"</p>\n\n<p>... so as you can see, I had to do a little string manipulation to pretty it up.</p>\n'}]
['https://Stackoverflow.com/questions/21514', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2383/']