从WMI运行exe时的网络身份验证

And*_*ndy 11 .net c# wmi unc windows-authentication

我有一个需要使用WMI运行并访问网络共享的C#exe.但是,当我访问共享时,我得到一个UnauthorizedAccessException.如果我直接运行exe,则可以访问共享.我在两种情况下都使用相同的用户帐户.

我的应用程序有两个部分,一个在本地PC上运行的GUI客户端和一个在远程PC上运行的后端进程.当客户端需要连接到后端时,它首先使用WMI启动远程进程(下面转载的代码).远程进程执行许多操作,包括使用Directory.GetDirectories()访问网络共享并向客户端报告.

当客户端使用WMI自动启动远程进程时,它无法访问网络共享.但是,如果我使用远程桌面连接到远程计算机并手动启动后端进程,则会成功访问网络共享.

WMI调用中指定的用户和远程桌面会话登录的用户是相同的,因此权限应该相同,不是吗?

我在Directory.Exists()的MSDN条目中看到它指出"Exists方法不执行网络身份验证.如果您在未经过预先身份验证的情况下查询现有网络共享,则Exists方法将返回false." 我认为这是相关的?如何确保在WMI会话中正确验证用户身份?

ConnectionOptions opts = new ConnectionOptions();

opts.Username = username;
opts.Password = password;

ManagementPath path = new ManagementPath(string.Format("\\\\{0}\\root\\cimv2:Win32_Process", remoteHost));

ManagementScope scope = new ManagementScope(path, opts);

scope.Connect();

ObjectGetOptions getOpts = new ObjectGetOptions();
using (ManagementClass mngClass = new ManagementClass(scope, path, getOpts))
{
    ManagementBaseObject inParams = mngClass.GetMethodParameters("Create");
    inParams["CommandLine"] = commandLine;
    ManagementBaseObject outParams = mngClass.InvokeMethod("Create", inParams, null);
}
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 2

按照上面 Isalamon 建议的链接(谢谢)后,我按照 Jestro 的建议并使用 psexec.exe 重写(可以从http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx下载)而不是WMI。这样做感觉有点麻烦,但似乎可行。

为遇到类似问题的人提供新代码:

Process proc = new Process();
proc.StartInfo.FileName = "PsExec.exe";
proc.StartInfo.Arguments = string.Format("\\\\{0} -d -u {1}\\{2} -p {3} {4}",
                                         remoteHost,
                                         domain,
                                         username,
                                         password,
                                         commandLine);
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
Run Code Online (Sandbox Code Playgroud)