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 (null != sftpLocal.get()) {
sftpLocal.get().closeChannel();
logger.info("關閉連接" + sftpLocal.get().sshSession);
sftpLocal.set(null);
}
}
/**
* 關閉通道
*
* @throws Exception
*/
public void closeChannel() {
if (null != channel) {
try {
channel.disconnect();
} catch (Exception e) {
logger.error("關閉SFTP通道發生異常:", e);
}
}
if (null != sshSession) {
try {
sshSession.disconnect();
} catch (Exception e) {
logger.error("SFTP關閉 session異常:", e);
}
}
}
/**
* @param directory
* 上傳ftp的目錄
* @param uploadFile
* 本地文件目錄
*
*/
public boolean upload(String directory, String uploadFile) throws Exception {
try { // 執行列表展示ls 命令
channel.ls(directory); // 執行盤符切換cd 命令
channel.cd(directory);
List<File> files = getFiles(uploadFile, new ArrayList<File>());
for (int i = 0; i < files.size(); i++) {
File file = files.get(i);
InputStream input = new BufferedInputStream(
new FileInputStream(file));
channel.put(input, file.getName());
fileName = file.getName();
System.out.println(fileName);
try {
if (input != null)
input.close();
} catch (Exception e) {
e.printStackTrace();
logger.error(file.getName() + "關閉文件時.....異常!"
+ e.getMessage());
}
if (file.exists()) {
boolean b = file.delete();
logger.info(file.getName() + "文件上傳完畢!刪除標識:" + b);
}
return true;
}
} catch (Exception e) {
logger.error("【子目錄創建中】:", e);
// 創建子目錄
channel.mkdir(directory);
}
return false;
}
// 獲取文件
public List<File> getFiles(String realpath, List<File> files) {
File realFile = new File(realpath);
if (realFile.isDirectory()) {
File[] subfiles = realFile.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
if (null == last_push_date) {
return true;
} else {
long modifyDate = file.lastModified();
return modifyDate > last_push_date.getTime();
}
}
});
for (File file : subfiles) {
if (file.isDirectory()) {
getFiles(file.getAbsolutePath(), files);
} else {
files.add(file);
}
if (null == last_push_date) {
last_push_date = new Date(file.lastModified());
} else {
long modifyDate = file.lastModified();
if (modifyDate > last_push_date.getTime()) {
last_push_date = new Date(modifyDate);
}
}
}
}
return files;
}
// 執行shell腳本
public boolean execute(String command) throws Exception {
// JSch jsch = new JSch();
// Session session = null;
Channel channel = null;
try {
/*
* session = jsch.getSession("zhejiang", "192.168.52.191", 22);
* session.setPassword("jiang1234"); session.setTimeout(2000);
* Properties config = new Properties();
* config.put("StrictHostKeyChecking", "no");
*/
Properties config = new Properties();
sshSession.setConfig(config);
channel = sshSession.openChannel("exec");
ChannelExec execChannel = (ChannelExec) channel;
execChannel.setCommand(command);
InputStream in = channel.getInputStream();
channel.connect();
StringBuffer sb = new StringBuffer();
int c = -1;
while ((c = in.read()) != -1) {
sb.append((char) c);
}
System.out.println("輸出結果是:" + sb.toString());
in.close();
return true;
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return false;
}
// 讀取本地文件
public String readTxtFile(String fileName2) throws IOException,
SftpException {
String result = "";
FileReader fileReader = null;
fileReader = new FileReader(fileName2);
InputStreamReader isr = new InputStreamReader(new FileInputStream(
fileName2), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
String read = null;
while ((read = bufferedReader.readLine()) != null) {
result += read;
}
if (fileReader != null) {
fileReader.close();
bufferedReader.close();
sshSession.disconnect();
}
System.out.println(result);
return result;
}
// 讀取服務器上的文件
public String readTxtFile1(String fileName2) throws IOException,
SftpException {
String result = "";
// FileReader fileReader = null;
// fileReader = new FileReader(fileName2);
InputStreamReader isr = new InputStreamReader(channel.get(fileName2),
"UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
String read = null;
while ((read = bufferedReader.readLine()) != null) {
result += read;
}
if (bufferedReader != null) {
bufferedReader.close();
sshSession.disconnect();
}
System.out.println(result);
return result;
}
// 下載
@SuppressWarnings("deprecation")
public boolean download(String srcPath, String saveFile, String srcfile) {
try {
channel.cd(srcPath);
File file = new File(saveFile);
if (file.isDirectory()) {
channel.get(srcfile, new FileOutputStream(file
+ SystemUtils.FILE_SEPARATOR + srcfile));
System.out.println("下載完成");
} else {
channel.get(srcfile, new FileOutputStream(file));
}
return true;
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Ftp ftp = new Ftp("193.168.52.195", 22, "user", "pwd");
} catch (Exception e) { // TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
}