大家如果熟悉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. BeanUtils.populate的作用

    它是在org.apache.commons.beanutils.BeanUtils包中的一个方法. 方法的作用:将一些 key-value 的值(例如 hashmap)映射到 bean 中的属性.   ...

  2. win8 VB6打开提示MSCOMCTL.ocx未注册

    从xp上复制相应的文件到win8相应的位置,如果是不可以,win8中反注册此控件,再注册此控件

  3. 《IT蓝豹》PlayNewsStandDemo资讯类新闻客户端框架

    PlayNewsStandDemo资讯类新闻客户端框架,支持tab滑动切换,当切换到最左边或者最后边的时候停止滑动 本例子切换tab的效果根据AccelerateDecelerateInterpola ...

  4. windows访问lnmp配置的虚拟域名

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://linuxzkq.blog.51cto.com/9379412/1630217 实 ...

  5. Struts2理解--动态方法和method属性及通配符_默认Action

    众所周知,默认条件下,在浏览器输入indexAction!execute.action,便会执行indexAction类里的execute方法,这样虽然方便,但可能带来安全隐患,通过url可以执行Ac ...

  6. C++的一些小的知识点

    1.初始化: 对于内置类型 ]; // 10个未初始化int ](); // 10个值初始化为0的int 对于自定义类型: 只要一调用new,那么编译器不仅仅给它分配内存,还调用它的默认构造函数初始化 ...

  7. 带锁的3D切割轮播图

    3D切割轮播图. 加入锁,限制点击太快次数 <!DOCTYPE html><html><head lang="en"> <meta cha ...

  8. HDU1075

    题目大意: 给你一本火星词典,每个火星单词对应一个英文单词. 然后给你一篇火星文章,要求你翻译成英文. 要求如下: 如果这个火星单词用英文单词可以表示,就翻译成英文,如果没有这个单词,就原样输出.遇到 ...

  9. XmlDocument解析Soap格式文件案例:

    private static string Analysis(string strResult) { var doc = new System.Xml.XmlDocument(); //加载soap文 ...

  10. 关于yii2框架活动记录activeRecord添加默认字段的问题

    平时使用sql的时候可以如下添加默认字段flag: "select a.*,0 as flag from user_info a", 对于yii2框架则需要这样: $query = ...