JSch 이용한 sftp 파일 다운로드
SSH2 프로토콜을 사용하는 JSch를 이용한 파일 업/다운로드 구현 소스
http://www.jcraft.com/jsch/
💡 import
파일입출력 : File FileInputStream FileOutputStream
성능향상 보조스트림: BufferedInputStream, BufferedOutputStream
매일 업데이트하는 로그 파일에 대한 네이밍에 쓰일 일자: SimpleDateFormat, Date
FTP 접속을 위한 모듈: JSch, Session, Channel, ChannelSftp, JSchException
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
✍ class
설계
-
멤버변수
접속을 위한 원격주소, 연결포트, 사용자명, 비밀번호와
JSch, Session, Channel, ChannelSftp 멤버변수로 갖는다 -
함수
connect, disconnect, upload, download
, 다운 받은 파일을 원격저장소에 복사하는 filecopy 함수를 정의한다
참고사항
-
연결함수에서 session.setConfig("StrictHostKeyChecking", "no"); 은
호스트 키를 확인하지 않겠다는 설정 -
DB 트랜잭션의 begin, commit과 같이 사용자가 원하는 때에 connect, disconnect 할 수 있도록 upload, download, 함수에 connect, disconnect 함수는 호출하지 않았다
-
filecopy 함수는 윈도우 환경(해당 모듈 작동 OS환경)
public class MySftp {
private String host;
private Integer port;
private String user;
private String password;
private JSch jsch;
private Session session;
private Channel channel;
private ChannelSftp sftpChannel;
public MySftp(String host, Integer port, String user, String password) {
this.host = host;
this.port = port;
this.user = user;
this.password = password;
}
public int connect() {
System.out.println("connecting..." + host);
try {
jsch = new JSch();
session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
sftpChannel = (ChannelSftp) channel;
System.out.println("connected" + host);
return 1;
} catch (JSchException e) {
System.out.println("fail to connect");
e.printStackTrace();
return 0;
}
}
public void disconnect() {
System.out.println("disconnecting...");
sftpChannel.disconnect();
channel.disconnect();
session.disconnect();
System.out.println("disconnected");
}
public void upload(String fileName, String remoteDir) {
FileInputStream fis = null;
try {
// Change to output directory
sftpChannel.cd(remoteDir);
// Upload file
File file = new File(fileName);
fis = new FileInputStream(file);
sftpChannel.put(fis, file.getName());
fis.close();
System.out.println("File uploaded successfully - "
+ file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
public void download(String fileName, String localDir) {
byte[] buffer = new byte[1024];
BufferedInputStream bis;
try {
// Change to output directory
String cdDir = fileName.substring(0, fileName.lastIndexOf("/") + 1);
sftpChannel.cd(cdDir);
File file = new File(fileName);
bis = new BufferedInputStream(sftpChannel.get(file.getName()));
File newFile = new File(localDir + "/" + file.getName());
// Download file
OutputStream os = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
int readCount;
while ((readCount = bis.read(buffer)) > 0) {
bos.write(buffer, 0, readCount);
}
bis.close();
bos.close();
System.out.println("File downloaded successfully - "
+ file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
public void filecopy(String path, String yesterday) {
try {
Runtime runtime = Runtime.getRuntime();
String s_exe = "cmd /c md \\\\192.168.0.76\\sftp\\" + yesterday;
runtime.exec(s_exe);
s_exe = "cmd /c move \\\\192.168.0.76\\sftp\\*." + yesterday.substring(2)
+ " \\\\192.168.0.76\\sftp\\" + yesterday;
runtime.exec(s_exe);
s_exe = "xcopy /Y " + path + " \\\\192.168.0.76\\sftp\\";
runtime.exec(s_exe);
} catch (Exception e) {
e.printStackTrace();
}
}
}
✍ main
일자와 시간으로 로그파일 구분
public static void main(String[] args) {
Date date = new Date();
Date yesterday = new Date();
SimpleDateFormat today = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat now = new SimpleDateFormat("hh:mm:ss");
String today_yymmdd = today.format(date).substring(2);
yesterday.setTime(date.getTime() - ((long) 1000 * 60 * 60 *24));
String strYesterday = today.format(yesterday);
String localPath = "C:\\sftp\\" + today.format(date);
String remotePath = "/home/jboss/sftp/";
File folder = new File(localPath);
folder.mkdirs();
MySftp sftp = new MySftp("192.168.110.10", 22, "ftpuser", "ftppw");
if(!sftp.connect())
return;
sftp.upload(localPath+"filetoupload.txt", remotePath);
sftp.download("/home/jboss/natgerp." + today_yymmdd, localPath);
sftp.disconnect();
filecopy(localPath, strYesterday);
}
📝 전체 소스
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class MySftp {
private String host;
private Integer port;
private String user;
private String password;
private JSch jsch;
private Session session;
private Channel channel;
private ChannelSftp sftpChannel;
public MySftp(String host, Integer port, String user, String password) {
this.host = host;
this.port = port;
this.user = user;
this.password = password;
}
public int connect() {
System.out.println("connecting..." + host);
try {
jsch = new JSch();
session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
sftpChannel = (ChannelSftp) channel;
System.out.println("connected" + host);
return 1;
} catch (JSchException e) {
System.out.println("fail to connect");
e.printStackTrace();
return 0;
}
}
public void disconnect() {
System.out.println("disconnecting...");
sftpChannel.disconnect();
channel.disconnect();
session.disconnect();
System.out.println("disconnected");
}
public void upload(String fileName, String remoteDir) {
FileInputStream fis = null;
try {
// Change to output directory
sftpChannel.cd(remoteDir);
// Upload file
File file = new File(fileName);
fis = new FileInputStream(file);
sftpChannel.put(fis, file.getName());
fis.close();
System.out.println("File uploaded successfully - "
+ file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
public void download(String fileName, String localDir) {
byte[] buffer = new byte[1024];
BufferedInputStream bis;
try {
// Change to output directory
String cdDir = fileName.substring(0, fileName.lastIndexOf("/") + 1);
sftpChannel.cd(cdDir);
File file = new File(fileName);
bis = new BufferedInputStream(sftpChannel.get(file.getName()));
File newFile = new File(localDir + "/" + file.getName());
// Download file
OutputStream os = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
int readCount;
while ((readCount = bis.read(buffer)) > 0) {
bos.write(buffer, 0, readCount);
}
bis.close();
bos.close();
System.out.println("File downloaded successfully - "
+ file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
public void filecopy(String path, String yesterday) {
try {
Runtime runtime = Runtime.getRuntime();
String s_exe = "cmd /c md \\\\192.168.0.76\\sftp\\" + yesterday;
runtime.exec(s_exe);
s_exe = "cmd /c move \\\\192.168.0.76\\sftp\\*." + yesterday.substring(2)
+ " \\\\192.168.0.76\\sftp\\" + yesterday;
runtime.exec(s_exe);
s_exe = "xcopy /Y " + path + " \\\\192.168.0.76\\sftp\\";
runtime.exec(s_exe);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Date date = new Date();
Date yesterday = new Date();
SimpleDateFormat today = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat now = new SimpleDateFormat("hh:mm:ss");
String today_yymmdd = today.format(date).substring(2);
yesterday.setTime(date.getTime() - ((long) 1000 * 60 * 60 *24));
String strYesterday = today.format(yesterday);
String localPath = "C:\\sftp\\" + today.format(date);
String remotePath = "/home/jboss/sftp/";
File folder = new File(localPath);
folder.mkdirs();
MySftp sftp = new MySftp("192.168.110.10", 22, "ftpuser", "ftppw");
if(!sftp.connect())
return;
sftp.upload(localPath+"filetoupload.txt", remotePath);
sftp.download("/home/jboss/natgerp." + today_yymmdd, localPath);
sftp.disconnect();
filecopy(localPath, strYesterday);
}
}
Author And Source
이 문제에 관하여(JSch 이용한 sftp 파일 다운로드), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@conda/JSch저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)