需求:定时远程上传文件,windows->linux

linux是一个云服务器,centos7

1:安装vsftpd

yum install vsftpd

2:设置开机启动服务
chkconfig vsftpd on

3:启动服务 
 service vsftpd start

4:防火墙端口打开

打开/etc/sysconfig/iptables文件

vi /etc/sysconfig/iptables

在REJECT行之前添加如下代码

-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 21 -j ACCEPT

保存和关闭文件,重启防火墙

service iptables restart

5:配置vsftpd 服务器

vi /etc/vsftpd/vsftpd.conf

将匿名登录关闭 anonymous_enable=NO

chroot_list_enable=YES //限制访问自身目录
# (default follows)
chroot_list_file=/etc/vsftpd/vsftpd.chroot_list

编辑 vsftpd.chroot_list文件,将受限制的用户添加进去,每个用户名一行,(但实际上加了这个会很麻烦,所以没加),比如出现 500 OOPS: vsftpd: refusing to run with writable root inside chroot()

参考这个link:https://zhidao.baidu.com/question/1732079113433285347.html

6:添加ftp用户

useradd -d /home/test test

passwd oneuser

如果加错了,可以删掉这个用户

userdel test

7:修改文件夹所有者

chown test /home/test -R

如果还是不好使,改一下权限

chmod -R 777 /home/test

8:最后,别忘了重启服务

service vsftpd restart

9:查看用户默认路径:  cat /etc/passwd

通过java的FTPClient去连接时会出现各种错误,首先,用户名和密码,端口别搞错了,FTPClient的jar包可以选最高的版本

网上有FTPutil的代码,我也是拿来主义了,但是发现有bug,下面是自己测试过的代码,传单个文件,如果要传文件夹的话也很简单。

补充:如果出现下载文件ftpClient.listFiles()为null的错误,用以下方法解决

执行ftpClient.listFiles()前加上一句:

