我想(或者更确切地说)我必须使用JSch使用SCP将循环文件复制到远程主机。 我是这样做的:
public long writeFiles (Map<String, byte[]> files) {
long count = 0;
try {
Channel channel = session.openChannel("exec");
count = files.entrySet().stream().filter( k -> k.getKey() != null ).peek((k) -> {
String command =
getProperty("scp.bin.path") + "scp -t " + getProperty("scp.target.path") +
"/" + k.getKey() + " ";
System.out.println("Sending command: " + command);
((ChannelExec) channel).setCommand(command);
try {
channel.connect();
System.out.println("Connected to channel to E@syMail Server " +
getProperty("scp.host.ip"));
command = "C0644 " + k.getValue().length + " " + k.getKey() + "\n";
System.out.println("Sending C644 command: " + command);
((ChannelExec) channel).setCommand(command);
final OutputStream out = channel.getOutputStream();
out.write(command.getBytes());
out.flush();
out.write(k.getValue());
out.flush();
out.write(new byte[]{0}, 0, 1);
out.flush();
out.close();
} catch (IOException ex) {
logger.error(ex.toString());
} catch (JSchException e) {
logger.error(e.toString());
}
System.out.println("File written to " + getProperty("scp.host.ip") + ":" +
getProperty("scp.target.path") + "/" + k.getKey());
((ChannelExec) channel).setCommand("chmod " + getProperty("scp.chmod") + "-R " +
k.getKey());
channel.disconnect();
}).count();
session.disconnect();
} catch (JSchException e) {
logger.error(e.toString());
}
final MessageFormat mf = new MessageFormat(getProperty("msg.scp.done") + "\n");
logger.info(mf.format(new Object[]{Long.valueOf(count),
getProperty("scp.host.ip"),
getProperty("scp.target.path")}));
return count;
}
...但是当我查看目标文件夹时,文件不会复制到那里。 我究竟做错了什么??我以示例JSch ScpTo
为导向编辑1: 在执行SCP命令之前,我尝试以这种方式远程 ls :
BufferedReader in=new BufferedReader(new InputStreamReader(channel.getInputStream()));
((ChannelExec) channel).setCommand("ls -lisa;");
channel.connect();
String msg=null;
while((msg=in.readLine())!=null){
System.out.println(msg);
}
......而且它的工作做得很好!