简述

>> 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 &amp; FTP Upload的更多相关文章

  1. Java使用SFTP和FTP两种连接方式实现对服务器的上传下载 【我改】

    []如何区分是需要使用SFTP还是FTP? []我觉得: 1.看是否已知私钥. SFTP 和 FTP 最主要的区别就是 SFTP 有私钥,也就是在创建连接对象时,SFTP 除了用户名和密码外还需要知道 ...

  2. 小白的linux笔记4:几种共享文件方式的速度测试——SFTP(SSH)/FTP/SMB

    测试一下各个协议的速度,用一个7205M的centos的ISO文件上传下载.5Gwifi连接时,本地SSD(Y7000)对服务器的HDD: smb download 23M/s(资源管理器) smb ...

  3. Sftp和ftp 差别、工作原理等(汇总ing)

    Sftp和ftp over ssh2的差别 近期使用SecureFx,涉及了两个不同的安全文件传输协议: -sftp -ftp over SSH2 这两种协议是不同的.sftp是ssh内含的协议,仅仅 ...

  4. 浅谈SFTP和FTP的区别

    一.适用场景 我们平时习惯了使用ftp来上传下载文件,尤其是很多Linux环境下,我们一般都会通过第三方的SSH工具连接到Linux,但是当我们需要传输文件到Linux服务器当中,很多人习惯用ftp来 ...

  5. Linux 下上传下载命令,SCP,SFTP,FTP

    scp 帮助命令: man scp scp功能: 下载远程文件或者目录到本地, 如果想上传或者想下载目录,最好的办法是采用tar压缩一下,是最明智的选择. 从远程主机 下载东西到 本地电脑 拷贝文件命 ...

  6. sftp与ftp的区别

    SFTP和FTP非常相似,都支持批量传输(一次传输多个文件),文件夹/目录导航,文件移动,文件夹/目录创建,文件删除等.但还是存在着差异,下面我们来看看SFTP和FTP之间的区别. 1. 安全通道FT ...

  7. sftp,ftp文件下载

    一.sftp工具类 package com.ztesoft.iotcmp.util; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsc ...

  8. linux命令-sftp(模拟ftp服务)和scp(文件异地直接复制)

    1)sftp sftp是模拟ftp的服务,使用22端口 针对远方服务器主机 (Server) 之行为 变换目录到 /etc/test 或其他目录 cd /etc/testcd PATH 列出目前所在目 ...

  9. Linux 远程连接sftp与ftp

    linux sftp远程连接命令 sftp -oPort=60001 root@192.168.0.254 使用-o选项来指定端口号. -oPort=远程端口号 sftp> get /var/w ...

随机推荐

  1. 设置CMD默认代码页为65001或936

    之前不知道怎么改的,CMD的代码页被默认设置成了65001   但我右击CMD标题,选择‘默认值’,显示默认却是936,但为何每次打开都是65001呢   上网找到设置默认值的方法 1 win键+R打 ...

  2. python-os模块及md5加密

    常用内置方法 __doc__打印注释 __package__打印所在包 __cached__打印字节码 __name__当前为主模块是__name__ == __main__ __file__打印文件 ...

  3. poj1111(单身快乐)

                                                                                                         ...

  4. 11 JVM 垃圾回收(上)

    引用计数法和可达性分析 垃圾回收,就是将已经分配出去的,但却不在使用的内存回收回来,以便再次分配.在 Java 虚拟机语境下,垃圾指的是死亡的对象所占据的堆空间.下面就总结一下如何如何辨别一个对象是否 ...

  5. git和github基础入门

    一.git: 1.安装配置git: 1.1从官网或者该网址处下载:https://pan.baidu.com/s/1kU5OCOB#list/path=%2Fpub%2Fgit 1.2安装,一路nex ...

  6. nyoj 题目12 喷水装置(二)

    喷水装置(二) 时间限制:3000 ms  |  内存限制:65535 KB 难度:4   描述 有一块草坪,横向长w,纵向长为h,在它的橫向中心线上不同位置处装有n(n<=10000)个点状的 ...

  7. [POI2005][luogu3462] SZA-Template [fail树]

    题面 传送门 思路 首先,我们观察一下这个要求的"模板串",发现它有如下性质: 1.一个模板串$A$是要求的文本串$B$的公共前后缀 2.如果一个模板串$A$有另一个模板串$B$( ...

  8. hdu 4293 区间DP

    /* 题目大意:n个人分成若干组,每个人都描叙他们组前面有多少人后面有多少人, 求说真话的人最多有多少个. 解题思路:把同一组的人数统计起来他们组前面有x人后面有y人, num[x+1][n-y]表示 ...

  9. Linux脚本中调用SQL,RMAN脚本

    Linux/Unix shell脚本中调用或执行SQL,RMAN 等为自动化作业以及多次反复执行提供了极大的便利,因此通过Linux/Unix shell来完成Oracle的相关工作,也是DBA必不可 ...

  10. .NET and php

    原文发布时间为:2011-12-29 -- 来源于本人的百度文章 [由搬家工具导入] http://www.php-compiler.net/blog/2011/phalanger-3-0