使用 JSch 在 powershell 上执行脚本

Ank*_*ain 5 java ssh powershell jsch

我想执行 powershell,然后在远程 Windows 系统上执行一些命令,我​​正在使用 JSCH ( http://www.jcraft.com/jsch/ )。我在 Windows 机器上有 Win32-OpenSSH https://github.com/PowerShell/Win32-OpenSSH

当我使用“exec”通道时,它会运行 powershell 并将其关闭,因此我无法在 powershell 中运行命令。另一方面,如果我运行“shell”通道,我会从命令提示符处获得输出,例如“Microsoft Windows [Version 10.0.14393] (c) 2016 Microsoft Corporation。保留所有权利。”所以我想执行 powershell 并获得powershell 进程的流,因此我可以将脚本写入该流并读取输出。我通过查看示例获得的流是 SSH 连接的流,其中运行 powershell 本身,而不是 powershell 内部/的流。

我正在使用以下代码在 powershell 中执行命令

private Streams executePowershell(Session session, String command) throws JSchException, IOException {
    Channel channel = session.openChannel("exec");

    ((ChannelExec) channel).setCommand(command);
    ((ChannelExec) channel).setErrStream(System.err);

    //4. Getting response as a stream

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

    System.out.println(out);

    Streams streams = new Streams();
    streams.setInputStream(in);
    streams.setOutputStream(out);
    streams.setChannel(channel);
    return streams;
}
//command will be powershell to invoke the powershell itself
//command2 will be something such as dir that is the command to execute within powershell
public String executeCommand(String command, String command2) {
    String output = null;
    try {
        Session session = getSession();

        Streams streams = null;

        streams = executePowershell(session, command);

        OutputStream outputStream = streams.getOutputStream();
        Util.writeToStream(outputStream, command2);

        output = Util.readStream(streams.getInputStream()).toString();

        streams.getChannel().disconnect();
        session.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return output;
}
Run Code Online (Sandbox Code Playgroud)