UserInfo ui = new SshUser();
session.setUserInfo(ui);
session.connect();
String command = "scp -p -t " + targetFileName;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
if (checkAck(in) != 0) {
throw new RuntimeException("Failed to scp key file");
}
// send "C0644 filesize filename", where filename should not include
// '/'
long filesize = (new File(sourcePath)).length();
command = "C0644 " + filesize + " ";
if (sourcePath.lastIndexOf('/') > 0) {
command += sourcePath.substring(sourcePath.lastIndexOf('/') + 1);
} else {
command += sourcePath;
}
command += "\n";
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
// this actually will never happend since checkAck already
// throws an exception now.
throw new RuntimeException("Fatal Error scp key file");
}
// send a content of lfile
FileInputStream fis = new FileInputStream(sourcePath);
byte[] buf = new byte[1024];
while (true) {
int len = fis.read(buf, 0, buf.length);
if (len <= 0)
break;
out.write(buf, 0, len); // out.flush();
}
fis.close();
fis = null;
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
if (checkAck(in) != 0) {
throw new RuntimeException("Failed to scp file");
}
out.close();
channel.disconnect();
session.disconnect();
} catch (JSchException e) {
throw new IOException("Unable to copy key file to host: ", e);
}
}