SFTP连接、创建多级目录、传文件
- SFTP连接
- 创建目录(逐级)
- 传输文件
- SFTP常用命令
通过FTP或SFTP传输指定格式的数据文件也是常见的需求,本文简单介绍一下常用的SFTP方法,另外需要注意的是,文中涉及的代码全都是在SpringBoot 服务中运行的。
SFTP连接
首先,需要导入依赖
<dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.54</version>
</dependency>
创建SFTP连接
public class SftpUtil{@Value("host")private String host;@Value("port")private String port;@Value("userName")private String userName;@Value("passWord")private String passWord;@Value("filePath")private String filePath;@Value("folder")private String folder;/***@description: 创建SFTP连接*@date: 2023/6/21 16:20*@param: [userName, passWord, host, port]*@return: com.jcraft.jsch.ChannelSftp*/private ChannelSftp setUpJsch(String userName,String passWord,String host,Integer port) throws JSchException {JSch jsch = new JSch();jsch.setKnownHosts("/home/srcu/.ssh/known_hosts");//找到自己服务器上的known_hosts文件路径Session jschSession = jsch.getSession(userName,host,port);//创建Session对象jschSession.setPassword(passWord);//设置密码jschSession.connect();//连接SFTPreturn (ChannelSftp) jschSession.openChannel("sftp");//返回ChannelSftp对象}
}
创建目录(逐级)
逐级进入指定目录,若目录不存在,则创建目录
/***@description: 逐级进入目录,若目录不存在则创建目录*@date: 2023/6/21 16:23*@param: [dirs, tempPath, length, index, sftp]*@return: void*/public void mkdirDir(String[] dirs, String tempPath, int length, int index, ChannelSftp sftp){//分割romoteDir后,首位为"",故而下标从1开始index++;if(index<length){//目录不存在,创建文件夹tempPath += "/" + dirs[index];}logger.info("检查目录 <" + tempPath + "> 是否存在");try {sftp.cd(tempPath);if (index < length){mkdirDir(dirs,tempPath,length,index,sftp);}} catch (SftpException e) {logger.info("创建目录 <" + tempPath + ">");try {sftp.mkdir(tempPath);//创建目录sftp.cd(tempPath);//进入目录} catch (SftpException e1) {e1.printStackTrace();logger.info("创建目录 <" + tempPath + ">失败,异常信息:{" + e1.getMessage() + "]");}mkdirDir(dirs,tempPath,length,index,sftp);}}
传输文件
使用获取到ChannelSftp对象,进入目标目录,并传输文件到目标目录下
/***@description: 上传文件到SFTP服务器*@date: 2023/6/21 16:25*@param: [userName, passWord, host, port, folder, filePath, fileName]*@return: void*/public void uploadFileUsingJsch(String userName,String passWord,String host,Integer port,String folder,String filePath,String fileName) throws JSchException, SftpException{ChannelSftp channelSftp = setUpJsch(userName,passWord,host,port);//获取ChannelSftp对象channelSftp.connect();//连接SFTPString localFile = filePath + fileName;//本地文件路径+文件名String remoteDir = folder + "TARGET/";//目标文件路径String dirs[]= remoteDir.split("/");mkdirDir(dirs,"",dirs.length,0,channelSftp);//逐级进入目录,无目录则创建目录channelSftp.put(localFile, remoteDir+fileName);//传文件channelSftp.exit();//退出SFTP服务器}
上述介绍的三个部分,都是SftpUtil类中的工具方法。
这三部分也是SFTP传输功能的核心逻辑。
SFTP常用命令
登录
sftp username@host
# 例:
sftp oracle@192.168.0.1
移除空文件夹
rmdir folder
删文件
rm fileName
传文件
put localPath/localFileName.txt remotePath/remoteFileName.txt
下载文件
get kcfb_cust_sign.OK localPath/#当前远程路径下文件下载到本地路径下
切换本地路径
lcd /srcu/webboot/ #切换本地路径