2016-07-20 66 views
2

我有一個停止並啓動Windows服務的Java應用程序。我有一個要求,它應該能夠在遠程機器上這樣做。當前的代碼我有啓動Windows服務遠程看起來如下:運行這個時,我得到以下錯誤如何在遠程計算機上停止並啓動java中的Windows服務

public void executeCommand() { 

    String[] command = {"cmd.exe", "/c", "sc", "\\\\192.168.1.27", "start", "btwdins"}; 
    try { 
     Process process = new ProcessBuilder(command).start(); 
     InputStream inputStream = process.getInputStream(); 
     InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
     BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
     String line; 
     while ((line = bufferedReader.readLine()) != null) { 
      System.out.println(line); 
     } 
    } catch (Exception ex) { 
     System.out.println("Exception : " + ex); 
    } 
} 

但是:

[SC] OpenSCManager FAILED 5: 

Access is denied. 

請注意以下事項:

  • 本地和遠程機器都運行在Windows 10上

  • 遠程機器有它的防火牆禁用

  • RPC(遠程過程調用)被遠程計算機

  • 文件和打印機共享已開啓遠程機器上

我在想什麼上運行?任何幫助將不勝感激。

+0

你可以嘗試加入執行'sc.exe'機器進入本地'Administrators'組在遠程機器上(如何做到這一點在很大程度上取決於你正在使用的Windows版本,所以添加到這個問題可能會幫助彈出進一步的答案)。 –

回答

0

您可以嘗試從網上下載PsExec.exe,然後輸入以下代碼。

公共類RemoteConnection {

static String psCommandStart = null; 
static String psCommandStop = null; 
public static void main(String[] args) { 
     String currentServerHostname="192.168.0.1"; 
     String currentServerUser="Administrator"; 
     String currentServerPass="admin"; 
     String commandToStart="net start ServiceName"; 
     String commandToStop="net stop ServiceName"; 
     String psCommand = "D://Workspace //PsExec.exe \\\\"+ currentServerHostname + " -u " + currentServerUser + " -p " + currentServerPass; 
     psCommandStart = psCommand + " " + commandToStart; 
     psCommandStop = psCommand + " " + commandToStop; 
     ServiceStart(); 
     ServiceStop();  

} 

private static void ServiceStop() { 
    String[] cmd = new String[5]; 
     cmd[0]="cmd.exe"; 
     cmd[1]="/C"; 
     cmd[2]=psCommandStop; 
     cmd[3]=""; 
     cmd[4]=""; 
     // Run remote command 
     File f = new File(getCurrentWorkingDirectory() + "\\lib"); 
     try 
     { 
     Process run = Runtime.getRuntime().exec(cmd,null,f); 

     } 
     catch (IOException e) 
     { 
     e.printStackTrace(); 
     } 


} 

private static void ServiceStart() { 
    String[] cmd = new String[5]; 
     cmd[0]="cmd.exe"; 
     cmd[1]="/C"; 
     cmd[2]=psCommandStart; 
     cmd[3]=""; 
     cmd[4]=""; 
     // Run remote command 
     File f = new File(getCurrentWorkingDirectory() + "\\lib"); 
     try 
     { 
     Process run = Runtime.getRuntime().exec(cmd,null,f); 
     } 
     catch (IOException e) 
     { 
     e.printStackTrace(); 
     } 


} 

private static String getCurrentWorkingDirectory() { 
    String currentDir = System.getProperty("user.dir"); 
    return currentDir; 
} 

}

相關問題