2017-12-13 6 views
0

원격 Windows 컴퓨터에서 Java를 사용하여 PowerShell 명령을 실행하고 싶습니다. 실제로는 인바운드 방화벽 포트를 여는 것입니다. script.ps1는 아래의 명령을Java를 사용하여 원격으로 PowerShell 명령을 실행하십시오.

PowerShell을 cmd를 포함 : - 규칙 이름 = "열기 포트 (8077)"DIR = 행동 = 있도록 프로토콜 = TCP의 localport = (8077)를 추가 방화벽 은 netsh advfirewall

enter image description here

아래의 코드는 로컬에서 잘 작동합니다. 하지만 로컬 컴퓨터에서만 원격 컴퓨터에서 동일한 작업을 수행하기를 원하며 수동으로 수행 할 수 없습니다 (PS1 파일을 만들지 않아도 가능). 원격 컴퓨터에 관리자 권한이 있습니다.
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 

public class TestMain2 { 

    public static void main(String[] args) throws IOException { 
     String command = "powershell.exe \"C:\\Users\\Administrator\\Desktop\\agent_port\\script.ps1\""; 

     // Executing the command 
     Process powerShellProcess = Runtime.getRuntime().exec(command); 
     // Getting the results 
     powerShellProcess.getOutputStream().close(); 
     String line; 
     System.out.println("Standard Output:"); 
     BufferedReader stdout = new BufferedReader(new InputStreamReader(powerShellProcess.getInputStream())); 
     while ((line = stdout.readLine()) != null) { 
      System.out.println(line); 
     } 
     stdout.close(); 
     System.out.println("Standard Error:"); 
     BufferedReader stderr = new BufferedReader(new InputStreamReader(powerShellProcess.getErrorStream())); 
     while ((line = stderr.readLine()) != null) { 
      System.out.println(line); 
     } 
     stderr.close(); 
     System.out.println("Done"); 

    } 
} 

은 또한이 링크를 시도 : - Running Powershell script remotely through Java

+0

복잡한 레이어를 추가해야하는 이유는 무엇입니까? PowerShell은 기본적으로'invoke-command '(및 다른 메소드)를 통해 원격 실행을 처리합니다. 이것을 Java로 랩핑하는 것은 단지 문제를 요구하는 것입니다. 어떻게하면 원격 컴퓨터에 대한 관리자 권한이 있지만 "그곳에서 아무 것도 할 수 없습니까?" – alroc

+1

링크 예에서 원격 서비스에서 winrm 서비스를 활성화해야합니다. 기본적으로 Azure Windows VM은 winrm 서비스를 활성화하지 않습니다. –

+0

@alroc 예, 자바 코드만으로해야하기 때문에 수동으로 할 수 없습니다. 우리는 비즈니스 요구 사항이 있으므로 그리고 아래의 invoke 명령도 시도했지만 5986 포트는 기본적으로 열리지 않습니다. - ** invoke-command -ComputerName "192.168.0.0"-filepath "C : \ Users \ Administrator \ Desktop \ agent_port \ script. ps1 "-credential"password "** – Ankit4mjis

답변

1

귀하의 링크 예를 들어 요구가 원격 VM에 WinRM이 서비스로서 수 있습니다. 기본적으로 Azure Windows VM은 winrm 서비스를 허용하지 않습니다. 따라서 예제를 사용할 수 없습니다.

Azure VM의 경우 Azure Custom Script Extension을 사용하면됩니다.

example을 사용할 수 있습니다. 다음 코드를 추가하십시오.

 //Add Azure Custom Script Extension 
     windowsVM.update() 
      .defineNewExtension("shuitest") 
      .withPublisher("Microsoft.Compute") 
      .withType("CustomScriptExtension") 
      .withVersion("1.9") 
      .withMinorVersionAutoUpgrade() 
      .withPublicSetting("commandToExecute", "netsh advfirewall firewall add rule name=\"Open Port 8077\" dir=in action=allow protocol=TCP localport=8077") 
      .attach() 
     .apply(); 
+0

감사합니다! 이제 제 일이 끝났습니다. – Ankit4mjis

관련 문제