package com.cmcc.servlet;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
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;
public class Ftp {
// 打印log日志
public static final Log logger = LogFactory.getLog(Ftp.class);
public static Date last_push_date = null;
public Session sshSession;
public ChannelSftp channel;
public static String fileName;
public static ThreadLocal<Ftp> sftpLocal = new ThreadLocal<Ftp>();
public Ftp(String host, int port, String username, String password)
throws Exception {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
// 根据用户名,密码,端口号获取session
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
// 修改服务器/etc/ssh/sshd_config 中 GSSAPIAuthentication的值yes为no,解决用户不能远程登录
sshSession.setConfig("userauth.gssapi-with-mic", "no");
// 为session对象设置properties,第一次访问服务器时不用输入yes
sshSession.setConfig("StrictHostKeyChecking", "no");
sshSession.connect();
// 获取sftp通道
channel = (ChannelSftp) sshSession.openChannel("sftp");
channel.connect();
logger.info("连接ftp成功!" + sshSession);
}
/**
* 是否已连接
*
* @return
*/
public boolean isConnected() {
return null != channel && channel.isConnected();
}
/**
* 获取本地线程存储的sftp客户端
*
* @return
* @throws Exception
*/
public static Ftp getSftpUtil(String host, int port, String username,
String password) throws Exception {
// 获取本地线程
Ftp sftpUtil = sftpLocal.get();
if (null == sftpUtil || !sftpUtil.isConnected()) {
// 将新连接防止本地线程,实现并发处理
sftpLocal.set(new Ftp(host, port, username, password));
}
return sftpLocal.get();
}
/**
* 释放本地线程存储的sftp客户端
*/
public static void release() {
if (