【问题标题】:Executing Process on a remote Machine c#在远程机器上执行进程 c#
【发布时间】:2018-07-24 13:04:51
【问题描述】:

我通过远程计算机上的 WMI 连接。

用户名和密码设置正确。

var options = new ConnectionOptions();
servicePath = "\\\\Testserver\\root\\cimv2";
options.EnablePrivileges = true;
options.Username = username;
options.Password = pwd;
serviceScope = new ManagementScope(servicePath, options);
serviceScope.Connect();

这是我想在远程机器上运行的代码序列

Process process = new Process();
process.StartInfo.FileName = "diskpart.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.StandardInput.WriteLine("list volume");
process.StandardInput.WriteLine("exit");
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();

// extract information from output
string table = output.Split(new string[] { "DISKPART>" }, StringSplitOptions.None)[1];
var rows = table.Split(new string[] { "\n" }, StringSplitOptions.None);
for (int i = 3; i < rows.Length; i++)
{
    if (rows[i].Contains("Volume"))
    {
        int index = Int32.Parse(rows[i].Split(new string[] { " " }, StringSplitOptions.None)[3]);
        string label = rows[i].Split(new string[] { " " }, StringSplitOptions.None)[8];
        Console.WriteLine($@"Volume {index} {label}:\");
    }
}

如果我要像这样通过 wmi 调用进程...

object[] theProcessToRun = { "diskpart" };
using (var managementClass = new ManagementClass(serviceScope, new ManagementPath("Win32_Process"), new ObjectGetOptions()))
{
managementClass.InvokeMethod("Create", theProcessToRun);
}

我可以调用这个进程,但是没有机会交出我想在这个进程中执行的命令...

如何解决?

【问题讨论】:

  • 您缺少问题描述。我确定有用于卷信息list volume 返回的 WMI 类,为什么不走那条路呢。
  • 这句话是什么意思? but havent the possibilites to hand over the commands i would like to execute in this process...
  • 我知道,WMI 类可以给我卷信息。我知道。但我需要一个进程调用,我必须执行命令。目前我正在使用“List Volumes”命令,因为它们不会破坏任何东西。稍后我必须扩展卷,但首先我必须将命令传输到该进程的命令行。
  • 为了更好地解释问题描述。我想通过 WMI 连接到远程机器。这就是我已经做过的。之后我想调用diskpart进程,因为我以后必须扩展一个卷。不幸的是,我无法传输命令,我通常可以在上面之前的帖子的中间代码部分使用这些命令。那么如何将命令传输到进程?
  • 使用 Psexe 在远程机器上执行进程 c#

标签: c# wmi remoting


【解决方案1】:

您可以使用脚本作为包含您的命令的命令行参数的一部分传入。

参考:https://www.computerhope.com/diskpart.htm

您还应该使用 cmd 将输出重定向到文件,因为您也应该直接获取输出。

对于脚本,请确保您使用其他机器/用户可以访问的 unc。对于输出文件,请确保您使用其他机器/用户可以写入并且您可以通过程序读取的 unc。

【讨论】:

  • 好的,好的,我可以调用这个对象的函数[] theProcessToRun = { "diskpart /select volume f" }; -> 所以 diskpart 正在使用卷 f。位我需要第二个命令来扩展磁盘。如果我再次调用该命令,我不能调用它两次,据我所知,我调用了该进程的一个新实例,对吗?
  • 是的..你会调用第二个进程..除非你使用我上面提到的脚本方法
  • 好的,对于那部分,我有一个脚本文件是必要的。嗯....首先我以为我可以将命令连接起来,但这行不通。我想我必须这样做
猜你喜欢
  • 2011-01-21
  • 2017-04-17
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
  • 2016-02-24
相关资源
最近更新 更多