我正在寻找一个用于SFTP文件传输的简单Java库.除此之外,我不需要任何其他功能.
我已经尝试过Zehon了,但这是令人难以置信的唠叨,我认为8个jar文件对我所需要的功能来说有点疯狂.
图书馆必须是免费的(如免费啤酒),最好是开源(不是要求).
谢谢.
Val*_*her 41
编辑:我将保留我以前的答案,因为JSch仍在许多地方使用,但如果你需要一个更好的文档库,你可以使用sshj.如何使用它来做sftp的一个例子是:
SSHClient ssh = new SSHClient();
ssh.loadKnownHosts();
ssh.connect("host");
try {
ssh.authPassword("username", "password");
SFTPClient sftp = ssh.newSFTPClient();
try {
sftp.put(new FileSystemFile("/path/of/local/file"), "/path/of/ftp/file");
} finally {
sftp.close();
}
} finally {
ssh.disconnect();
}
Run Code Online (Sandbox Code Playgroud)
使用JSch(例如Ant使用的java ssh lib),您可以执行以下操作:
Session session = null;
Channel channel = null;
try {
JSch ssh = new JSch();
ssh.setKnownHosts("/path/of/known_hosts/file");
session = ssh.getSession("username", "host", 22);
session.setPassword("password");
session.connect();
channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
sftp.put("/path/of/local/file", "/path/of/ftp/file");
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
Run Code Online (Sandbox Code Playgroud)
这是使用JSch进行SFTP的另一个链接.
你可以通过这种方式直接使用JSch,或者通过Commons VFS,但是你必须拥有公共vfs jar和jsch jar.
以下是使用JSch的示例的完整源代码,无需担心ssh密钥检查.
import com.jcraft.jsch.*;
public class TestJSch {
public static void main(String args[]) {
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("username", "127.0.0.1", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("password");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.get("remotefile.txt", "localfile.txt");
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (SftpException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
64820 次 |
最近记录: |