5

我有一个remote server name(Windows)usernamepassword.

使用 C# .Net,我想run a command在远程服务器上取回console output

有没有办法在 C# 中做到这一点?

我能够使用WMI以下代码(部分)运行命令,但没有获得控制台输出的运气。我只能取回Process ID

ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_Process");
ManagementClass processClass = new ManagementClass(scope, managementPath,objectGetOptions);

ManagementBaseObject inParams = processClass.GetMethodParameters("Create");

inParams["CommandLine"] = "cmd.exe /c "+ mycommand;
ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

有任何想法吗?

4

2 回答 2

5

这个功能是我经过一番研究后得出的。希望它可以帮助别人。

public string executeCommand(string serverName, string username, string password, string domain=null, string command)
{
    try
    {
        System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.RedirectStandardOutput = true;
        startInfo.UseShellExecute = false;
        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        if (null != username)
        {
            if (null != domain)
            {
                startInfo.Arguments = "/C \"psexec.exe \\\\" + serverName + " -u " + domain+"\\"+username + " -p " + password + " " + command + "\"";
            }
            else
            {
                startInfo.Arguments = "/C \"psexec.exe \\\\" + serverName + " -u " + username + " -p " + password + " " + command + "\"";
            }
        }
        else
        {
            startInfo.Arguments = "/C \"utils\\psexec.exe "+serverName+" "+ command + "\"";
        }
        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit();

        if (process.ExitCode == 0 && null != process && process.HasExited)
        {
           return process.StandardOutput.ReadToEnd();
        }
        else
        {
            return "Error running the command : "+command;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
于 2013-04-11T22:39:53.197 回答
1

您可以尝试使用 PsTools 执行命令。他们提供的众多功能之一是PsExec。它允许您在远程服务器上运行命令。它还应该将结果返回到控制台(在运行它的本地 PC 上)。

于 2013-04-11T07:15:01.527 回答