在 Windows 远程服务器中运行命令并获取 C# .NET 中的控制台输出

2023-11-21

我有一个remote server name(视窗),username and password.

使用 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);

有任何想法吗?


这个功能是我经过一番研究后想出来的。希望它对其他人有帮助。

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;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Windows 远程服务器中运行命令并获取 C# .NET 中的控制台输出 的相关文章

随机推荐