I need to execute following command:
scp -r ~/dataIn [email protected]:~/dataOut
In Ubuntu (16.04) terminal this command work correctly. [email protected] 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 [email protected]:~/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 [email protected]:~/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?
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?