从PsExec命令检索cmd提示输出?

时间:2014-05-05 20:35:03

标签: c# psexec

使用案例:我通过PsExec运行命令检查远程系统上的某些凭据(例如,我试图检索当前安装在远程系统上的知识库文章)。

我有以下内容来检索命令输出:

public string GetCmDOutput(string cmd)
    ProcessStartInfo startInfo = new ProcessStartInfo("control", cmd)
    {
        WindowStyle = ProcessWindowStyle.Hidden,
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    };

    string output = string.Empty;

    Process process = Process.Start(startInfo);
    process.OutputDataReceived += (sender, e) => output = string.Concat(output, e.Data);
    process.BeginOutputReadLine();
    process.Start();
    process.WaitForExit();
    Delay.Milliseconds(1500) //API-specific delay

    return output;
}

每当我使用GetCmdOutput()在本地运行命令时它就像魅力一样,但如果我尝试用PsExec运行命令,我的输出就是空的。

例如,我运行了以下内容:

string cmd = @"\psexec.exe \\remoteComputerName -u username -p password -c cmd /c wmic qfe";
GetCmdOutput(cmd);
Report.Info(cmd); //API-specific reporting

返回一个空字符串。

在玩了几个小时后,我觉得我可能需要第二眼。可能导致此问题的原因是什么?

1 个答案:

答案 0 :(得分:2)

我遇到了同样的问题。我的解决方案是运行cmd并让它调用psexec。我将psexec的输出保存到临时文件中以便进一步操作。我的代码返回一个List。

public List<string> ExecutePSExec(string hostname)
{
    List<string> recordNames = new List<string>();
    string command = @"\\path\to\psexec.exe /accepteula \\" + hostname + ". exe-to-run-remotely";
    try
    {
        string location = AppDomain.CurrentDirectory.BaseDirectory;
        string cmdWithFileOutput = string.Format("{0} >{1}temp.log", command, location);

        procStartInfo.UseShellExecute = true;
        procStartInfo.CreateNoWindow = true;
        procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

        Process proc = new Process();
        proc.StartInfo = procStartInfo;
        proc.Start();
        proc.WaitForExit();

        // Read file contents, manipulate data and then delete temp file here
    }
    catch (Exception e)
    {
        Console.WriteLine("Failure to run psexec: {0}", e.Message);
    }

    return recordNames;
}

注意:我遇到了另一个问题,发现以这种方式运行psexec要求命令中的远程主机名(而不是IP地址)在句号\\" + hostname + ".

此代码假定您可以作为当前用户在远程计算机上运行psexec。

相关问题