【问题标题】:Kill process on remote machine杀死远程机器上的进程
【发布时间】:2014-11-01 20:29:15
【问题描述】:

我正在尝试终止远程计算机上的进程。但我得到错误。我做错了什么,我该如何做?

我的代码:

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: Feature is not supported for remote machines. at System.Diagnostics.Process.EnsureState

【问题讨论】:

标签: c# process remote-access kill-process


【解决方案1】:

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();

【讨论】:

  • 我可以在远程机器上使用 CancellationToken 取消正在运行的线程,即 System.Threading.Task 吗?
  • 如果你在同一个 AppDomain 中(在同一台机器上)启动一个远程 shell 进程,你可以用进程句柄杀死它。当心,因为 Thread.Terminate 问题仍然适用。
猜你喜欢
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多