首页 > 解决方案 > Jsch ChannelExec:如何在命令后将密码传递给服务器?

问题描述

我想使用我的 java 应用程序 Jsch 和 ChannelExec 中的“scp”命令。命令没问题,但我如何传递我的密码?

直接在服务器上它会像这样:

$ scp user@server:/myPath/* .
$ user@server's password:
(informations on files copied)

命令和密码在 2 个单独的行上。

为了在java中重新创建它,我这样做了:

ChannelExec channelExec = (ChannelExec) session.openChannel("exec"); //$NON-NLS-1$
channelExec.setCommand(scpCommand);
channelExec.connect();
try (OutputStream outputStream = channelExec.getOutputStream()) {
    pause(5000);
    outputStream.write((password + "\n").getBytes()); //$NON-NLS-1$
    outputStream.flush();
}

(read result and terminate session)

但是你可以猜到它是行不通的。

你有关于如何解决这个问题的线索吗?我应该在命令中传递密码,用特殊字符分隔吗?('\n' 也许我不知道) 还是有其他解决方案?

谢谢你的时间 !

标签: javasshjsch

解决方案


在连接之前,使用下面的代码行。

channelExec.setPty(true);

有关更多详细信息,请参阅下面的文档。 https://epaul.github.io/jsch-documentation/simple.javadoc/com/jcraft/jsch/ChannelExec.html#setPtyType-java.lang.String-


推荐阅读