我在使用jsch库的SFTP通道通过SFTP通道上传文档时遇到异常。我知道它是通过Filezilla / cyberduck中的相同键和详细信息来工作的,而不是java。有人可以指出我在想什么吗?
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class TestSSHUpdloadFile {
public static void main(String[] args) throws Exception {
JSch jsch = new JSch();
String privateKey = "/Users/Documents/SFTP/sftprivate_key";
Session session = null;
try {
jsch.addIdentity(privateKey, "Passphrase");
session = jsch.getSession("User", "sftp.aws.com", 22);
session.setConfig("StrictHostKeyChecking", "no");
//session.setPassword("Passphrase");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.put("/Users/Documents/Temp1.csv", "/mys3bucket/Temp1.csv");
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
}
}
下面是例外
com.jcraft.jsch.JSchException: USERAUTH fail
at com.jcraft.jsch.UserAuthPublicKey.start(UserAuthPublicKey.java:119)
at com.jcraft.jsch.Session.connect(Session.java:470)
at com.jcraft.jsch.Session.connect(Session.java:183)
at TestS3.TestSSHUpdloadFile.main(TestSSHUpdloadFile.java:21)
u必须使用inputStream从服务器获取文件并再次放入就我而言,我使用的是流动代码我没有使用端口号进行身份验证:
private ChannelSftp setupJsch(String host, String username, String password) {
JSch jsch = new JSch();
//jsch.setKnownHosts(knownHosts);
Session jschSession;
try {
jschSession = jsch.getSession(username, host);
jschSession.setPassword(password);
//extra config code
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
jschSession.setConfig(config);
jschSession.connect();
return (ChannelSftp) jschSession.openChannel("sftp");
} catch (JSchException e) {
}
return null;
}
private InputStream getInputStream(String host,
String username, String password,String pdfFromIN) {
InputStream in = null;
ChannelSftp channelSftp;
try {
channelSftp = setupJsch(host, username, password);
channelSftp.connect();
in=channelSftp.get(pdfFromIN);
} catch (JSchException |SftpException e) {
}
//channelSftp.exit();
return in;
}
private void putFile(String host,
String username, String password,InputStream in,String desFileRepo){
ChannelSftp channelSftp;
try {
channelSftp = setupJsch(host, username, password);
channelSftp.connect();
channelSftp.put(in, desFileRepo);
channelSftp.exit();
} catch (JSchException |SftpException e) {
;
}
}