package mocha.framework.util;
/*
* @author Xiehj
* @version 2019年10月28日 上午9:37:28
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector; import org.apache.log4j.Logger; import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException; public class SftpTools {
private static final Logger log = Logger.getLogger(SftpTools.class); Session sshSession;
/**
* 链接sftp
*
* @param host
* 主机
* @param port
* 端口
* @param username
* 用户名
* @param password
* 密码
* @return
*/
public ChannelSftp connect(String host, int port, String username,
String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
sshSession = jsch.getSession(username, host, port);
//log.info("Session创建成功");
sshSession.setPassword(password);
//log.info("密码输入成功");
//sshSession.setConfig("kex","diffie-hellman-group1-sha1");
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
//log.info("链接参数设置成功");
sshSession.setConfig(sshConfig);
sshSession.connect();
//log.info("Session已连接");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
//log.info("连接到主机" + host);
} catch (Exception e) {
e.printStackTrace();
}
return sftp;
} /**
* 文件重命名
*
* @param directory 目录
* @param oldname 旧文件名
* @param newname 新文件名
* @param sftp
*/
public void renameFile(String directory, String oldname, String newname,
ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rename(oldname, newname);
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 文件上传
*
* @param directory 目录
* @param uploadFile 要上传的文件名
* @param sftp
*/
public void upload(String directory, String uploadFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
} catch (Exception e) {
e.printStackTrace();
}
} public void uploada(String directory,String sftpFileName,InputStream input, ChannelSftp sftp) throws SftpException{
try {
sftp.cd(directory); } catch (Exception e) {
}
sftp.put(input, sftpFileName);
}
/**
* 将输入流的数据上传到sftp作为文件。文件完整路径=basePath+directory
*
* @param basePath
* 服务器的基础路径
* @param directory
* 上传到该目录
* @param sftpFileName
* sftp端文件名
* @param input
* 输入流 throws SftpException
*/
public boolean upload(String directory, String sftpFileName,
InputStream input, ChannelSftp sftp) {
boolean ret = false;
try {
// sftp.cd(basePath);
sftp.cd(directory);
ret = true;
} catch (SftpException e) {
// 目录不存在,则创建文件夹
String[] dirs = directory.split("/");
String tempPath = "";
for (String dir : dirs) {
if (null == dir || "".equals(dir))
continue;
tempPath+="/"+dir;
//tempPath = dir;
try {
sftp.cd(tempPath);
ret = true;
} catch (SftpException ex) {
try {
sftp.mkdir(tempPath);
sftp.cd(tempPath);
ret = true;
} catch (SftpException e1) {
ret = false;
return ret;
} catch (Exception e1) {
ret = false;
return ret;
}
} catch (Exception e1) {
ret = false;
return ret;
}
}
ret = true;
} catch (Exception e1) {
ret = false;
return ret;
} try {
sftp.put(input, sftpFileName);// 上传文件
ret = true;
} catch (SftpException e) {
ret = false;
}
return ret;
} /**
* 文件下载
*
* @param directory 目录
* @param downloadFile 要下载文件名
* @param saveFile 保持的文件名
* @param sftp
*/
public void download(String directory, String downloadFile,
String saveFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下载文件
* @param directory 下载目录
* @param downloadFile 下载的文件名
* @return 字节数组
*/
public InputStream download(String directory, String downloadFile,ChannelSftp sftp) {
if (directory != null && !"".equals(directory)) {
try {
sftp.cd(directory);
InputStream is = sftp.get(downloadFile);
return is;
} catch (SftpException e) {
e.printStackTrace();
}
}
return null;
} /**
* 文件删除
*
* @param directory 目录
* @param deleteFile 要删除的文件名
* @param sftp
*/
public void delete(String directory, String deleteFile, ChannelSftp sftp) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
log.info("删除成功");
} catch (Exception e) {
log.info("删除失败");
e.printStackTrace();
}
} /**
* 列出目录下的文件
*
* @param directory 目录
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory, ChannelSftp sftp)
throws SftpException {
return sftp.ls(directory);
} //批量删除文件
public void delete(String directory, String[] fileNames, ChannelSftp aa) {
for (String fileName : fileNames) {
this.delete(directory, fileName, aa);
}
} /**
* 创建目录文件夹
* @param directory 要创建文件夹的位置路径
* @param fileName 要创建文件夹的名称
* @param sftp sftp连接
*/
//创建目录文件
public void mkdir(String directory,String fileName,ChannelSftp sftp){
try {
sftp.cd(directory);
sftp.mkdir(fileName);
log.info("文件夹创建成功");
} catch (Exception e) {
log.info("文件夹创建失败");
e.printStackTrace();
}
} public static void downLoadPic(String path,String downLoadFileName,String newFileName){ SftpTools sftpTools = new SftpTools();
//测试环境地址
String host="10.1.1.105";
int port=22;
String username="weblogic";
String password="1232343";
String directory="/weblogic/wls1036_x64/user_projects/domains/sasdomain/app/zyx_server/images/showpic/";
//建立sftp连接
ChannelSftp content= sftpTools.connect(host, port, username, password);
String saveFile = newFileName;
//下载文件
sftpTools.download(directory, downLoadFileName, saveFile, content); } /**
* 关闭连接 server
*/
public void logout(ChannelSftp sftp){
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
// log.info("sftp is closed already");
}
}
if (sshSession != null) {
if (sshSession.isConnected()) {
sshSession.disconnect();
// log.info("sshSession is closed already");
}
}
}
public static void main(String[] args) throws IOException{
SftpTools s = new SftpTools();
String host= "";
//String host= "";
int port= 22;
String username= "";
//String username= "";
String password= "";
//String password= "";
ChannelSftp connect = s.connect(host, port, username, password);
String directory = "/opt/";
//String fileName = "test3.txt";
//s.mkdir(directory, fileName, connect);
// Vector listFiles;
// try {
// listFiles = s.listFiles(directory, connect);
// for (int i = 0; i < listFiles.size(); i++) {
// /*log.info(listFiles.get(i));*/
// System.out.println(listFiles.get(i));
// }
// } catch (SftpException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
InputStream input = s.download(directory, "D_20200902.txt", connect);
File tempFile = new File("F:\\test");
if (!tempFile.exists()) {
tempFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(tempFile.getPath() + File.separator + "D_20200902.txt");
byte[] b = new byte[2048];
int len;
while ((len = input.read(b)) != -1) {
out.write(b, 0, len);
}
System.out.println("文件下载成功");
s.logout(connect);
}
}

