2013-04-10 15 views
5

remote server name(windows)、usernameおよびpasswordです。 C#.NETを使用してWindowsリモートサーバーでコマンドを実行し、C#.NETでコンソール出力を取得します。

、私はC#でそれを行う方法があり、リモートサーバー上のrun a commandにしたいとconsole output

を取り戻しますか?

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

いずれかのアイデアはありますか?

+0

私は、telnetセッションを介してコマンドを呼び出すと考えています...多くのセキュリティ専門家が同意するとは思えませんが、出力をキャプチャするのは比較的簡単です。 – dotcomslashnet

+0

コンソール出力をテキストファイルにリダイレクトして、ファイルを何とか元に戻すことはできますか? –

+0

@dotcomslashnetその行をチェックします。 – BlackCursor

答えて

4

この機能は、いくつかの研究の後に思いついたものです。他の人に役立つことを願っています。

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; 
    } 
} 
1

PsToolsでコマンドを実行できます。彼らが提供する多くの機能の1つはPsExecです。これにより、リモートサーバー上でコマンドを実行できます。また、結果をコンソール(実行元のローカルPC)に戻す必要があります。

+0

ありがとうございます。私は正常に 'PsExec'を使ってリモートサーバに接続し、コマンドを実行し、コンソール出力を文字列として取得しました。別の答えとしてコードを追加しているので、他の人に役立つかもしれません。再度、感謝します! – BlackCursor