How to pass in the password in scp using Java ssh JSch and jcabi-ssh

佐手、 提交于 2020-03-21 05:02:52

问题


I need to execute following command:

scp -r ~/dataIn yatsuk@192.168.1.1:~/dataOut

In ubuntu (16.04) terminal this command work correctly. yatsuk@192.168.1.1 is localhost.

So I try this code using jcabi:

Shell shell = new SSHByPassword("192.168.1.1", 22, "yatsuk", "passw");
String stdout = new Shell.Plain(shell).exec("scp -r ~/dataIn yatsuk@192.168.1.1:~/dataOut");
System.out.println(stdout);

And this code by JSch:

JSch jsch = new JSch();
JSch.setConfig("StrictHostKeyChecking", "no");
Session session = jsch.getSession("yatsuk", 192.168.1.1, 22);
session.setPassword("passw");
session.connect();

Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand("scp -r ~/dataIn yatsuk@192.168.1.1:~/dataOut");
((ChannelExec) channel).setErrStream(System.err);
channel.setOutputStream(System.out);
channel.setInputStream(System.in);
channel.connect();

while (!channel.isClosed()) {
    Thread.sleep(1000);
}
channel.disconnect();
session.disconnect();

Both return me:

Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,password).
lost connection

Simple commands like "echo 1 > 1.txt" works perfectly. Maybe something I do not understand?


回答1:


Automating an execution of an interactive command is a sign of a bad design. Anyway...


The scp will prompt your for a password in an interactive session/terminal only. For security reasons, it won't read the password from a plain standard input.

So you have to enable an interactive session/terminal.

In JSch, you do that by calling .setPty:

channel.setPty(true);
channel.connect();

Similar question: Use JSch sudo example and Channel.setPty for running sudo command on remote host.


Another approach is using expect or sshpass tools: How to pass password to scp?




回答2:


The problem is that scp is looking for a password in your ~/.ssh and can't find it there. You should provide it again to scp. Something like this: How to pass password to scp?



来源:https://stackoverflow.com/questions/39232333/how-to-pass-in-the-password-in-scp-using-java-ssh-jsch-and-jcabi-ssh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!