我试图使用Java使用SFTP(而不是FTPS)从服务器检索一个文件。我该怎么做呢?
当前回答
我发现完整的工作示例SFTP在java使用JSCH API http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/
其他回答
有3个成熟的用于SFTP的Java库:Commons VFS、SSHJ和JSch
总而言之,如果你不需要Commons VFS提供的其他存储支持,那么SSHJ具有最清晰的API,是其中最好的API。
下面是从github编辑的SSHJ示例:
final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts(); // or, to skip host verification: ssh.addHostKeyVerifier(new PromiscuousVerifier())
ssh.connect("localhost");
try {
ssh.authPassword("user", "password"); // or ssh.authPublickey(System.getProperty("user.name"))
final SFTPClient sftp = ssh.newSFTPClient();
try {
sftp.get("test_file", "/tmp/test.tmp");
} finally {
sftp.close();
}
} finally {
ssh.disconnect();
}
虽然上面的答案很有帮助,但我花了一天时间让它们工作,面对各种异常,如“中断通道”,“rsa密钥未知”和“数据包损坏”。
下面是一个工作的可重用类SFTP文件上传/下载使用JSch库。
上传用法:
SFTPFileCopy upload = new SFTPFileCopy(true, /path/to/sourcefile.png", /path/to/destinationfile.png");
下载使用:
SFTPFileCopy download = new SFTPFileCopy(false, "/path/to/sourcefile.png", "/path/to/destinationfile.png");
类代码:
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JOptionPane;
import menue.Menue;
public class SFTPFileCopy1 {
public SFTPFileCopy1(boolean upload, String sourcePath, String destPath) throws FileNotFoundException, IOException {
Session session = null;
Channel channel = null;
ChannelSftp sftpChannel = null;
try {
JSch jsch = new JSch();
//jsch.setKnownHosts("/home/user/.putty/sshhostkeys");
session = jsch.getSession("login", "mysite.com", 22);
session.setPassword("password");
UserInfo ui = new MyUserInfo() {
public void showMessage(String message) {
JOptionPane.showMessageDialog(null, message);
}
public boolean promptYesNo(String message) {
Object[] options = {"yes", "no"};
int foo = JOptionPane.showOptionDialog(null,
message,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo == 0;
}
};
session.setUserInfo(ui);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
sftpChannel = (ChannelSftp) channel;
if (upload) { // File upload.
byte[] bufr = new byte[(int) new File(sourcePath).length()];
FileInputStream fis = new FileInputStream(new File(sourcePath));
fis.read(bufr);
ByteArrayInputStream fileStream = new ByteArrayInputStream(bufr);
sftpChannel.put(fileStream, destPath);
fileStream.close();
} else { // File download.
byte[] buffer = new byte[1024];
BufferedInputStream bis = new BufferedInputStream(sftpChannel.get(sourcePath));
OutputStream os = new FileOutputStream(new File(destPath));
BufferedOutputStream bos = new BufferedOutputStream(os);
int readCount;
while ((readCount = bis.read(buffer)) > 0) {
bos.write(buffer, 0, readCount);
}
bis.close();
bos.close();
}
} catch (Exception e) {
System.out.println(e);
} finally {
if (sftpChannel != null) {
sftpChannel.exit();
}
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
public static abstract class MyUserInfo
implements UserInfo, UIKeyboardInteractive {
public String getPassword() {
return null;
}
public boolean promptYesNo(String str) {
return false;
}
public String getPassphrase() {
return null;
}
public boolean promptPassphrase(String message) {
return false;
}
public boolean promptPassword(String message) {
return false;
}
public void showMessage(String message) {
}
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo) {
return null;
}
}
}
这就是我想到的解决办法 http://sourceforge.net/projects/sshtools/(为了清晰起见,省略了大多数错误处理)。这是我博客的节选
SshClient ssh = new SshClient();
ssh.connect(host, port);
//Authenticate
PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
passwordAuthenticationClient.setUsername(userName);
passwordAuthenticationClient.setPassword(password);
int result = ssh.authenticate(passwordAuthenticationClient);
if(result != AuthenticationProtocolState.COMPLETE){
throw new SFTPException("Login to " + host + ":" + port + " " + userName + "/" + password + " failed");
}
//Open the SFTP channel
SftpClient client = ssh.openSftpClient();
//Send the file
client.put(filePath);
//disconnect
client.quit();
ssh.disconnect();
hierynomus/sshj有一个完整的SFTP版本3的实现(OpenSSH实现的)
来自SFTPUpload.java的示例代码
package net.schmizz.sshj.examples;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.xfer.FileSystemFile;
import java.io.File;
import java.io.IOException;
/** This example demonstrates uploading of a file over SFTP to the SSH server. */
public class SFTPUpload {
public static void main(String[] args)
throws IOException {
final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts();
ssh.connect("localhost");
try {
ssh.authPublickey(System.getProperty("user.name"));
final String src = System.getProperty("user.home") + File.separator + "test_file";
final SFTPClient sftp = ssh.newSFTPClient();
try {
sftp.put(new FileSystemFile(src), "/tmp");
} finally {
sftp.close();
}
} finally {
ssh.disconnect();
}
}
}
我发现完整的工作示例SFTP在java使用JSCH API http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/
推荐文章
- JavaBean和POJO之间的区别是什么?
- 注释在Java中如何使用,在哪里使用?
- 如何在Ubuntu下安装JDK 11 ?
- Spring Boot -无法确定数据库类型为NONE的嵌入式数据库驱动程序类
- 如何转换/解析从字符串到字符在java?
- 如何在Android中动态更改菜单项文本
- 如何比较两个没有时间部分的日期?
- 如何在Java中找到给定类的所有子类?
- 匿名类的访问构造函数
- 从Java访问Kotlin扩展函数
- 解析LocalDateTime时无法从TemporalAccessor获取LocalDateTime (Java 8)
- 以AM/PM的12小时格式显示当前时间
- 求两个集合的差值
- Junit @Rule如何工作?
- SSL握手警告:unrecognized_name错误,因为升级到Java 1.7.0