1、SFTPChannel
import com.jcraft.jsch.*;
import org.jboss.logging.Logger;
import java.util.Map;
import java.util.Properties;
public class SFTPChannel {
Session session = null;
Channel channel = null;
private static final Logger LOG = Logger.getLogger(SFTPChannel.class.getName());
public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout) throws JSchException {
String ftpHost = sftpDetails.get(SFTPConstants.SFTP_REQ_HOST);
String port = sftpDetails.get(SFTPConstants.SFTP_REQ_PORT);
String ftpUserName = sftpDetails.get(SFTPConstants.SFTP_REQ_USERNAME);
String ftpPassword = sftpDetails.get(SFTPConstants.SFTP_REQ_PASSWORD);
int ftpPort = SFTPConstants.SFTP_DEFAULT_PORT;
if (port != null && !port.equals("")) {
ftpPort = Integer.valueOf(port);
}
JSch jsch = new JSch();
session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
LOG.debug("Session created.");
if (ftpPassword != null) {
session.setPassword(ftpPassword);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(timeout);
session.connect();
LOG.debug("Session connected.");
LOG.debug("Opening Channel.");
channel = session.openChannel("sftp");
channel.connect();
LOG.debug("Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = " + ftpUserName
+ ", returning: " + channel);
return (ChannelSftp) channel;
}
public void closeChannel() throws Exception {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
2、SftpClientUtil
import com.jcraft.jsch.*;
import org.jboss.logging.Logger;
import java.io.*;
import java.util.*;
public class SftpClientUtil {
private static Logger logger = Logger.getLogger(SftpClientUtil.class);
private Session session;
private Channel channel;
private ChannelSftp sftp;
private InputStream in;
private OutputStream out;
public SftpClientUtil(String host, String username, String password, int port, boolean isHightSSH) throws Exception {
JSch jsch = new JSch();
this.session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
if (isHightSSH) {
config.put("kex", "diffie-hellman-group1-sha1,"
+ "diffie-hellman-group-exchange-sha1,"
+ "diffie-hellman-group-exchange-sha256");
}
session.setConfig(config);
try {
session.connect();
} catch (Exception e) {
if (session.isConnected())
session.disconnect();
logger.error("链接报错!!!", e);
throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],端口[" + port + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
}
channel = session.openChannel("sftp");
try {
if (channel.isConnected())
channel.disconnect();
channel.connect();
} catch (Exception e) {
throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],端口[" + port + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
}
sftp = (ChannelSftp) channel;
}
public SftpClientUtil(String host, String username, String password, int port, String encoding) throws Exception {
JSch jsch = new JSch();
this.session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
try {
session.connect();
} catch (Exception e) {
if (session.isConnected())
session.disconnect();
throw new Exception("连接服务器失败,请检查主机[" + host + "],端口1[" + port + "],用户名[" + username + "],端口[" + port + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
}
channel = session.openChannel("sftp");
try {
channel.connect();
} catch (Exception e) {
if (channel.isConnected())
channel.disconnect();
throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],密码[" + password + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
}
sftp = (ChannelSftp) channel;
sftp.setFilenameEncoding(encoding);
}
private SftpClientUtil(String host, String username, String password, int port, String encoding, int timeout)
throws Exception {
JSch jsch = new JSch();
this.session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
try {
session.connect();
} catch (Exception e) {
if (session.isConnected())
session.disconnect();
throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],密码[" + password + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
}
session.setTimeout(timeout);
channel = session.openChannel("sftp");
try {
channel.connect();
} catch (Exception e) {
if (channel.isConnected())
channel.disconnect();
throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],密码[" + password + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
}
sftp = (ChannelSftp) channel;
sftp.setFilenameEncoding(encoding);
}
public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
FileInputStream in = null;
try {
createDir(remotePath);
File file = new File(localPath + localFileName);
in = new FileInputStream(file);
sftp.put(in, remoteFileName);
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
public boolean createDir(String createpath) {
try {
createpath = createpath.trim();
if (isDirExist(createpath)) {
this.sftp.cd(createpath);
logger.info("cd " + createpath);
return true;
}
String[] pathArray = createpath.split("/");
for (String path : pathArray) {
path = path.trim();
if ("".equals(path)) {
continue;
}
if (!isDirExist(path)) {
sftp.mkdir(path);
}
logger.info("cd " + path);
sftp.cd(path);
}
return true;
} catch (SftpException e) {
e.printStackTrace();
}
return false;
}
public boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = sftp.lstat(directory);
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
logger.error("directory:" + directory + ",no such file ERROR!!!");
}
}
return isDirExistFlag;
}
public List<String> downloadFiles(String remotePath, String localPath){
List<String> downloadFiles = new ArrayList<String>();
try {
logger.info("切换到指定目录:" + remotePath);
boolean flag = openDir(remotePath, sftp);
if (flag) {
Vector<?> vv = listFiles("*");
if (vv == null) {
return null;
} else {
for (Object object : vv) {
ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
String remoteFileName = entry.getFilename();
logger.info("校验文件名:" + remoteFileName);
String path = localPath.substring(localPath.length() - 1).equals("/") ? localPath : localPath + "/";
File file = new File(path + remoteFileName);
logger.info("保存校对文件的本地路径为:" + file.getAbsolutePath());
logger.info("start downLoad " + remoteFileName + " ~~");
sftp.get(remoteFileName, new FileOutputStream(file));
logger.info("downLoad ok ~~");
downloadFiles.add(remoteFileName);
}
if (downloadFiles.size() < 1) {
logger.error("remotePath:" + remotePath + "路径下,未匹配到校对文件!");
}
}
} else {
logger.info("对应的目录" + remotePath + "不存在!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
if (session != null) {
if (session.isConnected()) {
session.disconnect();
}
}
}
return downloadFiles;
}
public boolean openDir(String directory, ChannelSftp sftp) {
try {
sftp.cd(directory);
logger.info("cd " + directory + " ok");
return true;
} catch (SftpException e) {
logger.error(e + "");
return false;
}
}
public Vector listFiles(String directory) throws SftpException {
return sftp.ls(directory);
}
public void disconnect() {
try {
sftp.disconnect();
} catch (Exception ignored) {
}
try {
channel.disconnect();
} catch (Exception ignored) {
}
try {
session.disconnect();
} catch (Exception ignored) {
}
}
public static SftpClientUtil getInstans(String host, String username, String password, int port) throws Exception {
return new SftpClientUtil(host, username, password, port, false);
}
public static SftpClientUtil getInstans(String host, String username, String password, int port, String encoding)
throws Exception {
return new SftpClientUtil(host, username, password, port, encoding);
}
public static SftpClientUtil getInstans(String host, String username, String password, int port, String encoding,
int timeout) throws Exception {
return new SftpClientUtil(host, username, password, port, encoding, timeout);
}
3、SFTPConstants
public class SFTPConstants {
public static final String SFTP_REQ_HOST = "192.168.1.1";
public static final String SFTP_REQ_PORT = "22";
public static final String SFTP_REQ_USERNAME = "mulu";
public static final String SFTP_REQ_PASSWORD = "mima";
public static final int SFTP_DEFAULT_PORT = 22;
public static final String SFTP_REQ_LOC = "location";
4、测试
SftpClientUtil sftp = new SftpClientUtil(SFTPConstants.SFTP_REQ_HOST,SFTPConstants.SFTP_REQ_USERNAME,SFTPConstants.SFTP_REQ_PASSWORD, SFTPConstants.SFTP_DEFAULT_PORT,"UTF-8");
List<String> files = sftp.downloadFiles("/mulu","/bendimulu");