使用JSch在powershell上执行脚本

时间:2018-01-09 12:34:25

标签: java powershell ssh jsch

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

上安装了Win32-OpenSSH

当我使用" exec"它运行powershell并将其关闭,因此我无法在powershell中运行命令。另一方面,如果我运行" shell" channel我从命令提示符输出,例如" 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;
}

0 个答案:

没有答案