有些网络环境中,考虑利用更为安全的文件传输协议:sftp
这里顺带整理一个之前编写的sftp的访问工具类:
package com.huaxia.alarm.utils;
import org.apache.log4j.Logger;
import com.huaxia.alarm.beans.FTPConfig;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
/**
*
* @author xum
*
* sftp工具类
*/
public class SFTPUtil {
private static final Logger logger = Logger.getLogger(SFTPUtil.class);
public static final String SFTP_CHANNEL_TYPE = "sftp";
public static ChannelSftp getSftpConnection(final FTPConfig ftpConfig) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
Session sshSession = jsch.getSession(ftpConfig.getFtpUserName(),
ftpConfig.getFtpHost(), ftpConfig.getFtpPort());
logger.info("SFTP Session created.");
sshSession.setPassword(ftpConfig.getFtpPassword());
// Properties sshConfig = new Properties();
// sshConfig.put("StrictHostKeyChecking", "no");
// sshSession.setConfig(sshConfig);
sshSession.setUserInfo(new com.jcraft.jsch.UserInfo() {
public String getPassphrase() {
return null;
}
public String getPassword() {
return ftpConfig.getFtpPassword();
}
public boolean promptPassphrase(String pArg0) {
return true;
}
public boolean promptPassword(String pArg0) {
return true;
}
public boolean promptYesNo(String pArg0) {
return true;
}
public void showMessage(String pArg0) {
}
});
sshSession.setTimeout(60000);// 连接的Timeout时间
sshSession.connect();
Channel channel = sshSession.openChannel(SFTP_CHANNEL_TYPE);
channel.connect();
logger.info("Opening Channel...");
sftp = (ChannelSftp) channel;
logger.info("Connected to server [" + ftpConfig.getFtpHost()
+ "] success.");
return sftp;
} catch (Exception e) {
logger.error("Connected to server [" + ftpConfig.getFtpHost()
+ "] fail, ", e);
return null;
}
}
public static void closeChannelSftp(ChannelSftp sftp) {
if (null != sftp) {
if (sftp.isConnected()) {
sftp.disconnect();
logger.info("ChannelSftp [sftp] disconnect success.");
}
}
}
}
用到的第三方jar为:
jsch-0.1.49.jar
工具类中只提供了连接和断开连接的方法,至于cd修改当前目录,list等命令,返回的ChannelSftp类中都有对应的方法可供调用。