2011-06-28 17 views
3

我需要在遠程計算機上執行程序,所以我創建了一個服務以便調用psexec(這對使用該服務非常重要)。但是,此服務無法調用psexec。使用C#中的服務執行psexec服務#

下面的代碼:

  String cmd = "", arguments = ""; 
      cmd = @"C:\PsTools\psexec.exe"; 

      arguments = @"\\remoteComputer -u "user" -p "password" "C:\program.exe""; 

      Process process = new Process(); 
      process.StartInfo.FileName = cmd; 
      process.StartInfo.Arguments = arguments; 

      process.StartInfo.UseShellExecute = false; 
      process.StartInfo.RedirectStandardOutput = true; 
      process.StartInfo.RedirectStandardError = true; 
      process.StartInfo.CreateNoWindow = true; 
      process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 

      process.Start(); 
      result = process.StandardOutput.ReadToEnd(); 
      sError = process.StandardError.ReadToEnd(); 

      result += "Program has finished its execution"; 

不要任何人知道爲什麼服務不能調用PSEXEC?

+0

你看到什麼錯誤? – Lazarus

+0

psexec只是「掛」的呼叫? –

+0

服務必須以允許訪問此目錄的權限運行。當沒有用戶登錄時,服務也在運行。 – nabuchodonossor

回答

4

我在遠程運行批處理文件時也遇到了psexec掛起的問題。 WMI如何?在遠程計算機上運行某些東西時,這對我有用;它也適用於* .bat和* .exe。您可能需要單擊Project> Add Reference,然後在.NET選項卡上選擇「System.Management」 - 直到手動添加參考時,VS 2010中才提供參考。

 System.Management.ConnectionOptions connOptions = 
      new System.Management.ConnectionOptions(); 

     connOptions.Impersonation = System.Management.ImpersonationLevel.Impersonate; 
     connOptions.EnablePrivileges = true; 

     string compName = "RemoteComputerName"; 
     System.Management.ManagementScope manScope = 
      new System.Management.ManagementScope(
       String.Format(@"\\{0}\ROOT\CIMV2", compName), connOptions); 
     manScope.Connect(); 

     System.Management.ObjectGetOptions objectGetOptions = 
      new System.Management.ObjectGetOptions(); 

     System.Management.ManagementPath managementPath = 
      new System.Management.ManagementPath("Win32_Process"); 

     System.Management.ManagementClass processClass = 
      new System.Management.ManagementClass(manScope, managementPath, objectGetOptions); 

     System.Management.ManagementBaseObject inParams = 
      processClass.GetMethodParameters("Create"); 

     inParams["CommandLine"] = @"c:\MyBatchFile.bat"; 

     System.Management.ManagementBaseObject outParams = 
      processClass.InvokeMethod("Create", inParams, null); 
1

你必須運行psexecAdministrator權限到遠程計算機的用戶。 (所有-u選項的作用是更改用於在遠程計算機上執行命令的帳戶。)要麼將服務配置爲對遠程計算機具有權限的帳戶運行,要麼使用第二個實例psexec運行第一個實例psexec作爲適當的用戶。