以上代码导入后,需要加入一个jsch的jar包

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>

快去试试吧

java使用SFTP连接服务器下载,上传文件的更多相关文章

  1. golang使用sftp连接服务器远程上传、下载文件

    安装github.com/pkg/sftp 我们之前介绍了,golang如何通过ssh连接服务器执行命令,下面我们来如何上传文件,上传文件同样需要之前的ssh,但是除此之外还需要一个模块,直接使用go ...

  2. 从Linux服务器下载上传文件

    首先要确定好哪两种的连接:Linux常用的有centors和unbantu两种版本,PC端Mac和Windows 如果在两个Linux之间传输,或Linux和Mac之间传输可以使用scp命令,类似于s ...

  3. https 协议下服务器根据网络地址下载上传文件问题

    https 协议下服务器根据网络地址下载上传文件遇到(PKIX:unable to find valid certification path to requested target 的问题) 使用h ...

  4. Centos 6.4下使用VSFTPD无法正常连接与无法上传文件的问题解决

    发表于 2014 年 4 月 13 日 作者 SCKA 最近利用Linux搭建服务器 搭建FTP的时候决定使用VSFTP搭建,结果却出现了无法正常连接与无法上传文件等诸多问题 经过许久的努力,终于让V ...

  5. 2.3 利用FTP服务器下载和上传文件

    二.利用FTP服务器的下载文件 from ftplib import FTP from os.path import exists def getfile(file,site,dir,user=(), ...

  6. 使用root用户登录到AWS EC2服务器,上传文件到/var/www目录

    关键词 1.aws ec2中上传文件到/var/www目录(使用filezilla) 2.使用root用户登录aws ec2实例 上一篇随笔中记录了在aws ec2实例中部署apache服务器的过程, ...

  7. git下载/上传文件提示:git did not exit cleanly

    问题:git操作下载/上传文件,提示信息如下 TortoiseGit-git did not exit cleanly (exit code 1) TortoiseGit-git did not ex ...

  8. java:ssh连接服务器,实现本地文件上传和下载

    1.连接至服务器:ssh hp@10.10.17.16 -p 5555    下载文件:scp -r hp@10.10.17.16:/ccc(服务器路径,文件夹下所有文件)  /path(本地路径) ...

  9. python中使用paramiko模块并实现远程连接服务器执行上传下载

    paramiko模块 paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接. 因此,如果需要使用SSH从一个平台连接到另外一个平台,进行一系 ...

  10. ASP.NET、JAVA跨服务器远程上传文件(图片)的相关解决方案整合

    一.图片提交例: A端--提交图片 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string u ...

随机推荐

  1. 微信小程序隐藏页面滚动条

    开发小程序时,经常会碰到页面长度超过屏幕高度,然后下拉时会出现滚动条,对于一些有强迫症的人来说是不可忍受的. 网上看了好多,写的.都评论有起作用或者不起作用的. 我在这分享一个全局隐藏滚动条的方式. ...

  2. python 高级函数补充

    补充几个高级函数 zip 把两个可迭代内容生成一个可迭代的tuple元素类型组成的内容 # zip 案例 l1 = [ 1,2,3,4,5] l2 = [11,22,33,44,55] z = zip ...

  3. Python 项目:外星人入侵--第二部分

    外星人入侵 6.驾驶飞船 玩家左右移动飞船,用户按左或右按键时作出响应. 6.1响应按键 当用户在按键时,在python中注册一个事件,事件都是通过方法pygame.event.get()获取的. 在 ...

  4. 【Visual Leak Detector】源码调试 VLD 库

    说明 使用 VLD 内存泄漏检测工具辅助开发时整理的学习笔记.本篇介绍 VLD 源码的调试.同系列文章目录可见 <内存泄漏检测工具>目录 目录 说明 1. VLD 库源码调试步骤 1.1 ...

  5. Django4全栈进阶之路20 项目实战(在线报修):项目需求分析

    为了实现一个在线报修系统,您可以按照以下步骤进行: 创建Django项目和应用 使用Django的命令行工具创建一个Django项目,并在该项目中创建一个名为"RepairApp" ...

  6. Django中render()函数和redirect()函数

    render() 作用:render是渲染变量(结合一个给定的模板和一个给定的上下文字典)在模板中,通俗点将context的内容,加载进模板中定义的文件,通过浏览器渲染呈现. render()方法常用 ...

  7. Rocky 9 Linux 平台 vim 9.0 源码包编译安装踩坑记录

    目录 vim 9.0 部署准备环境 vim 9.0 源码包正式部署 vim 9.0 初体验 plug-vim 安装插件 在上一篇 <vim入门实战> 篇,我并没有介绍 Linux 平台源码 ...

  8. javascript中的错误类型

    javascript 中的错误类型: SyntaxError TypeError ReferenceError RangeError URLError Error SyntaxError 语法错误 / ...

  9. vscode 注释快捷键 一键注释和取消注释快捷键

    // 注释:ctrl+/ /**/ 注释:alt+shift+a

  10. K8S in Action 读后感(概念简介)

    一.K8S的用武之地 今天,大型单体应用正被逐渐拆分成小的.可独立运行的组件,我们称之为微服务.微服务彼此之间解耦,所以它们可以被独立开发.部署.升级.伸缩.这使得我们可以对每一个微服务实现快速迭代, ...