11

I'm trying to kill a process on a remote machine. But I get error. What am I doing wrong and how can I make this work?

My code:

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

Just to clarify ImpersonateUser, it makes me login to the remote machine with correct user rights. So the problem is not there. When I debug and check the process object I find the correct process ID for notepad in this case. So the connection works fine. But when I try to kill the process I get this error:

System.NotSupportedException: Feature is not supported for remote machines. at System.Diagnostics.Process.EnsureState

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
MrProgram
  • 5,044
  • 13
  • 58
  • 98
  • From my previous non-answer that I deleted: From Micrsoft's documentation on `Process.Kill`: [You are attempting to call Kill for a process that is running on a remote computer. The method is available only for processes running on the local computer.](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill%28v=vs.110%29.aspx) – JoelC Jan 24 '17 at 16:26
  • Duplicate - http://stackoverflow.com/questions/348112/kill-a-process-on-a-remote-machine-in-c-sharp?rq=1 – vapcguy Jan 25 '17 at 18:42

1 Answers1

24

The System.Diagnostics.Process class cannot kill a remote process. You can use the System.Management namespace (be sure to set a reference), to use WMI.

A simple example is below.

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();
David Crowell
  • 3,711
  • 21
  • 28
  • Can I cancel a running thread, i.e. System.Threading.Task using CancellationToken on a remote machine ? – starklord Mar 13 '18 at 07:09
  • 1
    If you start a remote shell process within the same AppDomain (on the same machine), you can kill it with the process handle. Beware, as Thread.Terminate concerns still apply. – Latency Aug 02 '18 at 23:57