我有一个需要使用 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);
}