자바 sftp 클 라 이언 트 업로드 파일 및 폴 더 기능 코드 구현
2.로그 인 방식 은 비밀번호 로그 인,밀 스푼 로그 인
코드:
주 함수:
import java.util.Properties;
import com.cloudpower.util.Login;
import com.util.LoadProperties;
public class Ftp {
public static void main(String[] args) {
Properties properties = LoadProperties.getProperties();
Login.login(properties);
}
}
로그 인 페이지 의 코드:
package com.cloudpower.util;
import java.io.Console;
import java.util.Properties;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class Login {
public static void login(Properties properties) {
String ip = properties.getProperty("ip");
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
String port = properties.getProperty("port");
String privateKeyPath = properties.getProperty("privateKeyPath");
String passphrase = properties.getProperty("passphrase");
String sourcePath = properties.getProperty("sourcePath");
String destinationPath = properties.getProperty("destinationPath");
if (ip != null && !ip.equals("") && user != null && !user.equals("")
&& port != null && !port.equals("") && sourcePath != null
&& !sourcePath.equals("") && destinationPath != null
&& !destinationPath.equals("")) {
if (privateKeyPath != null && !privateKeyPath.equals("")) {
sshSftp2(ip, user, Integer.parseInt(port), privateKeyPath,
passphrase, sourcePath, destinationPath);
} else if (pwd != null && !pwd.equals("")) {
sshSftp(ip, user, pwd, Integer.parseInt(port), sourcePath,
destinationPath);
} else {
Console console = System.console();
System.out.print("Enter password:");
char[] readPassword = console.readPassword();
sshSftp(ip, user, new String(readPassword),
Integer.parseInt(port), sourcePath, destinationPath);
}
} else {
System.out.println(" ");
}
}
/**
*
*
* @param ip
* @param user
* @param psw
* @param port
* @param sPath
* @param dPath
*/
public static void sshSftp(String ip, String user, String psw, int port,
String sPath, String dPath) {
System.out.println("password login");
Session session = null;
JSch jsch = new JSch();
try {
if (port <= 0) {
// ,
session = jsch.getSession(user, ip);
} else {
//
session = jsch.getSession(user, ip, port);
}
// ,
if (session == null) {
throw new Exception("session is null");
}
//
session.setPassword(psw);//
// , :(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
//
session.connect(300000);
UpLoadFile.upLoadFile(session, sPath, dPath);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("success");
}
/**
*
*
* @param ip
* @param user
* @param port
* @param privateKey
* @param passphrase
* @param sPath
* @param dPath
*/
public static void sshSftp2(String ip, String user, int port,
String privateKey, String passphrase, String sPath, String dPath) {
System.out.println("privateKey login");
Session session = null;
JSch jsch = new JSch();
try {
//
// , jsch.getSession
if (privateKey != null && !"".equals(privateKey)) {
if (passphrase != null && "".equals(passphrase)) {
//
jsch.addIdentity(privateKey, passphrase);
} else {
//
jsch.addIdentity(privateKey);
}
}
if (port <= 0) {
// ,
session = jsch.getSession(user, ip);
} else {
//
session = jsch.getSession(user, ip, port);
}
// ,
if (session == null) {
throw new Exception("session is null");
}
// , :(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
//
session.connect(300000);
UpLoadFile.upLoadFile(session, sPath, dPath);
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
}
}
}
파일 업로드 코드:
package com.cloudpower.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class UpLoadFile {
public static void upLoadFile(Session session, String sPath, String dPath) {
Channel channel = null;
try {
channel = (Channel) session.openChannel("sftp");
channel.connect(10000000);
ChannelSftp sftp = (ChannelSftp) channel;
try {
sftp.cd(dPath);
Scanner scanner = new Scanner(System.in);
System.out.println(dPath + ": , ! y/n?");
String next = scanner.next();
if (!next.toLowerCase().equals("y")) {
return;
}
} catch (SftpException e) {
sftp.mkdir(dPath);
sftp.cd(dPath);
}
File file = new File(sPath);
copyFile(sftp, file, sftp.pwd());
} catch (Exception e) {
e.printStackTrace();
} finally {
session.disconnect();
channel.disconnect();
}
}
public static void copyFile(ChannelSftp sftp, File file, String pwd) {
if (file.isDirectory()) {
File[] list = file.listFiles();
try {
try {
String fileName = file.getName();
sftp.cd(pwd);
System.out.println(" :" + sftp.pwd() + "/" + fileName);
sftp.mkdir(fileName);
System.out.println(" :" + sftp.pwd() + "/" + fileName);
} catch (Exception e) {
// TODO: handle exception
}
pwd = pwd + "/" + file.getName();
try {
sftp.cd(file.getName());
} catch (SftpException e) {
// TODO: handle exception
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < list.length; i++) {
copyFile(sftp, list[i], pwd);
}
} else {
try {
sftp.cd(pwd);
} catch (SftpException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(" :" + file.getAbsolutePath());
InputStream instream = null;
OutputStream outstream = null;
try {
outstream = sftp.put(file.getName());
instream = new FileInputStream(file);
byte b[] = new byte[1024];
int n;
try {
while ((n = instream.read(b)) != -1) {
outstream.write(b, 0, n);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SftpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
outstream.flush();
outstream.close();
instream.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
}
프로필 의 코드 읽 기:
package com.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class LoadProperties {
public static Properties getProperties() {
File file = new File(Class.class.getClass().getResource("/").getPath()
+ "properties.properties");
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Properties properties = new Properties();
try {
properties.load(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return properties;
}
}
코드 디 렉 터 리 구조:테스트 가 실 행 될 때 설정 파일 은 프로젝트 의 빈 디 렉 터 리 에 놓 습 니 다.(jar 파일 을 실행 할 때 삭제 해 야 합 니 다.포장 이 완료 되면 설정 파일 과 jar 패 키 지 를 같은 등급 디 렉 터 리 에 두 면 됩 니 다)
properties.properties
ip=
user=
pwd=
port=22
privateKeyPath=
passphrase=
sourcePath=
destinationPath=/home/dbbs/f
압축 실행 가능 한 jar 파일:Export->java->Runnabe JAR file
완성 후
콘 솔 에서 자바-jar 실행 jar 가방 이름 내 보 내기.jar
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.