最近我们的客户意外地将我们从ftp收集的一些重要文件转移到了sftp服务器.最初我的印象是编写或找到一个可以处理sftp的java实用程序很简单,但事实证明并非如此.还有一个问题是我们正在尝试从Windows平台连接到sftp服务器(因此SSH_HOME在客户端上的定义非常混乱).
我一直在使用apache-commons-vfs库,并设法获得一个可靠地用于用户名/密码认证的解决方案,但至今还没有任何可以可靠地处理私钥/公钥认证的解决方案.
以下示例适用于用户名/密码身份验证,但我想调整它以进行私钥/公钥身份验证.
public static void sftpGetFile(String server, String userName,String password,
String remoteDir, String localDir, String fileNameRegex)
{
File localDirFile = new File(localDir);
FileSystemManager fsManager = null;
if (!localDirFile.exists()) {
localDirFile.mkdirs();
}
try {
fsManager = VFS.getManager();
} catch (FileSystemException ex) {
LOGGER.error("Failed to get fsManager from VFS",ex);
throw new RuntimeException("Failed to get fsManager from VFS", ex);
}
UserAuthenticator auth = new StaticUserAuthenticator(null, userName,password);
FileSystemOptions opts = new FileSystemOptions();
try {
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts,
auth);
} catch (FileSystemException ex) {
LOGGER.error("setUserAuthenticator failed", …Run Code Online (Sandbox Code Playgroud)