1.依赖的jar文件 jsch-0.1.53.jar

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; }
}

代码目录结构:

测试运行时配置文件放在项目的bin目录下(打包成可运行jar文件的时候要删除,打包完成后将配置文件和jar包放在同级目录下即可):

properties.properties
ip=
user=
pwd=
port=22
privateKeyPath=
passphrase=
sourcePath=
destinationPath=/home/dbbs/f

打包可运行jar文件:

Export->java->Runnabe JAR file

完成后

在控制台运行java -jar  导出jar包的名字.jar 即可

java实现sftp客户端上传文件以及文件夹的功能的更多相关文章

  1. java实现sftp客户端上传文件夹的功能

    使用的jar: <dependencies> <dependency> <groupId>jsch</groupId> <artifactId&g ...

  2. java 通过sftp服务器上传下载删除文件

    最近做了一个sftp服务器文件下载的功能,mark一下: 首先是一个SftpClientUtil 类,封装了对sftp服务器文件上传.下载.删除的方法 import java.io.File; imp ...

  3. Java使用SFTP协议上传、下载文件

    http://blog.csdn.net/haidage/article/details/6859716 在自己尝试之后发现以上内容里有坑. 1.关闭连接的时候,必须要sftp.getSession( ...

  4. .NET 客户端上传本地excel文件到服务器上,并在客户端显示

    // 上传按钮 protected void btnUp_Click(object sender, EventArgs e) { bool b = Upload(fuExcel); // 上传exce ...

  5. JAVA通过FTP方式向远程服务器或者客户端上传、下载文件,以及删除FTP服务器上的文件

    1.在目标服务器上搭建FTP服务器 搭建方式有多种大家可以自行选择,例如使用Serv-U或者FTPServer.exe:这里我以FTPServer.exe为例搭建:在目标服务器(这里对应的IP是10. ...

  6. 【JAVA】通过HttpURLConnection 上传和下载文件(二)

    HttpURLConnection文件上传 HttpURLConnection采用模拟浏览器上传的数据格式,上传给服务器 上传代码如下: package com.util; import java.i ...

  7. FastDfs java客户端上传、删除文件

    #配置文件 connect_timeout = 2 network_timeout = 30 charset = UTF-8 http.tracker_http_port = 9090 http.an ...

  8. Java基础知识强化之网络编程笔记14:TCP之多个客户端上传到一个服务器的思考(多线程改进)

    1. 多个客户端上传到一个服务器的思考 通过while循环可以改进一个服务器接收多个客户端. 但是这个是有问题的.如果是这种情况,假设我还有张三,李四,王五这三个人分别执行客户端  张三:好好学习.a ...

  9. Xshell5下利用sftp上传下载传输文件

    sftp是Secure File Transfer Protocol的缩写,安全文件传送协议.可以为传输文件提供一种安全的加密方法.sftp 与 ftp 有着几乎一样的语法和功能.SFTP 为 SSH ...

随机推荐

  1. css实现三栏自适应布局(两边固定,中间自适应)以及优缺点

    方法一:绝对定位(absolute + margin) 原理:给左右两边的元素设置absolute,这样左右两边的元素脱离标准文档流的控制,中间的元素自然会上来,然后给中间的元素设置margin留出左 ...

  2. [转帖]cmd批处理常用符号详解

    cmd批处理常用符号详解 https://www.jb51.net/article/32866.htm 很多符号 还是不清楚的.. 批处理能够极大的提高 工作效率 需要加强深入学习.   1.@一般在 ...

  3. CentOS7配置gradle,或配置maven

    借鉴博客: https://www.cnblogs.com/imyalost/p/8746527.html 特简单,不多说了,自己看 1.下载gradle4.6版本:wget https://down ...

  4. 微信小程序自定义组件

    要做自定义组件,我们先定一个小目标,比如说我们在小程序中实现一下 WEUI 中的弹窗组件,基本效果图如下. Step1 我们初始化一个小程序(本示例基础版本库为 1.7 ),删掉里面的示例代码,并新建 ...

  5. Linux基础学习笔记4-文本处理

    本章内容 抽取文本的工具 文件内容:less和cat 文件截取:head和tail 按列抽取:cut 按关键字抽取:grep 文件查看 文件查看命令:cat,tac,rev cat [OPTION] ...

  6. 不停机修改线上 MySQL 主键字段 以及其带来的问题和总结思考

    起因: 线上 user 数据库没有自增字段,数据量已经达到百万级.无论是给离线仓库还是数据分析同步数据,没有主键自增 id 都是杀手级的困难.所以在使用 create_time 痛苦了几次之后准备彻底 ...

  7. 莫烦theano学习自修第十天【保存神经网络及加载神经网络】

    1. 为何保存神经网络 保存神经网络指的是保存神经网络的权重W及偏置b,权重W,和偏置b本身是一个列表,将这两个列表的值写到列表或者字典的数据结构中,使用pickle的数据结构将列表或者字典写入到文件 ...

  8. qtp自动化测试-条件语句 if select case

    1 if 语句 if  condition  then end if If condition Then   [statements] [ElseIf condition-n Then   [else ...

  9. sql left join多表

    表A---------------------------------关联第一张表B-----------------------关联第二张表c select * fomr 表名A left join ...

  10. Web API2 使用EF Code Migrations to Seed DB

    console Enable-Migrations 运行这个命令,添加一个文件夹Migrations,Configuration.cs在这文件夹中 打开 Configuration.cs file. ...