大家如果熟悉Linux系统话,对ssh,sftp,scp等命令非常熟悉。ssh是一个安全协议,用来在不同系统或者服务器之间进行安全连接。ssh 在连接和传送的过程中会加密所有的数据。

而今天我要介绍的一个jar包,是使用 JSCH。JSCH是一个纯粹的用Java实现SSH功能的java  library.

官方地址为:http://www.jcraft.com/jsch/
GitHub 地址为:https://github.com/vngx/vngx-jsch

maven配置如下:

 <!-- 加入sftp依赖包 -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.50</version>
</dependency>

对于这样的设计我们先设计一个FTP连接接口:

package com.xuanyuan.tools;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
/**
* FTP 接口
* @author Punk Lin
* @email lentr@sina.cn
* @date 2016年12月23日
*
*/
public interface FTPService { /**
* 登入
* @param host 登入主机地址
* @param userName 用户名
* @param password 密码
* @param port 端口
* @throws Exception
*/
public void login(String host, String userName, String password, int port) throws Exception; /**
* 退出
*/
public void logout(); /**
* 上传文件
*
* @param in
* 输入流
* @param remoteFilePath
* 远程文件绝对路径
* @throws Exception
*/
public void uploadFile(InputStream in, String remoteFilePath) throws Exception; /**
* 文件下载到本地
*
* @param sourceFilePath
* 远程文件绝对路径
* @param localFilePath
* 本地目录或绝对路径
* @throws Exception
*/
public void downloadFile(String sourceFilePath, String localFilePath)
throws Exception; /**
* 文件下载到输出流
*
* @param sourceFilePath
* 远程文件绝对路径
* @param out
* 输出流
* @throws Exception
*/
public void downloadFile(String sourceFilePath, OutputStream out) throws Exception; /**
* 删除文件
*
* @param directory
* 要删除文件所在目录
* @param deleteFile
* 要删除的文件
*
* @throws Exception
*/
public void deleteFile(String directory, String fileName) throws Exception; /**
* 列出目录下的文件,包括目录
*
* @param directory
* 要列出的目录
*
* @return list 文件名列表
*
* @throws Exception
*/
public Vector<?> listFiles(String directory) throws Exception; }

对于它的具体实现,则如下:

package com.xuanyuan.tools.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.util.Vector; 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 com.xuanyuan.tools.FTPService; public class SFTPServiceImpl implements FTPService {
/** sftp会话session */
protected Session sshSession = null; /** sftp通道 */
protected ChannelSftp sftp = null; @Override
public void login(String host, String userName, String password, int port)
throws Exception {
try {
JSch jsch = new JSch();
this.sshSession = jsch.getSession(userName, host, port);
this.sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
this.sshSession.setConfig(sshConfig);
this.sshSession.connect(20000);
this.sftp = (ChannelSftp) sshSession.openChannel("sftp");
this.sftp.connect();
this.sftp.setFilenameEncoding("UTF-8");
} catch (JSchException e) {
throw new RuntimeException("无法使用sftp登陆,请检查用户名密码或端口");
} } @Override
public void logout() {
if (this.sftp != null) {
this.sftp.disconnect();
this.sshSession.disconnect();
this.sftp = null;
this.sshSession = null;
}
} @Override
public void uploadFile(InputStream in, String remoteFilePath)
throws Exception {
try {
String filepath = remoteFilePath.substring(0,
remoteFilePath.lastIndexOf("/"));
String fileName = remoteFilePath.substring(
remoteFilePath.lastIndexOf("/") + 1,
remoteFilePath.length());
this.sftp.cd(filepath);
this.sftp.put(in, fileName, 0); } catch (SftpException e) {
throw new RuntimeException("上传文件时发生错误!请检查文件路径是否正确");
} } @Override
public void downloadFile(String sourceFilePath, String localFilePath)
throws Exception {
File file = new File(localFilePath);
FileOutputStream out = null;
try {
if (file.isDirectory()) {
this.sftp.get(sourceFilePath, localFilePath);
} else {
out = new FileOutputStream(file);
this.sftp.get(sourceFilePath, out);
}
} catch (SftpException e) {
throw new RuntimeException("下载文件时发生错误!请检查文件路径是否正确");
} finally {
if (out != null)
out.close();
}
} @Override
public void downloadFile(String sourceFilePath, OutputStream out)
throws Exception {
try {
this.sftp.get(sourceFilePath, out);
} catch (SftpException e) {
throw new RuntimeException("下载文件时发生错误!请检查文件路径是否正确");
} } @Override
public void deleteFile(String directory, String fileName) throws Exception {
this.sftp.cd(directory);
this.sftp.rm(fileName); } @Override
public Vector<?> listFiles(String directory) throws Exception {
return this.sftp.ls(directory);
} }

至此工具完成了。这样我们也可以通过这个工具提供,网页这样的上传道服务器。

相信别人往往比相信自己更简单,是恐于未知,还是惧于无力。

