Java-使用SSH从远程服务器下载文件

作者:聂勇 欢迎转载,请保留作者信息并说明文章来源!

前言

Telnet、FTP、POP3在网络传输的过程中都是采用明文,容易被监听或者遭到到man-in-the-middle的攻击方式攻击。而SSH为远程登陆会话和其他的网络服务提供安全协议,通过加密数据防止传输过程中信息泄漏。
C/C++可以调用OpenSSH来实现SSH,Java也有相应的开源类库JSch,它是SSH2的一个纯Java实现。

源代码

类SftpDownloader的源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package cn.aofeng;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import cn.aofeng.dto.SftpConnectInfo;
import cn.aofeng.util.ConsoleProgressBar;
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;
import com.jcraft.jsch.SftpProgressMonitor;
/**
* 使用SFTP从远程主机下载文件。
*
* @author 傲风 <aofengblog@163.com>
*/
public class SftpDownloader {
private final static Logger logger = Logger.getLogger(SftpDownloader.class);
/**
* 使用SFTP从远程主机下载文件。
*
* @param connectInfo SFTP连接信息
* @param localPath 本地文件路径
* @param remotePath 远程文件路径
*/
public void download(SftpConnectInfo connectInfo, String localPath, final String remotePath) {
JSch jsch = new JSch();
Session session = null;
ChannelSftp channel = null;
OutputStream outs = null;
try {
session = jsch.getSession(connectInfo.getUsername(), connectInfo.getHost(), connectInfo.getPort());
session.setPassword(connectInfo.getPassword());
Properties props = new Properties();
props.put("StrictHostKeyChecking", "no");
session.setConfig(props);
session.connect(5000); // 毫秒
channel = (ChannelSftp) session.openChannel("sftp");
channel.connect(5000);
outs = new BufferedOutputStream(
new FileOutputStream(
new File(localPath)));
channel.get(remotePath, outs, new SftpProgressMonitor() {
ConsoleProgressBar progress = null;
private long current = 0;
@Override
public void init(int op, String src, String dest, long max) {
progress = new ConsoleProgressBar(0, max, 50);
}
@Override
public void end() {
if (logger.isInfoEnabled()) {
logger.debug( String.format("download file:%s complete", remotePath) );
}
}
@Override
public boolean count(long count) {
current += count;
progress.show(current);
return true;
}
});
} catch (JSchException e) {
logger.error( String.format("connect remote host[%s:%d] occurs error", connectInfo.getHost(), connectInfo.getPort()), e);
} catch (SftpException e) {
logger.error( String.format("get remote file:%s occurs error", remotePath), e);
} catch (FileNotFoundException e) {
logger.error( String.format("can not find local file:%s", localPath), e);
} finally {
IOUtils.closeQuietly(outs);
if (null != channel) {
channel.disconnect();
}
if (null != session) {
session.disconnect();
}
}
}
}

注:进度条ConsoleProgressBar的源代码查看文章”Java-实现在控制终端显示的字符进度条”。

类SftpConnectionInfo的源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package cn.aofeng.dto;
/**
* SFTP连接信息。
*
* @author 傲风 <aofengblog@163.com>
*/
public class SftpConnectInfo {
private String username;
private String password;
private String host;
private int port;
public SftpConnectInfo() {
}
public SftpConnectInfo(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@Override
public String toString() {
return "SftpConnectInfo [username=" + username + ", password="
+ password + ", host=" + host + ", port=" + port + "]";
}
}

效果

下面是使用SftpDownloader从多台服务器下载文件的程序执行输出的日志(有进度条的体验还不错):
下载文件效果