随着信息化、数字化的发展,企业对数据安全及应用安全意识普遍加强,在数据文件传输过程中,一般建议使用sftp协议进行文件传输,sftp文件操作脚本如下:

sftp操作主要有三种方式,分别是sftp客户端操作、sdk操作、操作系统命令操作,针对sdk方式。

一、sdk方式:

<!-- sftp集成jar -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
public class SftpUtils {

    private static final Logger logger = LoggerFactory.getLogger(SftpUtils.class);
private static final String SESSION_CONFIG_STRICT_HOST_KEY_CHECKING = "StrictHostKeyChecking"; /**
* 创建SFTP连接
* @return
* @throws Exception
*/
public static ChannelSftp createSftp(String username,String password,String host,int port) throws Exception {
JSch jsch = new JSch();
logger.info(("Try to connect sftp" + username + "@" + host + "], use password[" + password)); Session session = createSession(jsch,host, username, port);
session.setPassword(password);
session.connect(15000); logger.info("Session connected to {"+ host); Channel channel = session.openChannel("sftp");
channel.connect(); logger.info("Channel created to"+ host); return (ChannelSftp) channel;
}
/**
* 创建session
* @param jsch
* @param host
* @param username
* @param port
* @return
* @throws Exception
*/
private static Session createSession(JSch jsch, String host, String username, Integer port) throws Exception {
Session session = null; if (port <= 0) {
session = jsch.getSession(username, host);
} else {
session = jsch.getSession(username, host, port);
} if (session == null) {
throw new Exception(host + " session is null");
}
session.setConfig(SESSION_CONFIG_STRICT_HOST_KEY_CHECKING, "no");
return session;
} /**
* 关闭连接
* @param sftp
*/
public static void disconnect(ChannelSftp sftp) {
try {
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
} else if (sftp.isClosed()) {
//log.info("sftp is closed already");
System.out.println("sftp is closed already");
}
if (null != sftp.getSession()) {
sftp.getSession().disconnect();
}
}
} catch (JSchException e) {
e.printStackTrace();
}
} public static void download(String sftpUrl, String localFilePath, String sftpUsername, String sftpPassword, String sftpControlEncoding,String host,String port,String fileName) throws Exception {
String username = StringUtils.isEmpty(sftpUsername) ? ConfigConstants.getSftpUsername() : sftpUsername;
String password = StringUtils.isEmpty(sftpPassword) ? ConfigConstants.getSftpPassword() : sftpPassword;
String controlEncoding = StringUtils.isEmpty(sftpControlEncoding) ? ConfigConstants.getSftpControlEncoding() : sftpControlEncoding; logger.debug("SFTP connection url:{}, username:{}, password:{}, controlEncoding:{}, localFilePath:{}", sftpUrl, username, password, controlEncoding, localFilePath);
String remoteFilePath = sftpUrl.split(host + "/")[1].split("\\?")[0];
String encodefileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/")+1);
String dir = remoteFilePath.replace("/" + encodefileName,""); ChannelSftp channelSftp = createSftp(username,password,host,Integer.parseInt(port));
OutputStream outputStream = Files.newOutputStream(Paths.get(localFilePath));
channelSftp.cd(dir);
channelSftp.get(fileName,outputStream);
logger.debug("SFTP download success");
outputStream.flush();
outputStream.close();
disconnect(channelSftp);
} public static void main(String[] args) throws GalimatiasParseException {
String url = ("sftp://192.168.1.1/upload/test/demo/file.zip?sftp.username=sftpadmin&sftp.password=sftp&sftp.control.encoding=UTF-8");
String[] arrsy = url.split("192.168.1.1/");
System.out.println(url.split("192.168.1.1/"));
System.out.println(arrsy[1].split("\\?")[0]); String remoteFilePath = url.split("192.168.1.1" + "/")[1].split("\\?")[0];
}
}

二、客户端方式:

 1 #!/bin/bash
2
3 SFTP_HOST_IP=192.168.1.1
4 SFTP_HOST_PORT=22
5 SFTP_HOST_USER=sftpadmin
6 SFTP_HOST_PASSWD=sftp
7 SFTP_BASE_DIR=upload
8 SYSTEM_CODE=$1
9 UPLOAD_FILE=$2
10
11 UPLOAD_DIR=${SFTP_BASE_DIR}/${SYSTEM_CODE}
12 sftpPutFiles(){
13 ftpUser=$1
14 ftpPwd=$2
15 host=$3
16 port=$4
17 remoteDir=$5
18 uploadFile=$6
19 lftp -u ${ftpUser},${ftpPwd} sftp://${host}:${port} <<EOF
20 cd ${remoteDir}
21 mput ${uploadFile}
22 bye
23 EOF
24 }
25 echo "上传文件开始:" +`date`
26 sftpPutFiles $SFTP_HOST_USER $SFTP_HOST_PASSWD $SFTP_HOST_IP $SFTP_HOST_PORT $UPLOAD_DIR $UPLOAD_FILE
27 echo "上传文件结束:" +`date`
28
29 sftpGetFiles(){
30 ftpUser=$1
31 ftpPwd=$2
32 host=$3
33 port=$4
34 remoteDir=$5
35 downFile=$6
36 lftp -u ${ftpUser},${ftpPwd} sftp://${host}:${port} <<EOF
37 cd ${remoteDir}
38 set xfer:clobber on
39 mget ${downFile}
40 bye
41 EOF
42 }
43 echo "下载文件开始:" +`date`
44 sftpGetFiles $SFTP_HOST_USER $SFTP_HOST_PASSWD $SFTP_HOST_IP $SFTP_HOST_PORT $UPLOAD_DIR
45 echo "下载文件结束:" +`date`

