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:

如果ftp服务器没有开通20,但是FTP服务器开通了高位随机端口,则必须使用被动模块,同时也可以使用主动模式。

如果客服端的防火墙关闭了端口的主动接收功能,则无法使用主动模式,但可以使用被动模块,这也是被动模块存在的原因。

一般公司内部为了服务器安全点,使用主动模式,但对客户端有些要求,可以接受端口的请求数据。

PORT(主动)方式的连接过程是:

客户端向服务器的FTP端口(默认是21)发送连接请求,服务器接受连接,建立一条命令链路。

当需要传送数据时,客户端在命令链路上用PORT命令告诉服务器:“我打开了****端口,你过来连接我”。

于是服务器从20端口向客户端的****端口发送连接请求,建立一条数据链路来传送数据。

PASV(被动)方式的连接过程是:

客户端向服务器的FTP端口(默认是21)发送连接请求,服务器接受连接,建立一条命令链路。

当需要传送数据时,服务器在命令链路上用PASV命令告诉客户端:“我打开了****端口,你过来连接我”。

于是客户端向服务器的****端口发送连接请求,建立一条数据链路来传送数据。

从上面可以看出,两种方式的命令链路连接方法是一样的,而数据链路的建立方法就完全不同。

【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)) {
					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> exportCucFileCollection = FileUtils.listFiles(localDirectory, new String[] { "gz", "GZ", "xml", "XML", "zip", "ZIP" }, true);

		Set<File> exportCucFileSet = FtpUpload.upload(exportCucFileCollection);

		delete(exportCucFileSet);
	}
}

【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();
	}
}

SFTP & FTP Upload

时间: 2024-10-12 21:30:52

SFTP & FTP Upload的相关文章

SFTP &amp;amp; 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 l

安装SFTP/FTP插件快速编辑远程服务器文件

默认的Sublime Text 3 是没有sftp/ftp功能的,如果编辑器自带ftp势必会提高开发效率,虽然Sublime Text 3 默认是没有ftp功能,但是安装sftp插件很容易.下面是我安装步骤,希望能帮助那些喜欢Sublime Text 3的朋友. 按下Ctrl+Shift+P调出命令面板 输入install 调出 Install Package 选项并回车,然后输入ftp,下拉列表中会出现一些相关的插件,选中sftp进行安装就行了, 出现下图说明安装成功了. 装好后还需配置如下:

sublime2中SFTP/FTP插件的安装

开发中需要将自己本地的代码通过ftp工具同步到开发机,sublime有ftp方面的插件,安装过之后就可以使用ftp功能了. 首先安装Package Control插件.有两种方式: 1. 自动安装.在sublime2中按[CTRL + ~]键打开命令行工具,然后将如下的命令粘入命令行: import urllib2,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf

Sublime Text下使用SFTP/FTP插件

一.前言 本文主要记录了Sublime Text编辑器下的SFTP/FTP的安装使用,方便linux和windows下的文件编辑,只是简单的记录,有不足之处,还望指教. 二.Linux和windows下的文件共享方式 1.Samba 2.FTP 3.NFS 4.WinSCP 5.sshfs 关于sshfs的方式,本人试过之后,可依然不成功,也可能是本人sublime text编辑器的问题,所以用了sftp/ftp插件的方式,感兴趣的朋友,可参考下面方式自己动手试试 https://www.dig

ftp upload

unit TransferThread; //////////////////////////////////////////////////////////////////////////////// // 模块说明: FTP传输核心模块类 // 功能: 指定一个下载(上传)的日期或文件名,系统执行传输功能(支持续传) // 备注:该模块属于传输类的一个子线程模块. ////////////////////////////////////////////////////////////////

【Web】Sublime Text 3 连接sftp/ftp(远程服务器)

在 Win 下常用 Xftp 软件来和远程服务传递文件,但是要是在项目开发的时候频繁的将远程文件拖到本地编辑然后再传回远程服务器,那真是麻烦无比,但是Sublime中SFTP插件,它让这世界美好了许多.Sublime下的SFTP,只要 Ctrl+S 即可同步本地到服务器 使用步骤 1.安装Sublime Text 3 编辑器,参照:[Web]Sublime Text 3 安装+注册+汉化 2.安装sftp插件 a.打开Package Control,搜索Install Package    b.

使用sublime text3 连接sftp/ftp(远程服务器)

首先说明的是Sumblime Text 3,下载安装后,打开软件 在红色箭头指定的控制区域粘贴下面这段英文 import urllib.request,os,hashlib; h = '2915d1851351e5ee549c20394736b442' + '8bc59f460fa1548d1514676163dafc88'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urll

vsftpd+openssl+mysql实现sftp和ftp虚拟用户

FTP:File Transfer protocol ,端口:控制:tcp/21:数据:tcp/20或随机高端口 ftp有两个连接: 命令连接(控制连接):tcp/21 数据连接(按需打开): 主动模式:tcp/20(ftp服务器主动连接客户端) 被动模式:随机高端口 ftp有两种传输模式:二进制.文本(默认为auto,会根据文件特性动匹配) sftp是以openssl来实现:ftps是ssh的子功能. 系统平台:rhel5.8(32位),ip:32.12.32.227,采用系统自带的rpm包安

linux下不同服务器间数据传输(rcp,scp,rsync,ftp,sftp,lftp,wget,curl)

因为工作原因,需要经常在不同的服务器见进行文件传输,特别是大文件的传输,因此对linux下不同服务器间数据传输命令和工具进行了研究和总结.主要是rcp,scp,rsync,ftp,sftp,lftp,wget,curl. rcp rcp不是一种安全的的传输文件的方式,rcp通过rsh(rsh见下面)来执行远程命令,要使用rcp必须经过一些配置,现在rcp已经被scp取代了,常用scp来进行文件传输.要使用rcp,需要具备以下条件: (1)如果系统中有/etc/hosts 文件,应确保该文件包含要