如何使用jcraft 模拟SFTP登陆的更多相关文章

  1. 模拟Post登陆带验证码的网站

    前言: 作者在一个项目需求 模拟用户登陆,获取该用户的订单记录. 该系统需要用户名,密码,验证码 (验证码为正楷的数字4位),于是参考网络一些文章,并进行了很多测试,总结步骤如下: 步骤1 : 通过h ...

  2. curl模拟自动登陆&采集网页数据

    <!DOCTYPE> <html> <head> <meta http-equiv="Content-Type" content=&quo ...

  3. python urllib2 模拟网站登陆

    python urllib2 模拟网站登陆 1. 可用浏览器先登陆,然后查看网页源码,分析登录表单 2. 使用python urllib2,cookielib 模拟网页登录 import urllib ...

  4. HttpClient4的使用,模拟浏览器登陆新浪微博,发表微博和文字+图片微博

    HttpClient4,最原始的需求就是使用其来模拟浏览器想服务器发起http请求,当然,他的功能不止于此,但是我需要的就是这个功能而已,jdk也有其自带的类似的api:UrlConnection,效 ...

  5. Java模拟新浪微博登陆抓取数据

    前言:  兄弟们来了来了,最近有人在问如何模拟新浪微博登陆抓取数据,我听后默默地抽了一口老烟,暗暗的对自己说,老汉是时候该你出场了,所以今天有时间就整理整理,浅谈一二. 首先:  要想登陆新浪微博需要 ...

  6. Python模拟微博登陆,亲测有效

    今天想做一个微博爬个人页面的工具,满足一些不可告人的秘密.那么首先就要做那件必做之事!模拟登陆-- 代码是参考了:https://www.douban.com/note/201767245/ 我对代码 ...

  7. C# 模拟网站登陆

    实现此功能首先需要借助一些抓包工具,对相应的网站登陆过程进行分析,此过程根据网站的不同,可能复杂,也可能很简单.常用的抓包工具FF下FireBug和IE下的HttpWatch.这两个工具很强大,以此工 ...

  8. Golang模拟用户登陆,突破教务系统

    目录 一.Golang模拟用户登陆,突破教务系统 1.1 请求登陆页面 1.2 抓包分析登陆请求 1.3 golang使用js引擎合成salt 1.4 模拟表单提交,完成登陆 1.5 进入成绩查询页, ...

  9. [Javascript] 爬虫 模拟新浪微博登陆

     概述: 由于业务需要,要编写爬虫代码去爬去新浪微博用户的信息. 虽然在网上能找到不少信息,但由于新浪微博改版,其登陆机制进行了修改,故很多老的文章就不适合用了. 经过一番摸索,成功模拟新浪微博的登陆 ...

随机推荐

  1. WAP端 经验记录1

    1. 点击元素触发事件的先后顺序:touchstart, touchend, mousedown, mouseup, click 2. Animate 的 stop 问题问题:手机端由于用 CSS3 ...

  2. SQL指南-SELECT语句

    SELECT 语句 SELECT 语句用于从表中筛选数据.列表结果存储于一个结果表中(称作result-set) 语法 SELECT column_name(s)FROM table_name 注意: ...

  3. ANdroid5.0不能隐式启动service,必须显示,解决办法,加服务端包名

    Intent intent = new Intent(); intent.setAction("com.viaembedded.veonvif.RemoteService");// ...

  4. DeepLearning学习(1)--多层感知机

    想直接学习卷积神经网络,结果发现因为神经网络的基础较弱,学习起来比较困难,所以准备一步步学.并记录下来,其中会有很多摘抄. (一)什么是多层感知器和反向传播 1,单个神经元 神经网络的基本单元就是神经 ...

  5. Vim命令合集

    1.模式切换 三种模式:命令模式,输入模式,底行模式 命令模式与输入模式之间的切换:i esc 命令模式与底行模式的切换:shift + :  esc 2. 插入 i:在当前字符的左边插入 I:在当前 ...

  6. python项目实践一:即时标记

    转自:http://www.code123.cc/1317.html 这是<python基础教程>后面的实践,照着写写,一方面是来熟悉python的代码方式,另一方面是练习使用python ...

  7. jquery版本清单

    PM> Install-Package jQuery -Version 1.11.2 jQuery 2.1.3 (latest stable) 315444 Wednesday, Decembe ...

  8. jquery里面的名称冲突解决方法

    jQuery 使用 $ 符号作为 jQuery 的简介方式. 某些其他 JavaScript 库中的函数(比如 Prototype)同样使用 $ 符号. jQuery 使用名为 noConflict( ...

  9. PCIE学习

    PCIe在传输中用8b/10b编码,所以单PCEe2.0的有效带度是4Gb/s x2模式将用于内部接口而非插槽模式 PCIe卡能使用在至少与之传输通道相当的插槽上(例如x1接口的卡也能工作在x4或x1 ...

  10. python中获取今天昨天和明天的日期

    import datetime today = datetime.date.today()oneday = datetime.timedelta(days=1)yesterday = today-on ...