gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:32:26 25 4
gpt4 key购买 nike

我有一个远程服务器名称 (windows)、用户名密码

使用 C# .Net,我想在远程服务器上运行命令并取回控制台输出

有没有办法在 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;
}
}

关于c# - 在 Windows 远程服务器中运行命令并在 C# .NET 中取回控制台输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15937167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com