【发布时间】:2014-02-17 14:58:53
【问题描述】:
我正在使用 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 输出(因为我想要运行命令时服务器行为的日志)。
有什么帮助吗?
【问题讨论】:
-
您对如何将命令提示符命令的输出重定向到文件做了哪些研究?这是非常容易发现的信息。
-
我看到我可以在命令后使用 '>' 或 '>>' 来执行此操作,但它不起作用。我还看到了另一种使用 System.Management.ManagementBaseObject 执行此操作的方法,但它不会重定向控制台的内容,而是重定向进程日志的内容。
-
“它不起作用”并没有告诉我们任何事情。向我们展示您的尝试,并详细解释您所做的每一次尝试都发生了什么。
-
问题是他们说我不能使用 WMI 获得远程服务器的控制台日志,这让我对选择 WMI 犹豫不决,因为服务器日志记录是我需要的基本功能实施。你能帮忙吗?
-
请不要在问题标题中包含有关所用语言的信息,除非没有它就没有意义。标记用于此目的。