sftp文件上传下载方法
随着信息化、数字化的发展,企业对数据安全及应用安全意识普遍加强,在数据文件传输过程中,一般建议使用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