使用 java 通过远程服务器执行 powershell 命令

execute powershell command through remote server with java

我创建了一个允许我执行命令的函数。
由于 setcommand 执行的第一个命令是 "powershell" 运行良好,我得到 shell 的 return :
“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();
    }

为什么不用pocessbuilderapi?

示例代码 - 相应地更新您的代码。

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