我正在尝试使用JSch库通过sftp协议读取文件:
final JSch jsch = new JSch();
this.session = jsch.getSession("me","myserver.com",22);
session.setPassword("redacted");
//this is just a test, so I don't care about security
Properties props = new Properties();
props.put("StrictHostKeyChecking", "no");
session.setConfig(props);
session.connect();
final ChannelSftp channel = (ChannelSftp)session.openChannel("sftp");
InputStream is = channel.get("/home/me/totallyexistingfile.txt";
问题是我在代码的最后一行得到以下异常:
Exception in thread "main" java.io.IOException: Cannot read remote file
at com.teamead.ino.datauser.logproc.source.SSHLogSource.getStream(SSHLogSource.java:51)
at com.teamead.ino.datauser.logproc.processing.LogProc.main(LogProc.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: 4:
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:1513)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:1266)
at com.teamead.ino.datauser.logproc.source.SSHLogSource.getStream(SSHLogSource.java:48)
... 6 more
Caused by: java.lang.NullPointerException
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:1287)
... 8 more
我做了一些谷歌搜索,发现这个错误可能来自sftp服务器,通常发生在上传(空间不足等)。所以我已经设置了sftp服务器(DEBUG级别)的日志记录,只看到了这个:
Oct 21 16:41:14 me sshd[365]: Accepted password for me from 192.211.54.146 port 59458 ssh2
没有别的。我不知道我还能调查什么,因为我得到了来自双方的所有相关日志:( 远程机器是OpenSSH的Debian。
答案 0 :(得分:2)
原来我只缺少channel.connect()