java实现sftp客户端上传文件夹的功能
使用的jar:
<dependencies>
<dependency>
<groupId>jsch</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
</dependencies>
入口方法:
import java.util.HashMap; public class Sftp {
public static void main(String[] args) { String helpMessage = "You need enter 5 args\n"
+ "1. target ip or domain name\n"
+ "2. target user\n"
+ "3. target password\n"
+ "4. source path\n"
+ "5. destination path\n"; if (args[0].equalsIgnoreCase("-help") || args[0].equalsIgnoreCase("-h")) {
System.out.println(helpMessage);
} if (args.length != 5) {
System.out.println("The number of parameters entered is incorrect!\n" + helpMessage);
return;
} HashMap<String, String> map = new HashMap<>(8);
map.put("ip",args[0]);
map.put("user",args[1]);
map.put("pwd",args[2]);
map.put("sourcePath",args[3]);
map.put("destinationPath",args[4]);
map.put("port","22");
Login.login(map);
}
}
登录处理:
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();
}
}
}
Login.java
文件上传的代码:
import java.io.*;
import java.util.Vector; import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException; public class UpLoadFile {
private static String split = "\\"; 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; if (isDirExist(sftp, dPath)) {
String createPath = dPath + sPath.substring(sPath.lastIndexOf(split) + split.length());
if (isDirExist(sftp, createPath)) {
deleteSFTP(sftp, createPath);
}
} else {
createDir(sftp, 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();
}
}
}
} /**
* 创建目录
*
* @param createPath
* @return
*/
public static void createDir(ChannelSftp sftp, String createPath) {
try {
if (isDirExist(createpath)) {
sftp.cd(createpath);
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
// 建立目录
sftp.mkdir(filePath.toString());
// 进入并设置为当前目录
sftp.cd(filePath.toString());
}
}
} catch (SftpException e) {
e.printStackTrace();
}
} /**
* 删除stfp文件
*
* @param directory:要删除文件所在目录
*/
public static void deleteSFTP(ChannelSftp sftp, String directory) {
try {
if (isDirExist(directory)) {
Vector<ChannelSftp.LsEntry> vector = sftp.ls(directory);
if (vector.size() == 1) { // 文件,直接删除
sftp.rm(directory);
} else if (vector.size() == 2) { // 空文件夹,直接删除
sftp.rmdir(directory);
} else {
String fileName = "";
// 删除文件夹下所有文件
for (ChannelSftp.LsEntry en : vector) {
fileName = en.getFilename();
if (".".equals(fileName) || "..".equals(fileName)) {
continue;
} else {
deleteSFTP(sftp,directory + "/" + fileName);
}
}
// 删除文件夹
sftp.rmdir(directory);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 判断目录是否存在
*
* @param directory
* @return
*/
public static boolean isDirExist(String directory) {
try {
Vector<?> vector = sftp.ls(directory);
return (null != vector);
} catch (Exception e) {
return false;
}
}
}
UpLoadFile.java
参考:
https://www.cnblogs.com/zuo-java/p/5913295.html
https://www.cnblogs.com/future-eye/p/8194544.html
java实现sftp客户端上传文件夹的功能的更多相关文章
- java实现sftp客户端上传文件以及文件夹的功能
1.依赖的jar文件 jsch-0.1.53.jar 2.登录方式有密码登录,和密匙登录 代码: 主函数: import java.util.Properties; import com.cloudp ...
- java实现上传文件夹
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 首先我们需要了解的是上传文件三要素: 1.表单提交方式:post (get方式提交有大小 ...
- SFTP 上传文件夹
使用sftp上传文件夹时若使用如下命令并不work: put /media/Research/GWAS_Class/* Desktop/ 此时,需要添加一个参数 -r, 另外在目标文件夹下面建立一个同 ...
- MVC文件上传05-使用客户端jQuery-File-Upload插件和服务端Backload组件自定义上传文件夹
在零配置情况下,文件的上传文件夹是根目录下的Files文件夹,如何自定义文件的上传文件夹呢? MVC文件上传相关兄弟篇: MVC文件上传01-使用jquery异步上传并客户端验证类型和大小 MVC文 ...
- java上传文件夹文件
这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...
- java+实现上传文件夹
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 首先我们需要了解的是上传文件三要素: 1.表单提交方式:post (get方式提交有大小 ...
- java+struts上传文件夹文件
这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...
- java+上传+文件夹
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 首先我们需要了解的是上传文件三要素: 1.表单提交方式:post (get方式提交有 ...
- java上传文件夹
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用.此控件PC全平台支持包括mac,linux系统的文件上传,文章末尾将附上控件下载与教程链接 ...
随机推荐
- 一幅图,看懂中国CMMI
以下数据由Fancier凡奉信息根据历年CMMI Institute公布的CMMI评估结果的汇总整理.数据跨度2008-2017年,包含对中国CMMI与全球CMMI的不同等级.版本的统计.
- hadoop1.0 和 Hadoop 2.0 的区别
1.Hadoop概述 在Google三篇大数据论文发表之后,Cloudera公司在这几篇论文的基础上,开发出了现在的Hadoop.但Hadoop开发出来也并非一帆风顺的,Hadoop1.0版本有诸多局 ...
- SQLServer之创建视图
视图定义 视图是一个虚拟的表,是一个表中的数据经过某种筛选后的显示方式,视图由一个预定义的查询select语句组成. 使用SSMS数据库管理工具创建视图 1.连接数据库,选择数据库,展开数据库-> ...
- c/c++ 网络编程 UDP 发送端 bind 作用
网络编程 UDP 发送端 bind 作用 upd 发送端 调用bind函数的效果:把socket特定到一个指定的端口,如果不调用bind,内核会随机分配一个端口. upd 发送端 调用bind函数的目 ...
- 5.1Python数据处理篇之Sympy系列(一)---Sympy的大体认识
目录 目录 前言 目录 前言 sympy是python一个强大的数学符号运算第三方库,具体的功能请看下面操作 官网教程: https://docs.sympy.org/latest/tutorial/ ...
- Django REST framework基础:版本控制
DRF的版本控制 为什么需要版本控制 API 版本控制允许我们在不同的客户端之间更改行为(同一个接口的不同版本会返回不同的数据). DRF提供了许多不同的版本控制方案. 可能会有一些客户端因为某些原因 ...
- Collections方法的使用
public static void main(String[] args) { // 0.给List排序 List<Integer> list = new ArrayList<In ...
- java.io.IOException: There appears to be a gap in the edit log. We expected txid ***, but got txid
方式1 原因:namenode元数据被破坏,需要修复解决:恢复一下namenode hadoop namenode -recover 一路选择Y,一般就OK了 方式2 Need to copy the ...
- Kerberos原理
前些日子为了搞清楚Kerberos原理,把MIT的Kerberos经典对话看了几遍,终于有了一个稍微清晰的认识,这里稍微记录下,因为Kerberos是使用传统加密技术实现的一个认证机制,所以顺便备忘下 ...
- tmpfs使用探讨
一. 什么是tmpfs? tmpfs是一种基于内存的文件系统,它和虚拟磁盘ramdisk比较类似,但不完全相同,和ramdisk一样,tmpfs可以使用RAM,但它也可以使用swap分区来存储. 而且 ...