Sftp工具类(跨服务器传输)

Posted njly

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sftp工具类(跨服务器传输)相关的知识,希望对你有一定的参考价值。

 package com.damddos.waf.utils;
 
 import com.jcraft.jsch.*;
 import org.apache.commons.io.IOUtils;
 
 import java.io.IOException;
 import java.io.InputStream;
 import java.nio.charset.Charset;
 import java.util.Properties;
 
 /**
  * sftp工具类
  *
  * @author liYang
  * @date 2023/04/10
  */
 public class SftpUtil 
     private static JSch jsch;
     private static Session session = null;
     private static Channel channel = null;
     private static ChannelSftp channelSftp = null;
 
     //服务器用户名
     private String ftpUserName;
 
     //服务器密码
     private String ftpPassword;
 
     //服务器ip
     private String ftpHost;
 
     //服务器端口
     private String ftpPort;
 
     public SftpUtil() 
     
 
     public SftpUtil(String ftpUserName, String ftpPassword, String ftpHost, String ftpPort) 
         this.ftpUserName = ftpUserName;
         this.ftpPassword = ftpPassword;
         this.ftpHost = ftpHost;
         this.ftpPort = ftpPort;
     
 
     /**
      * 开启连接
      */
     public ChannelSftp connect() 
         jsch = new JSch();
         try 
             // 根据用户名、主机ip、端口号获取一个Session对象
             session = jsch.getSession(ftpUserName, ftpHost, Integer.valueOf(ftpPort));
             // 设置密码
             session.setPassword(ftpPassword);
             Properties config = new Properties();
             config.put("StrictHostKeyChecking", "no");
             // 为Session对象设置properties
             session.setConfig(config);
             // 设置连接超时为5秒
             session.setTimeout(100 * 50);
             // 通过Session建立连接
             session.connect();
             // 打开SFTP通道
             channel = session.openChannel("sftp");
             // 建立SFTP通道的连接
             channel.connect();
             channelSftp = (ChannelSftp) channel;
          catch (JSchException e) 
             e.printStackTrace();
         
         return channelSftp;
     
 
     /**
      * 关闭连接
      */
     public void close() 
         if (channel != null) 
             channel.disconnect();
         
         if (session != null) 
             session.disconnect();
         
     
 
     /**
      * 判断文件夹路径是否存在
      *
      * @param directory 文件夹路径,如:/root/test/saveFile/
      */
     public boolean isDirExist(String directory) 
         directory = null != directory && directory.endsWith("/") ? directory : directory + "/";
         boolean dirExist = false;
         try 
             SftpATTRS sftpATTRS = channelSftp.lstat(directory);
             dirExist = sftpATTRS.isDir();
          catch (Exception e) 
             if (e.getMessage().equalsIgnoreCase("no such file")) 
                 dirExist = false;
             
         
         return dirExist;
     
 
     /**
      * 创建一个文件夹(若整个路径都不存在会依次创建,若改路径已经存在则不会创建)
      *
      * @param createpath 要创建的文件夹路径,如:/root/test/saveFile/
      * @throws SftpException
      */
     public void createDir(String createpath) 
         createpath = null != createpath && createpath.endsWith("/") ? createpath : createpath + "/";
         if (!isDirExist(createpath)) 
             StringBuilder builder = new StringBuilder("/");
             String pathArry[] = createpath.split("/");
             for (String dir : pathArry) 
                 if (!dir.equals("")) 
                     builder.append(dir);
                     builder.append("/");
                     try 
                         String path = builder.toString();
                         if (!isDirExist(path)) 
                             // 建立目录
                             channelSftp.mkdir(path);
                         
                      catch (SftpException e) 
                         e.printStackTrace();
                     
                 
             
         
     
 
     /**
      * 删除文件
      *
      * @param deleteFile 要删除的文件路径,如:/root/test/saveFile/mylog.log
      */
     public void deleteFile(String deleteFile) 
         try 
             channelSftp.rm(deleteFile);
          catch (Exception e) 
             e.printStackTrace();
         
     
 
     /**
      * 文件上传
      *
      * @param fileStram 文件输入流
      * @param upToPath  要上传到的文件夹路径
      * @param fileName  上传后的文件名
      */
     public void uploadFile(InputStream fileStram, String upToPath, String fileName) 
         upToPath = null != upToPath && upToPath.endsWith("/") ? upToPath : upToPath + "/";
         try 
             channelSftp.put(fileStram, upToPath + fileName);
          catch (SftpException e) 
             e.printStackTrace();
         
     
 
     /**
      * 文件下载
      *
      * @param downlownPath 要下载的文件的所在文件夹路径
      * @param fileName     文件名
      * @return download  返回下载的文件流
      */
     public InputStream downloadFile(String downlownPath, String fileName) 
         downlownPath = null != downlownPath && downlownPath.endsWith("/") ? downlownPath : downlownPath + "/";
         InputStream download = null;
         try 
             download = channelSftp.get(downlownPath + fileName);
          catch (SftpException e) 
             e.printStackTrace();
         
         return download;
     
 
 
     /**
      * 执行linux命令
      *
      * @param order 要执行的命令,(如,打印指定目录下的文件信息: ls -a /usr/local/kkFileView/kkFileView-4.0.0/bin/)
      * @return result  执行后返回的结果
      */
     public String excutOrder(String order) 
         String result = "";
         try 
             ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
             channelExec.setCommand(order);
             channelExec.setErrStream(System.err);
             channelExec.connect();
             InputStream in = channelExec.getInputStream();
             result = IOUtils.toString(in, Charset.defaultCharset());
          catch (JSchException e) 
             e.printStackTrace();
          catch (IOException e) 
             e.printStackTrace();
         
         return result;
     
 
 

