package mocha.framework.util;
/*
* @author Xiehj
* @version 2019年10月28日 上午9:37:28
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;
import org.apache.log4j.Logger;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class SftpTools {
private static final Logger log = Logger.getLogger(SftpTools.class);
Session sshSession;
/**
* 鏈接sftp
*
* @param host
* 主機
* @param port
* 端口
* @param username
* 用戶名
* @param password
* 密碼
* @return
*/
public ChannelSftp connect(String host, int port, String username,
String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
sshSession = jsch.getSession(username, host, port);
//log.info("Session創建成功");
sshSession.setPassword(password);
//log.info("密碼輸入成功");
//sshSession.setConfig("kex","diffie-hellman-group1-sha1");
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
//log.info("鏈接參數設置成功");
sshSession.setConfig(sshConfig);
sshSession.connect();
//log.info("Session已連接");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
//log.info("連接到主機" + host);
} catch (Exception e) {
e.printStackTrace();
}
return sftp;
}
/**
* 文件重命名
*
* @param directory 目錄
* @param oldname 舊文件名
* @param newname 新文件名
* @param sftp
*/
public void renameFile(String directory, String oldname, String newname,
ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rename(oldname, newname);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 文件上傳
*
* @param directory 目錄
* @param uploadFile 要上傳的文件名
* @param sftp
*/
public void upload(String directory, String uploadFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
public void uploada(String directory,String sftpFileName,InputStream input, ChannelSftp sftp) throws SftpException{
try {
sftp.cd(directory);
} catch (Exception e) {
}
sftp.put(input, sftpFileName);
}
/**
* 將輸入流的數據上傳到sftp作為文件。文件完整路徑=basePath+directory
*
* @param basePath
* 服務器的基礎路徑
* @param directory
* 上傳到該目錄
* @param sftpFileName
* sftp端文件名
* @param input
* 輸入流 throws SftpException
*/
public boolean upload(String directory, String sftpFileName,
InputStream input, ChannelSftp sftp) {
boolean ret = false;
try {
// sftp.cd(basePath);
sftp.cd(directory);
ret = true;
} catch (SftpException e) {
// 目錄不存在,則創建文件夾
String[] dirs = directory.split("/");
String tempPath = "";
for (String dir : dirs) {
if (null == dir || "".equals(dir))
continue;
tempPath+="/"+dir;
//tempPath = dir;
try {
sftp.cd(tempPath);
ret = true;
} catch (SftpException ex) {
try {
sftp.mkdir(tempPath);
sftp.cd(tempPath);
ret = true;
} catch (SftpException e1) {
ret = false;
return ret;
} catch (Exception e1) {
ret = false;
return ret;
}
} catch (Exception e1) {
ret = false;
return ret;
}
}
ret = true;
} catch (Exception e1) {
ret = false;
return ret;
}
try {
sftp.put(input, sftpFileName);// 上傳文件
ret = true;
} catch (SftpException e) {
ret = false;
}
return ret;
}
/**
* 文件下載
*
* @param directory 目錄
* @param downloadFile 要下載文件名
* @param saveFile 保持的文件名
* @param sftp
*/
public void download(String directory, String downloadFile,
String saveFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下載文件
* @param directory 下載目錄
* @param downloadFile 下載的文件名
* @return 字節數組
*/
public InputStream download(String directory, String downloadFile,ChannelSftp sftp) {
if (directory != null && !"".equals(directory)) {
try {
sftp.cd(directory);
InputStream is = sftp.get(downloadFile);
return is;
} catch (SftpException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 文件刪除
*
* @param directory 目錄
* @param deleteFile 要刪除的文件名
* @param sftp
*/
public void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
log.info("刪除成功");
} catch (Exception e) {
log.info("刪除失敗");
e.printStackTrace();
}
}
/**
* 列出目錄下的文件
*
* @param directory 目錄
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory, ChannelSftp sftp)
throws SftpException {
return sftp.ls(directory);
}
//批量刪除文件
public void delete(String directory, String[] fileNames, ChannelSftp aa) {
for (String fileName : fileNames) {
this.delete(directory, fileName, aa);
}
}
/**
* 創建目錄文件夾
* @param directory 要創建文件夾的位置路徑
* @param fileName 要創建文件夾的名稱
* @param sftp sftp連接
*/
//創建目錄文件
public void mkdir(String directory,String fileName,ChannelSftp sftp){
try {
sftp.cd(directory);
sftp.mkdir(fileName);
log.info("文件夾創建成功");
} catch (Exception e) {
log.info("文件夾創建失敗");
e.printStackTrace();
}
}
public static void downLoadPic(String path,String downLoadFileName,String newFileName){
SftpTools sftpTools = new SftpTools();
//測試環境地址
String host="10.1.1.105";
int port=22;
String username="weblogic";
String password="1232343";
String directory="/weblogic/wls1036_x64/user_projects/domains/sasdomain/app/zyx_server/images/showpic/";
//建立sftp連接
ChannelSftp content= sftpTools.connect(host, port, username, password);
String saveFile = newFileName;
//下載文件
sftpTools.download(directory, downLoadFileName, saveFile, content);
}
/**
* 關閉連接 server
*/
public void logout(ChannelSftp sftp){
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
// log.info("sftp is closed already");
}
}
if (sshSession != null) {
if (sshSession.isConnected()) {
sshSession.disconnect();
// log.info("sshSession is closed already");
}
}
}
public static void main(String[] args) throws IOException{
SftpTools s = new SftpTools();
String host= "";
//String host= "";
int port= 22;
String username= "";
//String username= "";
String password= "";
//String password= "";
ChannelSftp connect = s.connect(host, port, username, password);
String directory = "/opt/";
//String fileName = "test3.txt";
//s.mkdir(directory, fileName, connect);
// Vector listFiles;
// try {
// listFiles = s.listFiles(directory, connect);
// for (int i = 0; i < listFiles.size(); i++) {
// /*log.info(listFiles.get(i));*/
// System.out.println(listFiles.get(i));
// }
// } catch (SftpException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
InputStream input = s.download(directory, "D_20200902.txt", connect);
File tempFile = new File("F:\\test");
if (!tempFile.exists()) {
tempFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(tempFile.getPath() + File.separator + "D_20200902.txt");
byte[] b = new byte[2048];
int len;
while ((len = input.read(b)) != -1) {
out.write(b, 0, len);
}
System.out.println("文件下載成功");
s.logout(connect);
}
}
以上代碼導入后,需要加入一個jsch的jar包
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
快去試試吧
