자바 jsch 를 이용 하여 sftp 도구 류 조작
package cn.fraudmetrix.luna.biz.util;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* sftp Created by jie on 2018/7/18.
*/
public class SFTPHelper implements Closeable {
private final static Logger log = LoggerFactory.getLogger(SFTPHelper.class);
private Session session;
private ChannelSftp channelSftp;
/**
* ,
*/
private final static int TIMEOUT = 60000;
private final static int BYTE_LENGTH = 1024;
public SFTPHelper(String userName, String password, String host){
try {
String[] arr = host.split(":");
String ip = arr[0];
int port = arr.length > 1 ? Integer.parseInt(arr[1]) : 22;
JSch jSch = new JSch();
session = jSch.getSession(userName, ip, port);
if (null != password) {
session.setPassword(password);
}
session.setTimeout(TIMEOUT);
Properties properties = new Properties();
properties.put("StrictHostKeyChecking", "no");
session.setConfig(properties);
} catch (Exception e) {
log.error("init host:{},userName:{},password:{} error:{}",host,userName,password, e);
}
}
/**
* : close
*
* @see SFTPHelper#close()
* @return
*/
public boolean connection() {
try {
if (!isConnected()) {
session.connect();
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
log.info("connected to host:{},userName:{}", session.getHost(), session.getUserName());
}
return true;
} catch (JSchException e) {
log.error("connection to sftp host:{} error:{}", session.getHost(), e);
return false;
}
}
/**
* sftp
*
* @param remoteFile +fileName
* @param localPath
* @return
*/
public boolean get(String remoteFile, String localPath) {
if (isConnected()) {
try {
channelSftp.get(remoteFile, localPath);
return true;
} catch (SftpException e) {
log.error("get remoteFile:{},localPath:{}, error:{}", remoteFile, localPath, e);
}
}
return false;
}
/**
* sftp
*
* @param remoteFile
* @return
*/
public byte[] getFileByte(String remoteFile) {
byte[] fileData;
try (InputStream inputStream = channelSftp.get(remoteFile)) {
byte[] ss = new byte[BYTE_LENGTH];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int rc = 0;
while ((rc = inputStream.read(ss, 0, BYTE_LENGTH)) > 0) {
byteArrayOutputStream.write(ss, 0, rc);
}
fileData = byteArrayOutputStream.toByteArray();
} catch (Exception e) {
log.error("getFileData remoteFile:{},error:{}", remoteFile, e);
fileData = null;
}
return fileData;
}
/**
* sftp ( ) ,
*
* @param remoteFile
* @param charsetName
* @return
*/
public List getFileLines(String remoteFile,String charsetName) {
List fileData;
try (InputStream inputStream = channelSftp.get(remoteFile);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charsetName);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
String str;
fileData = new ArrayList<>();
while((str = bufferedReader.readLine()) != null){
fileData.add(str);
}
} catch (Exception e) {
log.error("getFileData remoteFile:{},error:{}", remoteFile, e);
fileData = null;
}
return fileData;
}
/**
* sftp
*
* @param localFile
* @param remoteFile
* @return
*/
public boolean put(String localFile, String remoteFile) {
if (isConnected()) {
try {
channelSftp.put(localFile, remoteFile);
return true;
} catch (SftpException e) {
log.error("put localPath:{}, remoteFile:{},error:{}", localFile, remoteFile, e);
return false;
}
}
return false;
}
/**
* sftp
*
* @param remoteFile
* @return
*/
public boolean delFile(String remoteFile) {
if (isConnected()) {
try {
channelSftp.rm(remoteFile);
return true;
} catch (SftpException e) {
log.error("delFile remoteFile:{} , error:{}", remoteFile, e);
}
}
return false;
}
/**
*
* @param remotePath
* @return
*/
public Vector ls(String remotePath){
Vector vector = null;
if(isConnected()){
try {
vector = channelSftp.ls(remotePath);
} catch (SftpException e) {
vector = null;
log.error("ls remotePath:{} , error:{}",remotePath,e);
}
}
return vector;
}
/**
*
* @param remotePath
* @param filenamePattern
* @return
* ./ ../ ,
*/
public List lsFiles(String remotePath,Pattern filenamePattern){
List lsEntryList = null;
if(isConnected()){
try {
Vector vector = channelSftp.ls(remotePath);
if(vector != null) {
lsEntryList = vector.stream().filter(x -> {
boolean match = true;
if(filenamePattern != null){
Matcher mtc = filenamePattern.matcher(x.getFilename());
match = mtc.find();
}
if (match && !x.getAttrs().isDir() && !x.getAttrs().isLink()) {
return true;
}
return false;
}).collect(Collectors.toList());
}
} catch (SftpException e) {
lsEntryList = null;
log.error("lsFiles remotePath:{} , error:{}",remotePath,e);
}
}
return lsEntryList;
}
/**
*
*
* @return
*/
public boolean isConnected() {
if (session.isConnected() && channelSftp.isConnected()) {
return true;
}
log.info("sftp server:{} is not connected",session.getHost());
return false;
}
/**
*
*/
@Override
public void close() throws IOException {
if (channelSftp != null && channelSftp.isConnected()) {
channelSftp.quit();
}
if (session != null && session.isConnected()) {
session.disconnect();
}
log.info("session and channel is closed");
}
public static void main(String[] args) throws FileNotFoundException {
try(SFTPHelper sftpHelper = new SFTPHelper("vip001", "155d1e33274", "10.58.10.179")) {
if (sftpHelper.connection()) {
// boolean result = sftpHelper.get("/data/sftp/vip001/file/luna/newnew_result_20180730.txt","/tmp/luna/newnew_result_20180730.txt");
// boolean result = sftpHelper.get("/data/sftp/vip001/file/app.log","/tmp/app.log");
// boolean result = sftpHelper.put("/tmp/app.log","/data/sftp/vip001/file/app.log");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.