查询活动用户名时出现c#RPC服务器错误

时间:2017-02-02 12:08:27

标签: c# wmi

我有一个使用WMI连接到远程计算机的功能。当我以管理员权限启动它时,系统会显示RPC服务器错误。

我在Powershell中有相同类型的脚本,它工作正常,没有RPC服务器错误(所以WMI正在网络上工作,防火墙不阻止它。我只在互联网上找到那种答案) ,以及公司用c#编写的其他软件与这些计算机正常工作(开发人员不再为公司工作,我无法掌握源代码)

无论我使用计算机名称还是IP地址,都会出现同样的问题。

static public string GetUsername(string computer)
    {

        string username = string.Empty;
        ManagementScope scope = new ManagementScope("\\\\computer\\root\\cimv2");
        //scope.Connect(); If I activate this line, the error occurs on this line
        string queryString = "select LogonId from win32_logonsession where logontype = 2";
        ManagementObjectSearcher query = new ManagementObjectSearcher(scope, new SelectQuery(queryString));
        foreach (ManagementObject mo in query.Get()) //if scope.connect(); is not activated, it's blocking on this line
        {
            username = mo["LogonId"].ToString();

        }



        return username;
    }

我尝试从Visual Studio运行我的软件,或者直接从.exe运行我的软件(使用管理员)。我还尝试以编程方式作为工作站管理员进行模拟,但问题仍然存在。

提前感谢您的帮助。

编辑

我已经尝试过像这样的connectionOptions解决方案:

options.Username = "YOUR USERNAME";
options.Password = "YOUR PASSWORD";
options.Authority = "ntlmdomain:YOURDOMAIN";

并且像这样:

options.Username = "YOUR USERNAME";
options.Password = "YOUR PASSWORD";
options.Authority = "Kerberos:YOURDOMAIN";

并添加了impersionation选项

   options.Impersonation = ImpersonationLevel.Impersonate;
   options.EnablePrivileges = true;

仍然无法正常工作。

2 个答案:

答案 0 :(得分:1)

您是否尝试过像这样的管理工具设置用户名和密码?

static public string GetUsername(string computer)
{
    string username = string.Empty;
    ConnectionOptions options = new ConnectionOptions();
    options.Username = "YOUR USERNAME";
    options.Password = "YOUR PASSWORD";
    options.Authority = "ntlmdomain:YOURDOMAIN";
    ManagementScope scope = new ManagementScope("\\\\computer\\root\\cimv2",options);
    //scope.Connect(); If I activate this line, the error occurs on this line
    string queryString = "select LogonId from win32_logonsession where logontype = 2";
    ManagementObjectSearcher query = new ManagementObjectSearcher(scope, new SelectQuery(queryString));
    foreach (ManagementObject mo in query.Get()) //if scope.connect(); is not activated, it's blocking on this line
    {
        username = mo["LogonId"].ToString();
    }
    return username;
}

有关详细信息,请查看ManagementScope here的MSDN页面 对于ConnectionOptions here

答案 1 :(得分:1)

好的,我明白了......我的错误在于

ManagementScope scope = new ManagementScope("\\\\computer\\root\\cimv2",options);

应该是

ManagementScope scope = new ManagementScope("\\\\" + computer + "\\root\\cimv2",options); 

变量computer在字符串中无法识别,因为它在Powershell中...我很糟糕!

感谢所有试图帮助的人......下次我会更加小心!