使用的jar包:

 <dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>

文件上传也可以使用scp,但是最后实现发现scp特别困难,而且只能实现上传这一个功能。如果要实现文件的删除则需要使用其他命令。

而sftp则是建立一个ssh通道,然后可以很方便的在通道内执行一系列命令,如put, get, rm, mkdir, rmdir,从而可以方便的管理远程服务器的文件。

下面介绍下Java实现。

首先我们创建一个pojo,将所有的账号信息及远程服务器信息都封装一下。

 package com.snow.sftp;

 import lombok.Data;

 @Data
public class SftpAuthority {
private String host; // 服务器ip或者主机名
private int port; // sftp端口
private String user; // sftp使用的用户
private String password; // 账户密码
private String privateKey; // 私钥文件名
private String passphrase; // 私钥密钥 public SftpAuthority(String user, String host, int port) {
this.host = host;
this.port = port;
this.user = user;
}
}

在建立sftp通道过程中我们可以选择使用用户名密码的方式,也可以选择使用私钥(私钥可以有密钥)的方式。

建立一个service interface

 package com.snow.sftp;

 public interface SftpService {

     void createChannel(SftpAuthority sftpAuthority);

     void closeChannel();

     boolean uploadFile(SftpAuthority sftpAuthority, String src, String dst);

     boolean removeFile(SftpAuthority sftpAuthority, String dst);

 }

具体实现:

 package com.snow.sftp;

 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;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import java.util.Properties; @Slf4j
@Service(value = "sftpService")
public class SftpServiceImpl implements SftpService { private Session session;
private Channel channel;
private ChannelSftp channelSftp; @Override
public void createChannel(SftpAuthority sftpAuthority) {
try {
JSch jSch = new JSch();
session = jSch.getSession(sftpAuthority.getUser(), sftpAuthority.getHost(), sftpAuthority.getPort()); if (sftpAuthority.getPassword() != null) {
// 使用用户名密码创建SSH
session.setPassword(sftpAuthority.getPassword());
} else if (sftpAuthority.getPrivateKey() != null) {
// 使用公私钥创建SSH
jSch.addIdentity(sftpAuthority.getPrivateKey(), sftpAuthority.getPassphrase());
} Properties properties = new Properties();
properties.put("StrictHostKeyChecking", "no"); // 主动接收ECDSA key fingerprint,不进行HostKeyChecking
session.setConfig(properties);
session.setTimeout(0); // 设置超时时间为无穷大
session.connect(); // 通过session建立连接 channel = session.openChannel("sftp"); // 打开SFTP通道
channel.connect();
channelSftp = (ChannelSftp) channel;
} catch (JSchException e) {
log.error("create sftp channel failed!", e);
}
} @Override
public void closeChannel() {
if (channel != null) {
channel.disconnect();
} if (session != null) {
session.disconnect();
}
} @Override
public boolean uploadFile(SftpAuthority sftpAuthority, String src, String dst) {
if (channelSftp == null) {
log.warn("need create channelSftp before upload file");
return false;
} if (channelSftp.isClosed()) {
createChannel(sftpAuthority); // 如果被关闭则应重新创建
} try {
channelSftp.put(src, dst, ChannelSftp.OVERWRITE);
log.info("sftp upload file success! src: {}, dst: {}", src, dst);
return true;
} catch (SftpException e) {
log.error("sftp upload file failed! src: {}, dst: {}", src, dst, e);
return false;
}
} @Override
public boolean removeFile(SftpAuthority sftpAuthority, String dst) {
if (channelSftp == null) {
log.warn("need create channelSftp before remove file");
return false;
} if (channelSftp.isClosed()) {
createChannel(sftpAuthority); // 如果被关闭则应重新创建
} try {
channelSftp.rm(dst);
log.info("sftp remove file success! dst: {}", dst);
return true;
} catch (SftpException e) {
log.error("sftp remove file failed! dst: {}", dst, e);
return false;
}
} }

调用示例:

 package com.snow.sftp;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSftp { public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"sftp-application-context.xml"}); // 用户名密码方式
SftpService sftpService = context.getBean(SftpService.class);
SftpAuthority sftpAuthority = new SftpAuthority("user", "ip or host", port);
sftpAuthority.setPassword("user password"); sftpService.createChannel(sftpAuthority);
sftpService.uploadFile(sftpAuthority, "/home/snow/test/test.png", "/user/testaaa.png");
sftpService.removeFile(sftpAuthority, "/user/testaaa.png");
sftpService.closeChannel(); // 公私钥方式
sftpAuthority = new SftpAuthority("user", "ip or host", port);
sftpAuthority.setPrivateKey("your private key full path");
sftpAuthority.setPassphrase("private key passphrase");
sftpService.createChannel(sftpAuthority);
sftpService.uploadFile(sftpAuthority, "/home/snow/test/test.png", "/user/testaaa.png");
sftpService.removeFile(sftpAuthority, "/user/testaaa.png");
sftpService.closeChannel();
} }

除了本文介绍的put和rm操作以外,channelSftp还有很多其它的操作,比如get, mkdir, lcd, rename, rmdir, ls, lstat等,大家可以自行探索。

