Bla*_*sor 5 .net c# windows wmi command-line
我有一个remote server name(窗口),username和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);
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
这个功能是我经过一番研究后想到的。希望它可以帮助别人。
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6146 次 |
| 最近记录: |