终止远程计算机上的进程

本文关键字:进程 计算机 终止 | 更新日期: 2023-09-27 18:21:00

我正试图终止远程机器上的进程。但我犯了错误。我做错了什么?我该怎么做?

我的代码:

var iu = new ImpersonateUser();
try
{
    iu.Impersonate(Domain, _userName, _pass);
    foreach (var process in Process.GetProcessesByName("notepad", "RemoteMachine"))
    {
        string processPath = pathToExe; //Is set as constant (and is correct)
        process.Kill();
        Thread.Sleep(3000);
        Process.Start(processPath);
    }
}
catch (Exception ex)
{
    lblStatus.Text = ex.ToString();
}
finally
{
    iu.Undo();
}

只是为了澄清ImpersonateUser,它让我以正确的用户权限登录到远程机器。所以问题不存在。在这种情况下,当我调试和检查流程对象时,我会为记事本找到正确的流程ID。所以连接很好。但当我试图杀死这个过程时,我会得到这个错误:

System.NotSupportedException:远程计算机不支持该功能。在System.Diagnostics.Process.EnsureState

终止远程计算机上的进程

System.Diagnostics.Process类不能终止远程进程。您可以使用System.Management命名空间(一定要设置引用)来使用WMI。

下面是一个简单的例子。

var processName = "iexplore.exe";
var connectoptions = new ConnectionOptions();
connectoptions.Username = @"YourDomainName'UserName";
connectoptions.Password = "User Password";
string ipAddress = "192.168.206.53";
ManagementScope scope = new ManagementScope(@"''" + ipAddress + @"'root'cimv2", connectoptions);
// WMI query
var query = new SelectQuery("select * from Win32_process where name = '" + processName + "'");
using (var searcher = new ManagementObjectSearcher(scope, query))
{
    foreach (ManagementObject process in searcher.Get()) // this is the fixed line
    {
        process.InvokeMethod("Terminate", null);
    }
}
Console.ReadLine();