SFTP & FTP Upload
简述
>> FTP:
1. Install FTP service on Linux(Red Hat) as root user
[root]# yum install ftp
2. Configure FTP as root user
a) Be clear with below properties, and configure them in the file /etc/vsftpd/vsftpd.conf as root user
# Uncomment this to allow local users to log in.
local_enable=YES
# Uncomment this to enable any form of FTP write command.
write_enable=YES
# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
local_umask=022
# When "listen" directive is enabled, vsftpd runs in standalone mode and
# listens on IPv4 sockets. This directive cannot be used in conjunction
# with the listen_ipv6 directive.
listen=YES
userlist_enable=YES
userlist_deny=NO
#Passive mode not allowed
pasv_enable=NO
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=YES
#Specify listen port
listen_port=21
#Allow active mode
port_enable=YES
b) Make sure ftp user exists in the file /etc/vsftpd/user_list as root user
3. Restart FTP service as root user
[root]# service vsftpd restart
>> SFTP:
Generally SFTP service is installed/configured on Linux OS
>> Please refer to below info:
假设ftpserver没有开通20。可是FTPserver开通了高位随机port,则必须使用被动模块,同一时候也能够使用主动模式。
假设客服端的防火墙关闭了port的主动接收功能,则无法使用主动模式。但能够使用被动模块,这也是被动模块存在的原因。
一般公司内部为了server安全点。使用主动模式,但对client有些要求,能够接受port的请求数据。
PORT(主动)方式的连接过程是:
client向server的FTPport(默认是21)发送连接请求,server接受连接。建立一条命令链路。
当须要传送数据时,client在命令链路上用PORT命令告诉server:“我打开了****port,你过来连接我”。
于是server从20port向client的****port发送连接请求,建立一条数据链路来传送数据。
PASV(被动)方式的连接过程是:
client向server的FTPport(默认是21)发送连接请求,server接受连接。建立一条命令链路。
当须要传送数据时。server在命令链路上用PASV命令告诉client:“我打开了****port,你过来连接我”。
于是client向server的****port发送连接请求。建立一条数据链路来传送数据。
从上面能够看出。两种方式的命令链路连接方法是一样的,而数据链路的建立方法就全然不同。
【FTP Upload】
package shuai.study.ftp; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator; /**
* @Description: FTP Upload
* @author Zhou Shengshuai
* @date 2014年8月5日 下午2:37:57
*
*/
public class FtpUpload {
private static final Logger logger = LogManager.getLogger(FtpUpload.class); static {
System.setProperty("FTP_LOG", "/home/tmp/log");
DOMConfigurator.configure("/home/tmp/configuration/log4j.xml");
} private static String hostname = "192.168.0.1";
private static int ftpPort = 21; private static String ftpUsername = "ftpuser";
private static String ftpPassword = "ftpPassword"; private static String remoteDirectoryString = "/upload";
private static File localDirectory = new File("/home/tmp/local"); public static Set<File> upload(Collection<File> localFileCollection) {
Set<File> localFileSet = new HashSet<File>(); FTPClient ftpClient = connect(hostname, ftpPort, ftpUsername, ftpPassword, remoteDirectoryString); if (ftpClient != null && ftpClient.isConnected()) {
Iterator<File> localFileIterator = localFileCollection.iterator(); while (localFileIterator.hasNext()) {
File localFile = localFileIterator.next();
if (upload(ftpClient, localFile)) {
// Add localFile into localFileSet after upload successfully, and will delete these local files
localFileSet.add(localFile);
}
}
} disconnect(ftpClient); return localFileSet;
} private static boolean upload(FTPClient ftpClient, File localFile) {
boolean storeFileFlag = false; if (localFile != null && localFile.isFile()) {
InputStream fileInputStream = null; try {
fileInputStream = new FileInputStream(localFile); storeFileFlag = ftpClient.storeFile(localFile.getName(), fileInputStream); if (storeFileFlag) {
logger.info("Upload local file " + localFile + " to remote directory " + ftpUsername + "@" + hostname + ":" + remoteDirectoryString + " via FTP");
} else {
logger.error("Fail to upload local file " + localFile + " to remote directory " + ftpUsername + "@" + hostname + ":" + remoteDirectoryString + " via FTP");
}
} catch (IOException ioe) {
logger.error("FTP Upload Exception", ioe);
} finally {
IOUtils.closeQuietly(fileInputStream);
}
} return storeFileFlag;
} private static FTPClient connect(String hostname, int ftpPort, String ftpUsername, String ftpPassword, String remoteDirectoryString) {
FTPClient ftpClient = new FTPClient(); try {
ftpClient.connect(hostname, ftpPort);
logger.info("FTP Connected " + hostname + ":" + ftpPort); ftpClient.login(ftpUsername, ftpPassword);
logger.info("FTP Logined as " + ftpUsername); // ftpClient.enterLocalPassiveMode();
// if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
// logger.error("FTP Response Unsuccessfully");
// disconnect(ftpClient);
// } if (ftpClient.makeDirectory(remoteDirectoryString)) {
logger.info("FTP Directory Made " + remoteDirectoryString);
} ftpClient.changeWorkingDirectory(remoteDirectoryString);
logger.info("FTP Working Directory Changed as " + remoteDirectoryString); // ftpClient.setBufferSize(1024);
// ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
} catch (IOException ioe) {
logger.error("FTP Connection Exception", ioe);
} return ftpClient;
} private static void disconnect(FTPClient ftpClient) {
if (ftpClient != null) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException ioe) {
logger.error("FTP Disconnection Exception", ioe);
}
} logger.info("FTP Disconnected");
} private static void delete(Set<File> exportCucFileSet) {
Iterator<File> exportCucFileIterator = exportCucFileSet.iterator(); while (exportCucFileIterator.hasNext()) {
File exportCucFile = exportCucFileIterator.next(); if (FileUtils.deleteQuietly(exportCucFile)) {
logger.info("Delete local file " + exportCucFile + " after FTP upload");
} else {
logger.error("Fail to delete local file " + exportCucFile + " after FTP upload");
}
}
} public static void main(String[] args) {
Collection<File> localFileCollection = FileUtils.listFiles(localDirectory, new String[] { "gz", "GZ", "xml", "XML", "zip", "ZIP" }, true); Set<File> localFileSet = FtpUpload.upload(localFileCollection); delete(localFileSet);
}
}
【SFTP Upload】
package shuai.study.sftp; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties; import org.apache.commons.io.FileUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator; import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException; /**
* @Description: SFTP Upload
* @author Zhou Shengshuai
* @date 2014年8月1日 下午2:37:57
*
*/
public class SftpUpload {
private static final Logger logger = LogManager.getLogger(SftpUpload.class); static {
System.setProperty("FTP_LOG", "/home/tmp/log");
DOMConfigurator.configure("/home/tmp/configuration/log4j.xml");
} private static String hostname = "192.168.0.1";
private static int sftpPort = 22; private static String sftpUsername = "ftpuser";
private static String sftpPassword = "ftpPassword"; private static String remoteDirectoryString = "/upload";
private static String localDirectoryString = "/home/tmp/local"; /**
* @Description: Upload
*/
public static void upload() {
File localDirectory = new File(localDirectoryString); if (localDirectory.exists()) {
ChannelSftp sftp = connect(hostname, sftpPort, sftpUsername, sftpPassword); Collection<File> localFileCollection = FileUtils.listFiles(localDirectory, new String[] { "gz", "GZ", "xml", "XML", "zip", "ZIP" }, true);
Iterator<File> localFileIterator = localFileCollection.iterator(); while (localFileIterator.hasNext()) {
File localFile = localFileIterator.next();
logger.info("Local File: " + localFile); if (sftp != null && sftp.isConnected()) {
upload(remoteDirectoryString, localFile, sftp);
}
} disconnect(sftp);
} else {
logger.warn("The Local Directory " + localDirectoryString + " doesn't exist");
}
} /**
* @Description: SFTP Upload
*
* @param remoteDirectoryString
* Remote CM Directory
* @param localFile
* Local CM File
* @param sftp
* ChannelSftp
*/
public static void upload(String remoteDirectoryString, File localFile, ChannelSftp sftp) {
logger.info("Remote Directory: " + remoteDirectoryString); try {
sftp.cd(remoteDirectoryString);
sftp.put(new FileInputStream(localFile), localFile.getName()); FileUtils.deleteQuietly(localFile); logger.info("Upload Local File " + localFile + " via SFTP");
} catch (FileNotFoundException fnfe) {
logger.error("File Not Found Exception", fnfe);
} catch (SftpException se) {
logger.error("SFTP Upload Exception", se);
}
} /**
* @Description: SFTP Connection
*
* @param hostname
* SFTP HOST
* @param sftpPort
* SFTP PORT
* @param sftpUsername
* SFTP USERNAME
* @param sftpPassword
* SFTP PASSWORD
*
* @return ChannelSftp
*/
public static ChannelSftp connect(String hostname, int sftpPort, String sftpUsername, String sftpPassword) {
JSch jsch = new JSch();
Properties sshConfig = new Properties(); Channel channel = null; try {
Session session = jsch.getSession(sftpUsername, hostname, sftpPort);
logger.info("Session Created"); session.setPassword(sftpPassword); sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
// session.setTimeout(60000);
// session.setServerAliveInterval(90000); session.connect();
logger.info("Session Connected"); channel = session.openChannel("sftp");
logger.info("Channel Opened"); channel.connect();
logger.info("Channel Connected");
} catch (JSchException je) {
logger.error("SFTP Exception", je);
} return (ChannelSftp) channel;
} /**
* @Description: Disconnect SFTP
*
* @param sftp
* ChannelSftp
*/
public static void disconnect(ChannelSftp sftp) {
if (sftp != null) {
try {
sftp.getSession().disconnect();
} catch (JSchException je) {
logger.error("SFTP Disconnect Exception", je);
} sftp.disconnect();
}
} /**
* @Description: Main Thread
* @param args
*/
public static void main(String[] args) {
SftpUpload.upload();
}
}
【Shell FTP Upload】
#!/bin/bash HOST="192.168.0.1"
USER="ftpuser"
PASS="ftpPassword" LOCAL_DIR="/home/tmp/local"
REMOTE_DIR="/home/<ftp-user>/remote" ftp -v -n << EOF
open ${HOST}
user ${USER} ${PASS}
prompt off
passive off
binary
lcd ${LOCAL_DIR}
cd ${REMOTE_DIR}
mput *
close
bye
EOF
SFTP & FTP Upload的更多相关文章
- Java使用SFTP和FTP两种连接方式实现对服务器的上传下载 【我改】
[]如何区分是需要使用SFTP还是FTP? []我觉得: 1.看是否已知私钥. SFTP 和 FTP 最主要的区别就是 SFTP 有私钥,也就是在创建连接对象时,SFTP 除了用户名和密码外还需要知道 ...
- 小白的linux笔记4:几种共享文件方式的速度测试——SFTP(SSH)/FTP/SMB
测试一下各个协议的速度,用一个7205M的centos的ISO文件上传下载.5Gwifi连接时,本地SSD(Y7000)对服务器的HDD: smb download 23M/s(资源管理器) smb ...
- Sftp和ftp 差别、工作原理等(汇总ing)
Sftp和ftp over ssh2的差别 近期使用SecureFx,涉及了两个不同的安全文件传输协议: -sftp -ftp over SSH2 这两种协议是不同的.sftp是ssh内含的协议,仅仅 ...
- 浅谈SFTP和FTP的区别
一.适用场景 我们平时习惯了使用ftp来上传下载文件,尤其是很多Linux环境下,我们一般都会通过第三方的SSH工具连接到Linux,但是当我们需要传输文件到Linux服务器当中,很多人习惯用ftp来 ...
- Linux 下上传下载命令,SCP,SFTP,FTP
scp 帮助命令: man scp scp功能: 下载远程文件或者目录到本地, 如果想上传或者想下载目录,最好的办法是采用tar压缩一下,是最明智的选择. 从远程主机 下载东西到 本地电脑 拷贝文件命 ...
- sftp与ftp的区别
SFTP和FTP非常相似,都支持批量传输(一次传输多个文件),文件夹/目录导航,文件移动,文件夹/目录创建,文件删除等.但还是存在着差异,下面我们来看看SFTP和FTP之间的区别. 1. 安全通道FT ...
- sftp,ftp文件下载
一.sftp工具类 package com.ztesoft.iotcmp.util; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsc ...
- linux命令-sftp(模拟ftp服务)和scp(文件异地直接复制)
1)sftp sftp是模拟ftp的服务,使用22端口 针对远方服务器主机 (Server) 之行为 变换目录到 /etc/test 或其他目录 cd /etc/testcd PATH 列出目前所在目 ...
- Linux 远程连接sftp与ftp
linux sftp远程连接命令 sftp -oPort=60001 root@192.168.0.254 使用-o选项来指定端口号. -oPort=远程端口号 sftp> get /var/w ...
随机推荐
- STL学习笔记3--deque
看这一节,是为了下一节的使用,在ogre3d里有些操作要使用到deque. C++ Deque(双向队列) 的使用 Deque结合了vector 和list 优缺点,是一种使用简单的容器. deq ...
- git和github基础入门
一.git: 1.安装配置git: 1.1从官网或者该网址处下载:https://pan.baidu.com/s/1kU5OCOB#list/path=%2Fpub%2Fgit 1.2安装,一路nex ...
- ACM-ICPC 2018 焦作赛区网络预赛
这场打得还是比较爽的,但是队友差一点就再过一题,还是难受啊. 每天都有新的难过 A. Magic Mirror Jessie has a magic mirror. Every morning she ...
- springboot 连接redis
引入依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>s ...
- Summary—【base】(JavaScript)
1.认识Js 1.1 Js就是一门运行在客户端浏览器的脚本编程语言 1.2 组成 ECMAScript:Js的语法标准 DOM:JS操作网页 ...
- 【bzoj3091】城市旅行 LCT区间合并
题目描述 输入 输出 样例输入 4 5 1 3 2 5 1 2 1 3 2 4 4 2 4 1 2 4 2 3 4 3 1 4 1 4 1 4 样例输出 16/3 6/1 题解 LCT区间合并 前三个 ...
- post方式的数据抓取
public static String sendPost(String url, String param) { PrintWriter out = null; Buff ...
- hihoCoder offer 收割编程练习赛 83 C 播放列表
题目 用 $1,2 ,3 \dots, N$ 代表 $N$ 首歌.设想有 $L$ 个格子排成一排,编号 $1$ 到 $L$ .考虑将这些数字挨个填进格子里的情形.假设当前要往第 $i$ 个格子里填一个 ...
- hdu 1025 n*logn最长上升子序列
/* TLE */ #include <iostream> #include <cstdio> #include <cstring> using namespace ...
- HH去散步(bzoj 1875)
Description HH有个一成不变的习惯,喜欢饭后百步走.所谓百步走,就是散步,就是在一定的时间 内,走过一定的距离. 但是同时HH又是个喜欢变化的人,所以他不会立刻沿着刚刚走来的路走回. 又因 ...