JAVA实现上传文件到服务器、删除服务器文件的更多相关文章

  1. java上传、下载、删除ftp文件

    一共三个类,一个工具类Ftputil.,一个实体类Kmconfig.一个测试类Test 下载地址:http://download.csdn.net/detail/myfmyfmyfmyf/669710 ...

  2. java使用Jsch实现远程操作linux服务器进行文件上传、下载,删除和显示目录信息

    1.java使用Jsch实现远程操作linux服务器进行文件上传.下载,删除和显示目录信息. 参考链接:https://www.cnblogs.com/longyg/archive/2012/06/2 ...

  3. [CentOs7]搭建ftp服务器(3)——上传,下载,删除,重命名,新建文件夹

    摘要 上篇文章介绍了如何为ftp添加虚拟用户,本篇将继续实践如何上传,下载文件. 上传 使用xftp客户端上传文件,如图所示 此时上传状态报错,查看详情 从错误看出是应为无法创建文件造成的.那么我们就 ...

  4. Java下载https文件上传到阿里云oss服务器

    Java下载https文件上传到阿里云oss服务器 今天做了一个从Https链接中下载音频并且上传到OSS服务器,记录一下希望大家也少走弯路. 一共两个类: 1 .实现自己的证书信任管理器类 /** ...

  5. MVC图片上传、浏览、删除 ASP.NET MVC之文件上传【一】(八) ASP.NET MVC 图片上传到服务器

    MVC图片上传.浏览.删除   1.存储配置信息 在web.config中,添加配置信息节点 <appSettings> <add key="UploadPath" ...

  6. java实现上传文件夹

    我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 首先我们需要了解的是上传文件三要素: 1.表单提交方式:post (get方式提交有大小 ...

  7. java servlet上传centos服务器

    前面一篇随笔说了Centos上架设javaWeb运行环境的方法,这篇主要讲打包上传服务器. 一.数据库连接文件.propeties 为了数据库安全,mysql3306端口访问我做了ip访问限制,由于m ...

  8. C#通过FTP账号上传、修改、删除文件 FTPClient

    下面类文件中,主要做的工作是:从ftp服务器上下载文件把本地文件替换.添加.或删除功能,在替换本地文件时会先备份一下本地的文件,若整个操作都完成了就会发出commit命令,表示全部替换成功.若中间操作 ...

  9. Java ftp上传文件方法效率对比

    Java ftp上传文件方法效率对比 一.功能简介: txt文件采用ftp方式从windows传输到Linux系统: 二.ftp实现方法 (1)方法一:采用二进制流传输,设置缓冲区,速度快,50M的t ...

  10. PHP文件上传至另一台服务器

    PHP程序上传文件时,想指定上传到另一台服务器. move_uploaded_file这个方法第二个参数指定的存放路径需要和php程序文件一个服务器,没办法指定其他服务器的地址,本人才疏学浅,哪位大哥 ...

随机推荐

  1. CSS关键词的值-currentColor关键字(当前颜色)

    currentColor关键字 currentColor关键字相当于一个CSS变量. currentColor关键字与CSS变量也是有区别的: (1)他只可以能接受<color>值的地方使 ...

  2. JavaWeb(七)Cookie,EL表达式,标准标签库

    Cookie Cookie概述 Cookie译为小型文本文件或小甜饼,Web应用程序利用Cookie在客户端缓存服务器端文件.Cookie是以键值对形式存储在客户端主机硬盘中,由服务器端发送给客户端, ...

  3. [2015-11-10]iis远程发布配置

    近期工作总结备忘,下次重新部署时再总结更新. 基本流程 一台初始化的win2012: 安装服务器角色,启用IIS,启用IIS管理服务,启用.Net相关框架等: 安装webdeploy工具(选择完整安装 ...

  4. JSP入门必读

    JSP基础知识:转自老师上课梳理的笔记,希望对大家有所帮助.有什么不妥当的地方还望大家批评指正. 特别适用于JSP入门的人员使用.1.JSP [1] 简介1.1 HTML    HTML擅长显示一个静 ...

  5. RGB转MIPI CSI芯片方案TC358746XBG

    型号:TC358746XBG功能:RGB888/666/565与MIPI CSI 互转通信方式:IIC/SPI分辨率:720p电源:3.3/1.2V封装形式:BGA72深圳有现货库存,价格有优势,样片 ...

  6. Linux安装解压缩版jdk

    #解压到指定目录 tar zxvf ./jdk-7-Linux-i586.tar.gz  -C /usr/lib/jvm 配置环境变量 #vi  /etc/profile 编辑文件,在最后添加: ex ...

  7. 工作常用git命令

    克隆项目 git clone gitssh地址 提交前的准备 git config user.name 您的中文名 git config user.email 公司邮箱 获取分支 #### 将远端分支 ...

  8. Spring 对缓存的抽象

    Cache vs. Buffer A buffer is used traditionally as an intermediate temporary store for data between ...

  9. .net asp mvc 如何从后端返回数据对象

    今天在做项目时,有一个需求:获取从控制器返回的数组对象,方法如下 public ActionResult GetAllFiles() { string dir = Server.MapPath(&qu ...

  10. 初入PHP,(for循环~水仙花数)

    找出100-999之间的所有"水仙花数".所谓水仙花数是指一个三位 数,各位数字的立方和等于该数本身.(如153次方=1的3次方+5的3次方+3的3次方)并输出这些数字 想想153 ...