1

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?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Andrei Iatsuk
  • 452
  • 6
  • 17

2 Answers2

0

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?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
0

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?

Community
  • 1
  • 1
yegor256
  • 102,010
  • 123
  • 446
  • 597