项目需要。

Linux命令之sftp - 安全文件传输命令行工具

用途说明

sftp命令可以通过ssh来上传和下载文件,是常用的文件传输工具,它的使用方式与ftp类似,但它使用ssh作为底层传输协议,所以安全性比ftp要好得多。

常用方式

格式:sftp <host>

通过sftp连接<host>,端口为默认的22,用户为Linux当前登录用户。

格式:sftp -oPort=<port> <host>

通过sftp连接<host>,指定端口<port>,用户为Linux当前登录用户。

格式:sftp <user>@<host>

通过sftp连接<host>,端口为默认的22,指定用户<user>。

格式:sftp -oPort=<port> <user>@<host>

通过sftp连接<host>,端口为<port>,用户为<user>。

 

 Xshell工具可以按住Ctrl + Alt + F打开本机

sftp连接成功之后常用操作命令如下:

help/? 打印帮助信息。

pwd   查看远程服务器当前目录;

lpwd  查看本地系统的当前目录。

cd <dir>   将远程服务器的当前目录更改为<dir>;

lcd <dir>  将本地系统的当前目录更改为<dir>。

ls 显示远程服务器上当前目录的文件名;

ls -l  显示远程服务器上当前目录的文件详细列表;

ls <pattern> 显示远程服务器上符合指定模式<pattern>的文件名;

ls -l <pattern>  显示远程服务器上符合指定模式<pattern>的文件详细列表。

lls 显示本地系统上当前目录的文件名;

lls的其他参数与ls命令的类似。

get <file> 下载指定文件<file>;

get <pattern> 下载符合指定模式<pattern>的文件。

put <file> 上传指定文件<file>;

put <pattern> 上传符合指定模式<pattern>的文件。

progress 切换是否显示文件传输进度。

mkdir <dir> 在远程服务器上创建目录;

lmkdir <dir> 在本地系统上创建目录。

exit/quit/bye 退出sftp。

! 启动一个本地shell。

! <commandline> 执行本地命令行。

其他命令还有:chgrp, chmod, chown, ln, lumask, rename, rm, rmdir, symlink, version

以上是关于Sftp工具类(跨服务器传输)的主要内容,如果未能解决你的问题,请参考以下文章

Linux命令之sftp - 安全文件传输命令行工具

CentOS7.6服务器搭建SFTP服务及JAVA工具类

sftp工具类

php 如何通过连接sftp并下载sftp服务器指定目录下的所有文件到本地?

centos下配置sftp且限制用户访问目录

sftp服务