在远程机器上执行 C# 代码

Execute C# code on remote machine

我有一段代码想在远程计算机上执行。我不知道该怎么做。就像我想在远程机器上执行下面给出的命令该怎么做。

 Process[] processlist = Process.GetProcesses();

这只是一个例子,就像我想在带有库的远程机器上执行整个代码一样。

如果您要回答获取进程列表为

SelectQuery selectQuery = new SelectQuery("Select * from Win32_Process");
using(ManagementObjectSearcher searcher =new ManagementObjectSearcher(manScope, selectQuery))

我已经知道了,请保存。有没有办法在连接到范围后执行整个代码。

远程机器上 GetProcesses() 没有重载,但如果您只是寻找特定的进程名称,您可以尝试 GetProcessesByName(string, string) 重载,它允许您通过一台机器name 作为第二个参数。

有关详细信息,请参阅 MSDN:https://msdn.microsoft.com/en-us/library/725c3z81(v=vs.110).aspx

另外请注意,您实际上并不是在远程计算机上执行命令,而是向远程计算机发出请求。为此,您需要研究 WCF(Windows Communication Foundation;从这里开始:https://msdn.microsoft.com/en-us/library/ms731082%28v=vs.110%29.aspx)。您可以 运行 远程计算机上的服务并让本地计算机上的客户端使用该服务。客户端可能会发送类似 "Get me all the processes!" 的消息,并且服务会 return 在远程计算机上 运行 宁 Process.GetProcesses() 之后的进程列表。

如果您正在询问一种无需任何特殊工具或库即可在远程计算机上执行任意代码的方法,none(或者更确切地说,有时有,但它们被认为是主要安全措施漏洞并在发现时进行修补)。

或者,可以使用远程桌面协议 (RDP) 来实现您想要实现的目标。可以通过编程方式使用它,但您可能很难将它限制在一个应用程序中。

只是一个想法,.NET 远程处理怎么样?

https://msdn.microsoft.com/library/kwdt6w2k%28v=VS.71%29.aspx?f=255&MSPPError=-2147217396

要获取远程机器上的进程列表,只需在括号中输入远程机器的名称..

      Process[] processlist = Process.GetProcesses(Remotemachine);

供参考: https://msdn.microsoft.com/en-us/library/1f3ys1f9%28v=vs.110%29.aspx

一些可能性:

  1. 使用 PowerShell 运行 远程命令:link
Enter-PSSession -ComputerName your-computer-name -Credential your-user-name
Set-Location "C:\your\code\location.exe"
.\location.exe
  1. NuGet 包 SSH.net:
//using Renci.SshNet; //Make sure the Nuget package is install and compatible
using (var client = new SshClient("your-computer-name", "your-user-name", "your-password")) 
{
    client.Connect();
    client.RunCommand("cd .\your\code\");
    SshCommand sc = client.RunCommand("location.exe");
    MessageBox.Show(sc.Error);
    MessageBox.Show(sc.Result);
    client.Disconnect();
}
  1. 通过c#启动远程控制:link
Process process = new Process();
process.StartInfo = new ProcessStartInfo(@"cmd.exe", "/C mstsc /v:\"your-computer-name\"");
process.Start();
public static string DoProcess(string cmd, string argv)
        {
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = cmd;
            p.StartInfo.Arguments = $" {argv}";
            p.StartInfo.CreateNoWindow = true;
            //p.StartInfo.Verb = "RunAs";
            p.Start();
            p.WaitForExit();
            string output = p.StandardOutput.ReadToEnd();
            p.Dispose();

            return output;
        }