将控制台输出重定向到日志文件

时间:2014-02-17 14:58:54

标签: c# .net wmi

我正在使用c#的WMI API来连接到远程服务器并执行一些命令。我已成功建立连接。我现在需要的是将远程CMD的输出重定向到本地计算机的日志文件中。

这是我的代码:

ConnectionOptions options = new ConnectionOptions();
options.Username = "login";
options.Password = "password";
ManagementScope scope = new ManagementScope("\\\\myserver\\root\\cimv2", options);
scope.Options.EnablePrivileges = true;
scope.Options.Impersonation = System.Management.ImpersonationLevel.Impersonate;
try
{
    scope.Connect();
    System.Management.ManagementClass local_ClassInstance = new System.Management.ManagementClass(scope, new System.Management.ManagementPath("Win32_Process"), null);
    Console.WriteLine("SUCCESS");
    //execute the command
    System.Management.ManagementBaseObject local_InParams = local_ClassInstance.GetMethodParameters("Create");
    local_InParams["CommandLine"] = @"cmd.exe /C myCommand";
    local_InParams["CurrentDirectory"] = @"mypath";
    System.Management.ManagementBaseObject local_ManagementBaseObject = local_ClassInstance.InvokeMethod("Create", local_InParams, null);
}
catch (Exception e)
{
    Console.WriteLine("FAILURE"+e.ToString());
}

修改

我尝试使用'>'来完成此操作原始的:

local_InParams["CommandLine"] = "command > log.txt";

但是我创建的输出文件不包含任何内容。

我还尝试使用流程

执行此操作
Process myProcess = new Process();
myProcess.StartInfo.FileName = "ipconfig";
myProcess.StartInfo.Arguments = "/all";
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.Start();
myProcess.WaitForExit();
string myResult = myProcess.StandardOutput.ReadToEnd();
Console.WriteLine(myResult);
myProcess.Close();

但是进程不返回我想要的信息,因为我想要远程机器的cmd输出(因为我想在运行命令时记录服务器的行为)。

请帮忙吗?

1 个答案:

答案 0 :(得分:1)

我也遇到捕获问题,发现另一种重定向与你的相似...

myProcess.StartInfo.RedirectStandardError = true;
// trap normal data received AND any ERROR data received too
myProcess.OutputDataReceived += DOSOutputResultsHandler;
myProcess.ErrorDataReceived += DOSOutputErrorsHandler;

我还有两个字符串构建器属性,用于捕获执行DOS调用过程的类的输出响应

StringBuilder DOSOutputResults = new StringBuilder();
StringBuilder DOSOutputErrors = new StringBuilder();


protected void DOSOutputResultsHandler(object sendingProcess,
   System.Diagnostics.DataReceivedEventArgs outLine)
{
   if (!string.IsNullOrEmpty(outLine.Data))
      // track data into the NORMAL output string builder
      DOSOutputResults.Append(Environment.NewLine + outLine.Data);
}


protected void DOSOutputErrorsHandler(object sendingProcess,
   System.Diagnostics.DataReceivedEventArgs outLine)
{
   if (!String.IsNullOrEmpty(outLine.Data))
      // track data into the ERROR output string builder
      DOSOutputErrors.Append(Environment.NewLine + outLine.Data);
}

此外,使用原语“>”重定向,还有一个“2>”处理未重定向到正常输出的错误的重定向。我在处理DOS调用Java时发现了这一点。