簡體   English   中英

使用java通過遠程服務器執行powershell命令

[英]execute powershell command through remote server with java

我創建了一個允許我執行命令的函數。
第一個命令,由於setcommand執行是“powershell”運行良好,我得到了shell的返回:
“Windows PowerShell版權所有(C)2009 Microsoft Corporation.Tous droits r ,serv ,s。”
我的問題是在powershell運行out.write函數后運行命令。

//The command is equal to "powershell" and run powershell correctly
private static void executeCommand(String command) {
    try {
    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);

     OutputStream out = channel.getOutputStream();
     InputStream in = channel.getInputStream();

    channel.connect();
    out.write(("mkdir C:\\test" + "\n").getBytes());
    out.flush();

    byte[] tmp = new byte[1024];
    while (channel.getExitStatus() == -1) {
        while (in.available() > 0) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0)
                break;
            System.out.print(new String(tmp, 0, i));
        }
        if (channel.isClosed()) {
            System.out.println("exit-status: " + channel.getExitStatus());
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception ee) {
            System.out.println(ee);
        }
    }
    channel.disconnect();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSchException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

你有什么解決方案來解決我的問題或任何其他方式來完成這項工作嗎?

編輯:

    Process p;

    try {

        p = new ProcessBuilder()
        .inheritIO()
        .command("powershell", "$user='root'; $pass='test'; $passwd=ConvertTo-SecureString -AsPlainText $pass -Force; $cred=New-Object System.Management.Automation.PSCredential -ArgumentList $user, $passwd; Invoke-command -ComputerName 10.64.2.35 -ScriptBlock {Get-ChildItem C:\\} -credential $cred").start();
        p.waitFor();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

為什么不使用pocessbuilder api?

示例代碼 - 相應地更新您的代碼。

 Process p = new ProcessBuilder()
            .inheritIO()
            .command("invoke-command", "-remoteServername", "ServerXYZ",
                    "-filepath", "C:\\scripts\\script.ps1").start();
    p.waitFor();

暫無
暫無

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

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