gpt4 book ai didi

c# - 杀死远程机器上的进程

转载 作者:可可西里 更新时间:2023-11-01 08:57:30 27 4
gpt4 key购买 nike

我正试图终止远程机器上的进程。但我得到错误。我做错了什么,我该如何解决这个问题?

我的代码:

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

最佳答案

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

关于c# - 杀死远程机器上的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25727323/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com