SFTP的使用:

1.项目中需要引入jar包,下载地址:https://sourceforge.net/projects/jsch/files/jsch.jar/

2.需要下载SFTP服务器,下载地址:http://www.freesshd.com/?ctt=download

服务器的配置参考:http://www.cnblogs.com/zxx-813/p/7353806.html、http://jingyan.baidu.com/article/f7ff0bfc1ebd322e27bb1344.html

3.java代码(基于SFTP上传、下载文件(单个以及批量)):

ChannelSftp使用api:http://epaul.github.io/jsch-documentation/javadoc/index.html?com/jcraft/jsch/ChannelSftp.html

package test.sftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector; import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException; public class Test2 { private static ChannelSftp sftp = null; private static String host = "127.0.0.1";
private static int port = 22;
private static String username = "root";
private static String password = "root";
private static Session sshSession = null; /**
* main方法
* @param args
*/
public static void main(String[] args) {
ChannelSftp channelSftp = connect(host, port, username, password);
System.out.println(channelSftp); sftp = channelSftp; /**
* 上传单个文件
* @param remotePath:远程保存目录
* @param remoteFileName:保存文件名
* @param localPath:本地上传目录(以路径符号结束)
* @param localFileName:上传的文件名
* @return
*/
/*String remotePath = "/test1/"; //远程保存目录
String remoteFileName = "test.rar"; //保存文件名
String localPath = "C:\\Users\\lyc\\Desktop\\"; //本地上传目录(以路径符号结束)
String localFileName = "msftpsrvr.rar"; //reservation3.sql //上传的文件名
uploadFile(remotePath,remoteFileName,localPath,localFileName);*/ /**
* 下载单个文件
* @param directory:下载目录
* @param downloadFile:下载的文件
* @param saveFile:存在本地的路径
* @param sftp
*/
/*String directory = "/test/"; //下载目录
String downloadFile = "test.sql"; //下载的文件
String saveFile = "D:\\"; //存在本地的路径 download(directory,downloadFile,saveFile,sftp);*/ /**
* 批量上传文件
* @param remotePath:远程保存目录
* @param localPath:本地上传目录(以路径符号结束)
* @param del:上传后是否删除本地文件
* @return
*/
/*String remotePath = "/test/";
String localPath = "C:/Users/lyc/Desktop/aa/";
boolean del = false;
bacthUploadFile(remotePath,localPath,del);*/ /**
* 批量下载文件
* @param remotPath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
* @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\)
* @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
* @param fileEndFormat:下载文件格式(文件格式)
* @param del:下载后是否删除sftp文件
* @return
*/
String remotePath = "/test/";
String localPath = "C:/Users/lyc/Desktop/aa/";
String fileFormat = ""; //下载特定字符开头的文件
String fileEndFormat = "x"; //下载某一种格式的文件(下载特定字符结尾的文件)
boolean del = false;
batchDownLoadFile(remotePath,localPath,fileFormat,fileEndFormat,del); } /**
* 链接sftp服务器
* @param host 服务器地址
* @param port 服务器端口
* @param username 登录用户名
* @param password 登录密码
* @return
*/
public static ChannelSftp connect(String host,int port,String username,String password){
ChannelSftp sftp = null;
JSch jsch = new JSch();
try {
sshSession = jsch.getSession(username, host, port);
System.out.println("创建session!");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig); sshSession.connect();
System.out.println("session链接"); Channel channel = sshSession.openChannel("sftp");
channel.connect(); sftp = (ChannelSftp)channel;
System.out.println("成功链接到"+host+".");
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sftp; } /**
* 上传单个文件
* @param remotePath:远程保存目录
* @param remoteFileName:保存文件名
* @param localPath:本地上传目录(以路径符号结束)
* @param localFileName:上传的文件名
* @return
*/
public static boolean uploadFile(String remotePath, String remoteFileName,String localPath, String localFileName){
FileInputStream in = null;
try {
createDir(remotePath); //远程保存目录
File file = new File(localPath + localFileName); //本地上传目录(以路径符号结束)
in = new FileInputStream(file);
sftp.put(in, remoteFileName); //远程文件名 return true;
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (SftpException e){
e.printStackTrace();
}
finally
{
if (in != null){
try{
in.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return false;
} /**
* 创建目录
* @param createpath 远程保存目录
* @return
*/
public static boolean createDir(String createpath) {
try {
if (isDirExist(createpath)){ //文件存在
sftp.cd(createpath); //cd()更改当前远程目录
return true;
}
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()); //mkdir()创建一个新的远程目录
// 进入并设置为当前目录
sftp.cd(filePath.toString());
}
}
sftp.cd(createpath);
return true; }
catch (SftpException e){
e.printStackTrace();
} return false; } /**
* 判断目录是否存在
* @param directory
* @return
*/
public static boolean isDirExist(String directory){
boolean isDirExistFlag = false;
try{
SftpATTRS sftpATTRS = sftp.lstat(directory); //lstat()检索文件或目录的文件属性
isDirExistFlag = true;
System.out.println(sftpATTRS.isDir());
return sftpATTRS.isDir(); //isDir()检查此文件是否为目录
}catch (Exception e){
if (e.getMessage().toLowerCase().equals("no such file")){
isDirExistFlag = false;
}
}
return isDirExistFlag;
} /**
* 下载单个文件
* @param directory 下载目录
* @param downloadFile 下载的文件
* @param saveFile 存在本地的路径
* @param sftp
*/
public static void download(String directory, String downloadFile,
String saveFile, ChannelSftp sftp) {
try {
sftp.cd(directory); //下载目录
sftp.get(downloadFile,saveFile); //下载的文件 存在本地的路径
}catch (Exception e){
e.printStackTrace();
}
} /**
* 批量上传文件
* @param remotePath:远程保存目录
* @param localPath:本地上传目录(以路径符号结束)
* @param del:上传后是否删除本地文件
* @return
*/
public static boolean bacthUploadFile(String remotePath, String localPath,
boolean del)
{
try
{
/*connect();*/
File file = new File(localPath);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()
&& files[i].getName().indexOf("bak") == -1){
if (uploadFile(remotePath, files[i].getName(),
localPath, files[i].getName())
&& del){ //上传文件
deleteFile(localPath + files[i].getName()); //上传后删除本地文件
}
}
}
/*if (log.isInfoEnabled())
{
log.info("upload file is success:remotePath=" + remotePath
+ "and localPath=" + localPath + ",file size is "
+ files.length);
}*/
return true;
}catch (Exception e){
e.printStackTrace();
}finally{
disconnect();
}
return false; } /**
* 删除本地文件
* @param filePath
* @return
*/
public static boolean deleteFile(String filePath){
File file = new File(filePath);
if (!file.exists()){
return false;
} if (!file.isFile()){
return false;
}
boolean rs = file.delete();
/*if (rs && log.isInfoEnabled())
{
log.info("delete file success from local.");
}*/
return rs;
} /**
* 关闭连接
*/
public static void disconnect(){
if (sftp != null){
if (sftp.isConnected()){
sftp.disconnect();
/*if (log.isInfoEnabled())
{
log.info("sftp is closed already");
}*/
}
}
if (sshSession != null){
if (sshSession.isConnected()){
sshSession.disconnect();
/*if (log.isInfoEnabled())
{
log.info("sshSession is closed already");
}*/
}
}
} /**
* 批量下载文件
* @param remotPath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
* @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\)
* @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
* @param fileEndFormat:下载文件格式(文件格式)
* @param del:下载后是否删除sftp文件
* @return
*/
@SuppressWarnings("rawtypes")
public static List<String> batchDownLoadFile(String remotePath, String localPath,
String fileFormat, String fileEndFormat, boolean del)
{
List<String> filenames = new ArrayList<String>();
try
{
// connect();
//Vector v = listFiles(remotePath);
Vector v = sftp.ls(remotePath); //lstat(String path):列出远程目录的内容
// sftp.cd(remotePath);
if (v.size() > 0)
{
System.out.println("本次处理文件个数不为零,开始下载...fileSize=" + v.size());
Iterator it = v.iterator();
while (it.hasNext())
{
LsEntry entry = (LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
if (!attrs.isDir())
{
boolean flag = false;
String localFileName = localPath + filename;
fileFormat = fileFormat == null ? "" : fileFormat
.trim();
fileEndFormat = fileEndFormat == null ? ""
: fileEndFormat.trim();
// 三种情况
if (fileFormat.length() > 0 && fileEndFormat.length() > 0)
{
if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat))
{
flag = downloadFile(remotePath, filename,localPath, filename);
if (flag)
{
filenames.add(localFileName);
if (flag && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
else if (fileFormat.length() > 0 && "".equals(fileEndFormat))
{
if (filename.startsWith(fileFormat))
{
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag)
{
filenames.add(localFileName);
if (flag && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
else if (fileEndFormat.length() > 0 && "".equals(fileFormat))
{
if (filename.endsWith(fileEndFormat))
{
flag = downloadFile(remotePath, filename,localPath, filename);
if (flag)
{
filenames.add(localFileName);
if (flag && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
else
{
flag = downloadFile(remotePath, filename,localPath, filename);
if (flag)
{
filenames.add(localFileName);
if (flag && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
}
}
/*if (log.isInfoEnabled())
{
log.info("download file is success:remotePath=" + remotePath
+ "and localPath=" + localPath + ",file size is"
+ v.size());
}*/
}
catch (SftpException e)
{
e.printStackTrace();
}
finally
{
// this.disconnect();
}
return filenames;
} /**
* 下载单个文件
* @param remotPath:远程下载目录(以路径符号结束)
* @param remoteFileName:下载文件名
* @param localPath:本地保存目录(以路径符号结束)
* @param localFileName:保存文件名
* @return
*/
public static boolean downloadFile(String remotePath, String remoteFileName,String localPath, String localFileName)
{
FileOutputStream fieloutput = null;
try
{
// sftp.cd(remotePath);
File file = new File(localPath + localFileName);
// mkdirs(localPath + localFileName);
fieloutput = new FileOutputStream(file);
sftp.get(remotePath + remoteFileName, fieloutput);
/*if (log.isInfoEnabled())
{
log.info("===DownloadFile:" + remoteFileName + " success from sftp.");
}*/
return true;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (SftpException e)
{
e.printStackTrace();
}
finally
{
if (null != fieloutput)
{
try
{
fieloutput.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return false;
} /**
* 删除stfp文件
* @param directory:要删除文件所在目录
* @param deleteFile:要删除的文件
* @param sftp
*/
public static void deleteSFTP(String directory, String deleteFile)
{
try
{
// sftp.cd(directory);
sftp.rm(directory + deleteFile);
/*if (log.isInfoEnabled())
{
log.info("delete file success from sftp.");
}*/
}
catch (Exception e)
{
e.printStackTrace();
}
} /**
* 列出目录下的文件
*
* @param directory:要列出的目录
* @param sftp
* @return
* @throws SftpException
*/
/*@SuppressWarnings("rawtypes")
public static Vector listFiles(String directory) throws SftpException
{
return sftp.ls(directory);
}*/
}

SFTP的使用的更多相关文章

  1. SFTP 命令列表以备查询

    Available commands: ascii Set transfer mode to ASCII binary Set transfer mode to binary cd path Chan ...

  2. Winscp开源的SSH|SFTP

    WinSCP 主要功能 图形用户界面 多语言与 Windows 完美集成(拖拽, URL, 快捷方式) 支持所有常用文件操作,支持基于 SSH-1.SSH-2 的 SFTP 和 SCP 协议 支持批处 ...

  3. virtualbox设置共享文件夹代替sftp同步代码

    通常的开发场景: 代码放在virtualbox上运行,本地的IDE通过sftp实现和虚拟机的代码同步. 有 一个不能避免的问题是,当使用git时,如果装在virtualbox端,那么每次virtual ...

  4. 【荐】如何规划 Nginx 网站目录的权限(用户,用户组,ssh,sftp)

    从上一篇文章:PHP网站(nginx.php-fpm.mysql) 用户权限解析,可以学习了解到,nginx 和 php-fpm 的用户是如何运作的. 有个工作场景: 1.公司的一台 CentOS 服 ...

  5. 线程.FTP.SFTP.打包

    Windows就是多线程模式.每一个解决方案就是一个进程.一个进程下拥有多个线程. 简单点.单核的处理器不存在多线程.是CPU在每一个线程上切换处理.在人反应不过来的情况下完成同步的效果. 比如左手画 ...

  6. Linux下几种文件传输命令 sz rz sftp scp

    Linux下几种文件传输命令 sz rz sftp scp 最近在部署系统时接触了一些文件传输命令,分别做一下简单记录: 1.sftp Secure Ftp 是一个基于SSH安全协议的文件传输管理工具 ...

  7. linux 使用sftp命令

    1.使用SecureCRT软件进入sftp界面 2.常用的一些命令 服务器                 本地                   进入目录     cd lcd 查看目录结构    ...

  8. linux下如何使用sftp命令

    sftp 是一个交互式文件传输程式.它类似于 ftp, 但它进行加密传输,比FTP有更高的安全性.下边就简单介绍一下如何远程连接主机,进行文件的上传和下载,以及一些相关操作. 举例,如远程主机的 IP ...

  9. SFTP交互式文件传输

    sftp 是一个交互式文件传输程式.它类似于 ftp, 但它进行加密传输,比FTP有更高的安全性.下边就简单介绍一下如何远程连接主机,进行文件的上传和下载,以及一些相关操作. 举例,如远程主机的 IP ...

  10. 【SFTP】使用Jsch实现Sftp文件下载-支持断点续传和进程监控

    参考上篇文章: <[SFTP]使用Jsch实现Sftp文件下载-支持断点续传和进程监控>:http://www.cnblogs.com/ssslinppp/p/6248763.html  ...

随机推荐

  1. cocos2d-x 中XML解析与数据存储

    一不小心就玩了一周的游戏了.哎.玩的时候时间过得总是这么快... 于是今天决定看一下之前不怎么非常熟悉的XML;(之前做游戏时数据的储存用到过XML,但这块是还有一个同事在做,所以不怎么熟悉), 看了 ...

  2. 终结者:负载均衡之Nginx(一)

            相信非常多人都听过Nginx.这个小巧的东西能够和Apache及IIS相媲美.那么它有什么作用呢?一句话.它是一个减轻Web应用server(如Tomcat)压力和实现Web应用ser ...

  3. hunnu11544:小明的烦恼——找字符串

    Problem description   小明是个非常优秀的同学.他除了特别公正外,他也非常细心,当然老师肯定也知道,这不,老师又有事情找他帮忙了.老师每周都会给他一个字符串A.然后问小明" ...

  4. (六)api网关服务 zuul-过滤器

    开启上文服务: Zuul给我们的第一印象通常是这样:它包含了对请求的路由和过滤两个功能,其中路由功能负责将外部请求转发到具体的微服务实例上,是实现外部访问统一入口的基础.过滤器功能则负责对请求的处理过 ...

  5. linux进程控制函数详解

    进程控制 fork函数 创建一个子进程. pid_t fork(void); 失败返回-1:成功返回:① 父进程返回子进程的ID(非负) ②子进程返回 0 pid_t类型表示进程ID,但为了表示-1, ...

  6. Objective-C —内存管理(上)

    内存管理 一.为什么要进行内存管理 移动设备的内存极其有限,每个app所能占用的内存是有限制的 下列行为都会增加一个app的内存占用 创建一个OC对象 定义一个变量 调用一个函数或者方法 内存占用多大 ...

  7. SAS小记

    2011年8月13日 最近一直在跟着李东风的<统计软件教程>学习SAS,刚刚学完初等统计,感觉还没入门,找不到matlab编程时那种手顺的感觉.继续学习吧,加油!     最近用spss处 ...

  8. Kafka Consumer1

    本文的代码基于kafka的0.10.1的版本. 重新设计的原因 0.9以前的consumer是通过zookeeper来进行状态管理里的. 羊群效应 任何Broker或者Consumer的增减都会触发所 ...

  9. 详解JavaScript中的原型和继承-转自颜海镜大大

    本文将会介绍面向对象,继承,原型等相关知识,涉及的知识点如下: 面向对象与继承 CEOC OLOO 臃肿的对象 原型与原型链 修改原型的方式 面向对象与继承 最近学习了下python,还写了篇博文&l ...

  10. 在javascript中对于this指向的再次理解

    总所周知,function () {}函数体内的this对象指向的是调用该函数的对象,那么我们看一下这个例子 <script> var length = 3; function fn () ...