三、操作系统命令方式:

1 上传sftp:
2 curl -T app.zip sftp://sftpuser:sftppasswd@127.0.0.1:12024/data/sftp_data/
3 下载sftp:
4 curl sftp://sftpuser:sftppasswd@127.0.0.1:12024/data/sftp_data/file.txt -o file.txt

sftp文件上传下载方法的更多相关文章

  1. 使用PuTTY时的文件上传下载方法

    如果你是个PuTTY重度用户,在使用ssh连上一个远端机器工作了好一阵子后,发现自己需要对 当前会话 上传/下载文件,要怎样才能简单快捷呢? 最简单的方式 最简单的方法: 安装WinSCP或者File ...

  2. 我的代码库-Java8实现FTP与SFTP文件上传下载

    有网上的代码,也有自己的理解,代码备份 一般连接windows服务器使用FTP,连接linux服务器使用SFTP.linux都是通过SFTP上传文件,不需要额外安装,非要使用FTP的话,还得安装FTP ...

  3. Java实现FTP与SFTP文件上传下载

    添加依赖Jsch-0.1.54.jar <!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency ...

  4. Jsch - java SFTP 文件上传下载

    使用Jsch上传.下载文件,核心步骤是:获取channel,然后使用get/put方法下载.上传文件 核心代码句: session = jSch.getSession(ftpUserName, ftp ...

  5. SFTP 文件上传下载工具类

    SFTPUtils.java import com.jcraft.jsch.*; import com.jcraft.jsch.ChannelSftp.LsEntry; import lombok.e ...

  6. Python Paramiko实现sftp文件上传下载以及远程执行命令

    一.简介 Paramiko模块是基于Python实现的SSH远程安全连接,用于SSH远程执行命令.文件传输等功能. 安装模块 默认Python没有自带,需要手动安装: pip3 install par ...

  7. java实现sftp文件上传下载

    /** * * @param filePath 文件全路径 * @param ftpPath 上传到目的端目录 * @param username * @param password * @param ...

  8. 使用ssh 登录Linux 文件上传下载方法

    最简单的方法: 安装WinSCP或者Filezilla, 启动该程序,然后自己输入输入主机名.端口.用户名.密码登录,然后在putty里面用pwd命令看看当前目录,再在WinSCP/Filezilla ...

  9. SFTP 文件上传下载引用代码

    http://sha1064616837.iteye.com/blog/2036996 http://www.cnblogs.com/itmanxgl/p/fe5d33512609fe540eb08a ...

  10. SFTP文件上传下载

    http://www.cnblogs.com/longyg/archive/2012/06/25/2556576.html  (转载)

随机推荐

  1. react路由过渡动画效果

    render() { return ( <div> <li><Link to="/home">Home</Link></li& ...

  2. react表单处理 非受控组件

    没有和state数据源进行关联的表单项,而是借助ref,使用元素DOM方式获取表单元素值 使用步骤 调用 React.createRef() 方法创建ref对象 将创建好的 ref 对象添加到文本框中 ...

  3. Ubuntu 更改鼠标滚轮速度

    1.安装imwheel sudo apt-get install imwheel 2.更改配置 sudo gedit ~/.imwheelrc 输入以下内容: ".*"None,  ...

  4. SonarQube代码质量扫描工具

    1.什么是SonarQube 既然是学习devops 运维流水线构建 开发 ↓ 测试 ↓ 运维 华为devops软件开发流水线文档 https://support.huaweicloud.com/re ...

  5. mysql报错 a foreign key constraint fails(外键约束错误)

    报错信息如下: (pymysql.err.IntegrityError) (1452, u'Cannot add or update a child row: a foreign key constr ...

  6. Spring源码——@Component,@Service是如何被解析?

    引言 在Spring中,Component.Service是在工作中经常被使用到的注解,为了加深对Spring运行机制的理解,今天我们一起来看一下Spring中对Component等注解的处理方式 C ...

  7. 增补博客 第三篇 python 英文统计

    编写程序实现对特定英文文章(文本文件)的单词数和有效行数的统计,其中要求空行不计数: def count_words_and_lines(file_path): word_count = 0 line ...

  8. oracle数据库与oracle实例

    1 oracle数据库分类 1.1 单租户数据库 ORACLE12C之前的oracle数据库都是单租户数据库.单租户数据库是独立和完整的数据库,包括ORACLE的元数据和应用的数据. 1.2 容器数据 ...

  9. JS模拟循环批量请求后台接口

    使用async, await处理异步请求.用Promise, setTimeout函数模拟后台接口 <!DOCTYPE html> <html> <script type ...

  10. 用pm2命令管理你的node项目

    文章目录 前言 安装 运行项目 pm2的命令 前言 我在服务器上运行node项目,使用命令nohup npm start &,结果关闭终端之后,进程就会停止,看来nohup也不是万能的后台运行 ...