ftpClient.enterLocalPassiveMode();

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException; import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply; public class FtpUtils {
//ftp服务器地址
public String hostname = "XXXX";
//ftp服务器端口号默认为21
public Integer port = 21 ;
//ftp登录账号
public String username = "XXX";
//ftp登录密码
public String password = "XXX"; public FTPClient ftpClient = null; /**
* 初始化ftp服务器
*/
public void initFtpClient() {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
try {
System.out.println("connecting...ftp服务器:"+this.hostname+":"+this.port);
ftpClient.connect(hostname, port); //连接ftp服务器
ftpClient.login(username, password); //登录ftp服务器
int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
if(!FTPReply.isPositiveCompletion(replyCode)){
System.out.println("connect failed...ftp服务器:"+this.hostname+":"+this.port);
}else{
System.out.println("connect successfu...ftp服务器:"+this.hostname+":"+this.port);
} }catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
} /**
* 上传文件
* @param pathname ftp服务保存地址
* @param fileName 上传到ftp的文件名
* @param originfilename 待上传文件的名称(绝对地址) *
* @return
*/
public boolean uploadFile( String pathname, String fileName,String originfilename){
boolean flag = false;
InputStream inputStream = null;
try{
System.out.println("开始上传文件");
inputStream = new FileInputStream(new File(originfilename));
initFtpClient();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
ftpClient.setDataTimeout(60000); //设置传输超时时间为60秒
ftpClient.setConnectTimeout(60000); //连接超时为60秒
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
System.out.println("上传文件成功");
}catch (Exception e) {
System.out.println("上传文件失败");
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
/**
* 上传文件
* @param pathname ftp服务保存地址
* @param fileName 上传到ftp的文件名
* @param inputStream 输入文件流
* @return
*/
public boolean uploadFile( String pathname, String fileName,InputStream inputStream){
boolean flag = false;
try{
System.out.println("开始上传文件");
initFtpClient();
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
System.out.println("上传文件成功");
}catch (Exception e) {
System.out.println("上传文件失败");
e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
//改变目录路径
public boolean changeWorkingDirectory(String directory) {
boolean flag = true;
try {
flag = ftpClient.changeWorkingDirectory(directory);
if (flag) {
System.out.println("进入文件夹" + directory + " 成功!"); } else {
System.out.println("进入文件夹" + directory + " 失败!开始创建文件夹");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return flag;
} //创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
public boolean CreateDirecroty(String remote) throws IOException {
boolean success = true;
String directory = remote + "/";
// 如果远程目录不存在,则递归创建远程服务器目录
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
String path = "";
String paths = "";
while (true) {
String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
path = path + "/" + subDirectory;
if (!existFile(path)) {
if (makeDirectory(subDirectory)) {
changeWorkingDirectory(subDirectory);
} else {
System.out.println("创建目录[" + subDirectory + "]失败");
changeWorkingDirectory(subDirectory);
}
} else {
changeWorkingDirectory(subDirectory);
} paths = paths + "/" + subDirectory;
start = end + 1;
end = directory.indexOf("/", start);
// 检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}
return success;
} //判断ftp服务器文件是否存在
public boolean existFile(String path) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
//创建目录
public boolean makeDirectory(String dir) {
boolean flag = true;
try {
flag = ftpClient.makeDirectory(dir);
if (flag) {
System.out.println("创建文件夹" + dir + " 成功!"); } else {
System.out.println("创建文件夹" + dir + " 失败!");
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
} /** * 下载文件 *
* @param pathname FTP服务器文件目录 *
* @param filename 文件名称 *
* @param localpath 下载后的文件路径 *
* @return */
public boolean downloadFile(String pathname, String filename, String localpath){
boolean flag = false;
OutputStream os=null;
try {
System.out.println("开始下载文件");
initFtpClient();
//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
FTPFile[] ftpFiles = ftpClient.listFiles();
for(FTPFile file : ftpFiles){
if(filename.equalsIgnoreCase(file.getName())){
File localFile = new File(localpath + "/" + file.getName());
os = new FileOutputStream(localFile);
ftpClient.retrieveFile(file.getName(), os);
os.close();
}
}
ftpClient.logout();
flag = true;
System.out.println("下载文件成功");
} catch (Exception e) {
System.out.println("下载文件失败");
e.printStackTrace();
} finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
if(null != os){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
} /** * 删除文件 *
* @param pathname FTP服务器保存目录 *
* @param filename 要删除的文件名称 *
* @return */
public boolean deleteFile(String pathname, String filename){
boolean flag = false;
try {
System.out.println("开始删除文件");
initFtpClient();
//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
ftpClient.dele(filename);
ftpClient.logout();
flag = true;
System.out.println("删除文件成功");
} catch (Exception e) {
System.out.println("删除文件失败");
e.printStackTrace();
} finally {
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
}
return flag;
} public static void main(String[] args) {
FtpUtils ftp =new FtpUtils();
ftp.uploadFile("XXX", "XXX", "XXX");
//ftp.downloadFile("ftpFile/data", "123.docx", "F://");
// ftp.deleteFile("ftpFile/data", "123.docx");
System.out.println("ok");
}
}

2019-4-28 update

添加了C#的版本,下面是核心的两个方法,注意,C#出了一个很诡异的问题(553) 不允许此文件名,原来是拼接linux路径的时候,不要把默认路径带进去!

 private void DownFile()
{
string FtpFilePath = ServerPath.Text.Trim(); //远程路径
string LocalPath = downloadPath.Text.Trim()+"\\my.txt"; //下载到的本地路径
if (File.Exists(LocalPath))
{
File.Delete(LocalPath);
}
string FTPPath = FTPAddress + FtpFilePath;
//建立ftp连接
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(FTPPath));
reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
reqFtp.UseBinary = true;
reqFtp.UsePassive = true;
reqFtp.ReadWriteTimeout = ;
reqFtp.KeepAlive = true;
reqFtp.Credentials = new NetworkCredential(FTPUsername, FTPPwd); FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int buffersize = ;
int readCount;
byte[] buffer = new byte[buffersize];
readCount = ftpStream.Read(buffer, , buffersize);
//创建并写入文件
FileStream OutputStream = new FileStream(LocalPath, FileMode.Create);
while (readCount > )
{
OutputStream.Write(buffer, , buffersize);
readCount = ftpStream.Read(buffer, , buffersize);
}
ftpStream.Close();
OutputStream.Close();
response.Close();
if (File.Exists(LocalPath)) {
MessageBox.Show("download OK!");
}
} private void UpFile()
{
string LocalPath = "D:\\test.txt"; //待上传文件
FileInfo f = new FileInfo(LocalPath);
string FileName = f.Name;
string ftpRemotePath = "/";
string FTPPath = FTPAddress + ftpRemotePath + FileName; //上传到ftp路径,如ftp://***.***.***.**:21/home/test/test.txt
//实现文件传输协议 (FTP) 客户端
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(FTPPath));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUsername, FTPPwd); //设置通信凭据
reqFtp.KeepAlive = false; //请求完成后关闭ftp连接
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.ContentLength = f.Length;
int buffLength = ;
byte[] buff = new byte[buffLength];
int contentLen;
//读本地文件数据并上传
FileStream fs = f.OpenRead();
try
{
Stream strm = reqFtp.GetRequestStream();
contentLen = fs.Read(buff, , buffLength);
while (contentLen != )
{
strm.Write(buff, , contentLen);
contentLen = fs.Read(buff, , buffLength);
}
strm.Close();
fs.Close();
MessageBox.Show("upload OK!");
}
catch (Exception ex)
{
MessageBox.Show("upload fail!");
}
}

linux 配置ftp服务的更多相关文章

  1. 阿里云linux配置ftp服务

    阿里云linux配置ftp服务 一.ftp服务安装 运行以下命令安装ftp yum install -y vsftpd 运行以下命令打开及查看etc/vsftpd cd /etc/vsftpd ls ...

  2. 配置FTP服务

    配置FTP服务 1.安装FTP服务器(默认已安装) 服 务:vsftpd 位 置:光盘1 软 件:vftpd-2.0.1-5.i386.rpm 配 置:/etc/vsftpd/vsftpd.conf ...

  3. Linux 安装FTP服务

    Linux 安装FTP服务,简单入门 环境: 虚拟机:Oracle VM VirtualBox. 系统:CentOS 7. (1)判断是否安装了ftp: rpm -qa | grep vsftpd 或 ...

  4. Linux SSH,FTP服务配置

    CentOS-6.4-x86_64-minimal 0.网卡配置 参考:Linux系统\Centos没有网卡eth0配置文件怎么办? - http://jingyan.baidu.com/articl ...

  5. 讲述一下自己在linux中配置ftp服务的经历

    本人大二小白一名,从大一下学期就开始接触到linux,当时看到学校每次让我们下载资源都在一个ftp服务器中,感觉特别的高大上,所以自己就想什么时候自己能够拥有自己的ftp服务器,自己放一点东西进去,让 ...

  6. Linux系统安装及配置ftp服务

    1. 先用rpm -qa| grep vsftpd命令检查是否已经安装,如果ftp没有安装,使用yum  -y  install vsftpd 安装,(ubuntu 下使用apt-get instal ...

  7. Linux:ftp服务本地用户,虚拟用户配置

    本地用户 1. 修改ftp配置文件,  anonymous_enable=NO   默认为YES,修改为NO,禁止匿名访问, 监听端口,可以根据自己的需求修改,为了安全起见自定义为好 2. /etc/ ...

  8. Linux:FTP服务匿名用户,本地用户,虚拟用户配置

    匿名用户  FTP协议占用两个端口号: 21端口:命令控制,用于接收客户端执行的FTP命令. 20端口:数据传输,用于上传.下载文件数据. 实验:匿名访问,服务器192.168.10.10    客户 ...

  9. CentOS系统下安装配置ftp服务

    安装配置步骤: rpm -ivh /opt/bak/vsftpd-2.2.2-11.el6.x86_64.rpm --本地安装vsftpd ll /etc/vsftpd/  --查看vsftpd的配置 ...

随机推荐

  1. python绘制中文词云图

    准备工作 主要用到Python的两个第三方库 jieba:中文分词工具 wordcloud:python下的词云生成工具 步骤 准备语料库,词云图需要的背景图片 使用jieba进行分词,去停用词,词频 ...

  2. github爬虫100项目

    为了更好的巩固所学,在github上开始100爬虫项目,记录学习过程,也希望对他人的学习有帮助,目前还在持续更新中,有兴趣可以看看 地址: https://github.com/mapyJJJ/100 ...

  3. 用mongols轻松打造websocket应用

    用websocket做聊天系统是非常合适的. mongols是一个运行于linux系统之上的开源c++库,可轻松开启一个websocket服务器. 首先,build一个websocket服务器. #i ...

  4. django signals 信号

    django signals 信号 配置方式 app下的 __init__.py default_app_config="web.apps.WebConfig" #初始化app配置 ...

  5. 深入理解 Java 多线程核心知识

    多线程相对于其他 Java 知识点来讲,有一定的学习门槛,并且了解起来比较费劲.在平时工作中如若使用不当会出现数据错乱.执行效率低(还不如单线程去运行)或者死锁程序挂掉等等问题,所以掌握了解多线程至关 ...

  6. struts2+springmvc+hibernate开发。个人纪录

    对于很多新手来说,都不太清楚应该怎么去放置代码并让他成为一种习惯.个人的总结如下: 一.基础包类的功能 1.dao :提供底层接口 2.daoimpl:实现底层接口类,与底层交互 3.entity:实 ...

  7. Vue 组件&组件之间的通信 之 单向数据流

    单向数据流:父组件值的更新,会影响到子组件,反之则不行: 修改子组件的值: 局部数据:在子组件中定义新的数据,将父组件传过来的值赋值给新定义的数据,之后操作这个新数据: 如果对数据进行简单的操作,可以 ...

  8. Q语言-[帝王三国送将辅助]

    纯属自己写的, 玩同一个游戏的朋友,需要送将的, 把需要送的将改名为送, 然后启动辅助即可 本辅助只支持1024x576 191dpi 附上源码 //本源码初始化分辨率1024x576[夏天] Dim ...

  9. 0x11栈之火车进栈

    参考<算法竞赛进阶指南>p.49 题目链接:https://www.acwing.com/problem/content/description/131/ 递推与递归的宏观描述 对于一个待 ...

  10. Git 版本还原命令

    转载:https://blog.csdn.net/yxlshk/article/details/79944535 1.需求场景: 在利用github实现多人协作开发项目的过程中,有时会出现错误提交的情 ...