簡體   English   中英

通過 Java 遠程 Powershell 腳本

[英]Remote Powershell scripts via Java

您是否知道一些用於 Java 調用遠程 PowerShell 腳本的 API?

從這個 API 我需要這樣的東西:

  • 登錄到 Windows 機器。
  • 執行 PowerShell 腳本
  • 獲取腳本執行結果

還是存在另一種方法來做到這一點? 謝謝

您可以使用 JPowerShell 庫: https : //github.com/profesorfalken/jPowerShell

PowerShell powerShell = null;
try {
    //Creates PowerShell session
    PowerShell powerShell = PowerShell.openSession();
    //Increase timeout to give enough time to the script to finish
    Map<String, String> config = new HashMap<String, String>();
    config.put("maxWait", "80000");

    //Execute script
    PowerShellResponse response = powerShell.configuration(config).executeScript("./myPath/MyScript.ps1");

    //Print results if the script
    System.out.println("Script output:" + response.getCommandOutput());
} catch(PowerShellNotAvailableException ex) {
    //Handle error when PowerShell is not available in the system
    //Maybe try in another way?
} finally {
    //Always close PowerShell session to free resources.
    if (powerShell != null)
        powerShell.close();
}

如果您想通過 Java 遠程執行某些操作,那么考慮RMI是一件好事。 我不知道您是否想保留登錄名(是否需要使用不同的用戶?),但是如果您更改 Windows 密碼等,此方法將繼續有效。也有一些方法可以確保它的安全(但在家庭環境中)沒那么必要)。 我推薦使用的 shell 調用是Apache Commons Exec (ExecuteWatchdog)來構建一個強大的解決方案。

長話短說:你可以通過這個繞過登錄並保持某種便攜的解決方案。

使用 winrm4j: https : //github.com/cloudsoft/winrm4j

winrm4j 是一個項目,它使 Java 應用程序能夠使用 WinRM 在遠程 Windows 服務器上執行批處理或 PowerShell 命令

WinRmClientContext context = WinRmClientContext.newInstance();

WinRmTool tool = WinRmTool.Builder.builder("my.windows.server.com", "Administrator", "pa55w0rd!")
    .authenticationScheme(AuthSchemes.NTLM)
    .port(5985)
    .useHttps(false)
    .context(context)
    .build();

tool.executePs("echo hi");

context.shutdown();

您可以嘗試 ProcessBuilder 並重定向輸出流,如下所示:

javac 1.8.0_60編譯並運行: java 版本“1.8.0_91”

import java.util.*;
import java.io.*;
public class Test {
    public static void main(String ... args) {
        try {
            ProcessBuilder launcher = new ProcessBuilder();
            Map<String, String> environment = launcher.environment();
            launcher.redirectErrorStream(true);
            launcher.directory(new File("\\\\remote_machine\\Snaps\\"));
            launcher.command("powershell.exe", ".\\Script.ps1");
            Process p = launcher.start(); // And launch a new process
            BufferedReader stdInput = new BufferedReader(new
            InputStreamReader(p.getInputStream()));
            String line;
            System.out.println("Output :");
            while ((line = stdInput.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e){
           e.printStackTrace();
        }
    }
}

我的Script.ps1是一個用於測試的文件,它是打印到輸出流的簡單文件:

Write-Host 'Hello World!'

你好,我沒有專門用 PowerShell 嘗試過這個,但我已經用批處理文件和 Windows Shell 主機嘗試過。 使用 RMI 的替代方法是使用 Windows 提供的遠程處理功能 DCOM。 這樣你就不需要在 Windows 機器上部署額外的遠程服務。 相反,您可以使用每個 Windows 機器提供的 DCOM 服務器。 Windows 機器公開了一種叫做 Windows Shell 主機的東西。 此 Windows Shell 主機可用於遠程執行腳本。 由於 Windows 中的幾乎所有東西都以 COM 對象的形式出現,我的期望是 Powershell 也以注冊的 COM 服務的形式出現,您只需找出它即可。

在此鏈接中,您將找到使用 Windows Shell Host 和 J-interop 作為 DCOM 協議的 Java 實現的問題的解決方案: 如何使用 jinterop 調用遠程 bat 文件

/ Create a session
JISession session = JISession.createSession(<domain>, <user>, <password>);
session.useSessionSecurity(true);

// Execute command
JIComServer comStub = new JIComServer(JIProgId.valueOf("WScript.Shell"),<IP>, session);
IJIComObject unknown = comStub.createInstance();
final IJIDispatch shell =     (IJIDispatch)JIObjectFactory.narrowObject((IJIComObject)unknown.queryInterface(IJIDispatch.I ID));
JIVariant results[] = shell.callMethodA("Exec", new Object[]{new JIString("%comspec% /c asadmin.bat" )});

如果您需要批處理的輸出,您可以使用 StdOut 來讀取它。

JIVariant stdOutJIVariant = wbemObjectSet_dispatch.get("StdOut"); 
IJIDispatch stdOut =  (IJIDispatch)JIObjectFactory.narrowObject(stdOutJIVariant.getObjectAsComObject());

// Read all from stdOut
while(!((JIVariant)stdOut.get("AtEndOfStream")).getObjectAsBoolean()){ 
    System.out.println(stdOut.callMethodA("ReadAll").getObjectAsString().getString()); 
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM