我们或多或少都见过别人使用xftp或者网页直接操作远程文件,看着很高大上,掌握了这个技能就可以把linux的图形化界面丢掉使用命令行了~

注意:
- 本文在ubuntu测试通过,不带注释的命令都是ubuntu的命令,centos的命令自行百度,差不多的
1.用户创建(可选)
用户创建不是必须的,用原有用户也可以
创建的这个用户并不是ftp的用户,而是linux系统用户,比如原来/home/
下已经有了一个用户user123,那么再创建后,相当于创建了一个与user1差不多级别的用户。而新用户的家目录也是可以选择的,但最好还是放在/home/
目录下,比较直观。
创建的用户同样可以用于ssh,只是我们把他用于ftp服务而已。
比如我们要创建一个用户:名为ftpuser
。名后加个user以区别是我们建的还是ftp软件自己建的内容。因为我一开始安装的时候总分不清命令里的名称代表的是目录还是用户名。
最好先把新建用户的家目录创建好,比如下面语句。
mkdir /home/ftpfile
chmod -R 777 /home/ftpfile
# 更改一下权限,不然没法进行写
# 后面的命令需要权限的话,命令前加sudo
为什么最好先创建ftpfile目录呢?因为我在之前实验的时候发现创建了用户后,指定用户的家目录,系统并不会自动生成此目录,还是需要手动创建,所以我们就先创建好。
接下来我们创建ubuntu系统用户:
# 对于ubuntu
# d是指定登入时的起始目录
sudo useradd -d /home/ftpfile -s /bin/bash ftpuser
sudo passwd ftpuser
# 输入密码并确认
# 对于centos
adduser username
passwd username
# 输入密码
useradd命令介绍:
useradd [-d home] [-s shell] [-c comment] [-m [-k template]] [-f inactive] [-e expire ] [-p passwd] [-r] name
最后一个为用户名,-d后面指定家目录
主要参数
-c:加上备注文字,备注文字保存在passwd的备注栏中。
-d:指定用户登入时的启始目录。***********
-D:变更预设值。
-e:指定账号的有效期限,缺省表示永久有效。
-f:指定在密码过期后多少天即关闭该账号。
-g:指定用户所属的群组。
-G:指定用户所属的附加群组。
-m:自动建立用户的登入目录。
-M:不要自动建立用户的登入目录。
-n:取消建立以用户名称为名的群组。
-r:建立系统账号。
-s:指定用户登入后所使用的shell。
-u:指定用户ID号。------------如果中途出错需要删除用户的话------------
删除用户:userdel name
2.安装 vsftpd服务器
# 对于ubuntu
sudo apt install vsftpd
# 对于centos7
yum -y install vsftpd
附安装可能使用的其他知识:
vim:这里只需要简单知道:
vim后刚进入的是基本模式,不能编辑,可以使用hjkl键左下上右,但不熟悉的话最好不要瞎按,直接按个i,进入插入模式,就可以正常打字了。
写好之后按ESC,然后输入
:wq
,若不成功,可能是没有加sudo或者没有给文件夹权限 chmod -R 777 文件目录/文件名
3.ftp配置与测试
3.1 修改配置文件
# 对于ubuntu
sudo vim /etc/vsftpd.conf
# 对于centos7
vim /etc/vsftpd/vsftpd.conf
没有的语句要自己加上,有些语句商家只是给注释了,把#去掉即可。
需要注意的配置:
- local_root=/home/ftpfile # 设置一个本地用户登录后进入到的目录,可以定义其他目录,与刚才用户创建的目录无关,但最好放这里
# Example config file /etc/vsftpd.conf
#
# The default compiled in settings are fairly paranoid. This sample file
# loosens things up a bit, to make the ftp daemon more usable.
# Please see vsftpd.conf.5 for all compiled in defaults.
#
# READ THIS: This example file is NOT an exhaustive list of vsftpd options.
# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's
# capabilities.
#
#
# Run standalone? vsftpd can run either from an inetd or as a standalone
# daemon started from an initscript.
listen=NO # 服务器监听
#
# This directive enables listening on IPv6 sockets. By default, listening
# on the IPv6 "any" address (::) will accept connections from both IPv6
# and IPv4 clients. It is not necessary to listen on *both* IPv4 and IPv6
# sockets. If you want that (perhaps because you want to listen on specific
# addresses) then you must run two copies of vsftpd with two configuration
# files.
listen_ipv6=YES
#
# Allow anonymous FTP? (Disabled by default).
anonymous_enable=NO # 匿名访问允许,默认不要开启。yes的话就可以不登录访问
#
# 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 # 是否允许上传文件,不开启会报 550 permission denied
#
# 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 # FTP上本地的文件权限,默认是077 022?
#
# Uncomment this to allow the anonymous FTP user to upload files. This only
# has an effect if the above global write enable is activated. Also, you will
# obviously need to create a directory writable by the FTP user.
#anon_upload_enable=YES # 匿名上传允许,默认是NO
#
# Uncomment this if you want the anonymous FTP user to be able to create
# new directories.
#anon_mkdir_write_enable=YES # 匿名创建文件夹允许
#
# Activate directory messages - messages given to remote users when they
# go into a certain directory.
dirmessage_enable=YES # 进入文件夹允许
#
# If enabled, vsftpd will display directory listings with the time
# in your local time zone. The default is to display GMT. The
# times returned by the MDTM FTP command are also affected by this
# option.
use_localtime=YES
#
# Activate logging of uploads/downloads.
xferlog_enable=YES # ftp 日志记录允许
#
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=YES # 启用20号端口作为数据传送的端口
#
# If you want, you can arrange for uploaded anonymous files to be owned by
# a different user. Note! Using "root" for uploaded files is not
# recommended!
#chown_uploads=YES
#chown_username=whoever
#
# You may override where the log file goes if you like. The default is shown
# below.
xferlog_file=/var/log/vsftpd.log
#
# If you want, you can have your log file in standard ftpd xferlog format.
# Note that the default log file location is /var/log/xferlog in this case.
xferlog_std_format=YES
#
# You may change the default value for timing out an idle session.
#idle_session_timeout=600
#
# You may change the default value for timing out a data connection.
#data_connection_timeout=120
#
# It is recommended that you define on your system a unique user which the
# ftp server can use as a totally isolated and unprivileged user.
#nopriv_user=ftpsecure
#
# Enable this and the server will recognise asynchronous ABOR requests. Not
# recommended for security (the code is non-trivial). Not enabling it,
# however, may confuse older FTP clients.
#async_abor_enable=YES
#
# By default the server will pretend to allow ASCII mode but in fact ignore
# the request. Turn on the below options to have the server actually do ASCII
# mangling on files when in ASCII mode.
# Beware that on some FTP servers, ASCII support allows a denial of service
# attack (DoS) via the command "SIZE /big/file" in ASCII mode. vsftpd
# predicted this attack and has always been safe, reporting the size of the
# raw file.
# ASCII mangling is a horrible feature of the protocol.
#ascii_upload_enable=YES
#ascii_download_enable=YES
#
# You may fully customise the login banner string:
ftpd_banner=Welcome to blah FTP service.# 欢迎信息
#
# You may specify a file of disallowed anonymous e-mail addresses. Apparently
# useful for combatting certain DoS attacks.
#deny_email_enable=YES
# (default follows)
#banned_email_file=/etc/vsftpd.banned_emails
#
# You may restrict local users to their home directories. See the FAQ for
# the possible risks in this before using chroot_local_user or
# chroot_list_enable below.
#chroot_local_user=YES # 用于指定用户列表文件中的用户是否允许切换到上级目录。默认值为NO。
#
# You may specify an explicit list of local users to chroot() to their home
# directory. If chroot_local_user is YES, then this list becomes a list of
# users to NOT chroot().
# (Warning! chroot'ing can be very dangerous. If using chroot, make sure that
# the user does not have write access to the top level directory within the
# chroot)
chroot_local_user=YES
chroot_list_enable=YES # 设置是否启用chroot_list_file配置项指定的用户列表文件。默认值为NO。
# user_sub_token=$USER 最初加上这句使我安装不成功
local_root=/home/ftpfile # 设置一个本地用户登录后进入到的目录,可以定义其他目录,与刚才用户创建的目录无关,但最好放这里
# (default follows)
chroot_list_file=/etc/vsftpd.chroot_list # 格式为一行一个用户,用于指定用户列表文件,该文件用于控制哪些用户可以切换到用户家目录的上级目录。
#
# You may activate the "-R" option to the builtin ls. This is disabled by
# default to avoid remote users being able to cause excessive I/O on large
# sites. However, some broken FTP clients such as "ncftp" and "mirror" assume
# the presence of the "-R" option, so there is a strong case for enabling it.
#ls_recurse_enable=YES
#
# Customization
#
# Some of vsftpd's settings don't fit the filesystem layout by
# default.
#
# This option should be the name of a directory which is empty. Also, the
# directory should not be writable by the ftp user. This directory is used
# as a secure chroot() jail at times vsftpd does not require filesystem
# access.
secure_chroot_dir=/var/run/vsftpd/empty
#
# This string is the name of the PAM service vsftpd will use.
# !!!!!!!!!!!****************************!!!!!!!!
pam_service_name=ftp
# !!!!!!!!!!!****************************!!!!!!!! 一定要把上句改好,
#
# This option specifies the location of the RSA certificate to use for SSL
# encrypted connections.
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
ssl_enable=NO
#
# Uncomment this to indicate that vsftpd use a utf8 filesystem.
utf8_filesystem=YES
然后编辑/etc/vsftpd.chroot_list文件,将ftpuser的帐户名添加进去,保存退出。这里不截图了,就是这个文件里写上创建的用户名即可。
vim /etc/vsftpd.chroot_list # 加入创建的用户
ftpuser
3.2 重新启动vsftpd:
# 注:修改配置文件后一定要重启服务才能生效
# 对于ubuntu
sudo service vsftpd restart
# 对于centos7
systemctl start vsftpd.service
3.3 查看服务状态
上句之后在命令行输入下句,查看之前步骤是否成功,不成功的话下面显示的不是running
# 对于ubuntu
service vsftpd status
# 对于centos
systemctl status vsftpd.service
按q退出
附安装可能使用的其他知识:
配置文件解释:https://www.cnblogs.com/acpp/archive/2010/02/08/1666054.html
3.4 开放访问端口
因为linux有防火墙,所以需要修改防火墙
# ftp端口:21端口用于连接,20端口用于传输数据
# 对于ubuntu:
sudo ufw disable
# 或尝试` service iptables stop`
# 对于centos
firewall-cmd --zone=public --add-port=21/tcp --permanent # 打开21端口
firewall-cmd --zone=public --add-port=1025-65535/tcp --permanent # 打开这个区间的端口
systemctl restart firewalld
# centos:`systemctl disable firewalld` (systemctl stop firewalld是暂时关闭,disable是永久)
3.5 上传文件到了哪里
上传的文件会保存在访问用户的工作空间,如/home/username
,但我们也可以在上面的conf文件中配置
3.6vsftpd常用命令:
# 对于ubuntu
# 卸载vsftpd
sudo apt-get remove --purge vsftpd
#(--purge 选项表示彻底删除改软件和相关文件)
#开启、停止、重启vsftpd服务的命令:
service vsftpd start
service vsftpd stop
service vsftpd restart
PS: 有关ftp端口。
ftp服务有两个端口,默认情况下,一个是20端口,另一个是21端口。21端口用于连接,20端口用于数据传输。
进行ftp文件传输,客户端首先连接到ftp服务器的21端口,进行用户的认证,认证成功后,要传输文件时,ftp服务器会开一个端口20来进行传输数据文件。
--------------------------------------------------.命令行输入
ifconfig
可以查看该远程IP
4.测试与使用
4.1cmd方式使用
可以在windows下cmd下使用下面语句访问目录。
ftp IP号
ls # 查看文件
dir #查看文件
使用`get 文件名` 进行下载
4.2文件夹方式使用
在文件夹的目录位置输入:
ftp:192.168.2.10
然后输入账号密码
4.3浏览器方式使用
和文件使用方式相同,输入ftp:192.168.2.10
会自动补全成ftp://192.168.2.10/
4.4xftp方式使用
这里实际登录方式是ssh,即你登录了之后进去的是你创建的系统用户的家目录,跟ftp没有关系,但是你也可以找到对应位置进行传文件,如果传不进去,原因是你之前用户创建的时候没有给该文件修改写权限
4.5xftp破解地址
:https://blog.csdn.net/u011622631/article/details/88991941
5.常见报错:
5.1报错:500 OOPS: vsftpd: refusing to run with writable root inside chroot() Login f
解决方案:
sudo vim /etc/vsftpd.conf
插入:
allow_writeable_chroot=YES
5.2报错:ftp登陆报错530 Login incorrect. Login failed.
解决:https://blog.csdn.net/hahahaxiaoyu/article/details/100582853 (但是我没查到我们是登录shell,算了,虚拟机上还是使用root用户吧)
5.3报错:虚拟机ftp 192.168.2.10 ftp: connect :连接超时
解决方案:
sudo /sbin/iptables -P INPUT ACCEPT #先把默认策略改为ACCEPT
sudo /sbin/iptables -F # 之前前一定要查看iptables -L,确认默认策略为ACCEPT
5.4报错:无法登录:ftp: connect: Connection refused
同时ipv4和ipv6同时运行服务器报错。
解决方案:vsftpd.conf文件里的#listen_ipv6=YES被取消注释了。
于是将上面那句注释掉,就可以啦。
我的网是ipv6的,但是注释掉不影响,依然可以ipv4和ipv6都可以。
但是如果listen=YES和listen_ipv6=YES同时在就会报错。
6 springboot使用ftp
视频学习可以参考:https://space.bilibili.com/27385378/channel/detail?cid=108639
接下来也只写关键点
加入ftp依赖
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
ftp工具类
获取连接
public FTPClient getConnectionFTP(String hostName, int port, String userName, String password) {
// 创建FTPClient对象
FTPClient ftp = new FTPClient();
try {
// 连接FTP服务器
ftp.connect(hostName, port);
// 下面三行代码必须要,而且不能改变编码格式,否则不能正确下载中文文件
ftp.setControlEncoding("GBK");
// FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
// conf.setServerLanguageCode("zh");
// 登录ftp
ftp.login(userName, password);
int replyCode = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
ftp.disconnect();
logger.debug("FTPUtil getConnectionFTP method id =>连接服务器失败");
}
logger.debug("FTPUtil getConnectionFTP method id =>登陆服务器成功");
} catch (IOException e) {
e.printStackTrace();
}
return ftp;
}
配置信息类
我们也可以把配置到properties中然后获取
public static String getFtpPropertis(String key) {
String result = null;
java.util.Properties props;
try {
// 利用PropertiesLoaderUtils类获取配置文件信息
props = PropertiesLoaderUtils.loadAllProperties("appftpserver.properties");
result = props.getProperty(key);//根据name得到对应的value
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
比如配置文件中我们有ip、端口、用户名、密码
file.service=192.168.1.170
file.service.port=21
file.service.uid=hhh
file.service.pwd=123123
于是获取连接类修正为
// 重载
public FTPClient getConnectionFTP() {
// 从配置文件中获取ip port uid pwd
FTPClient ftp = getConnectionFTP(PropertiesUtil.getFtpPackey("file.service"),
Integer.parseInt(PropertiesUtil.getFtpPackey("file.service.port")),
PropertiesUtil.getFtpPackey("file.service.uid"),
PropertiesUtil.getFtpPackey("file.service.pwd"));
return ftp;
}
ftp上传
- 获取连接
- 设置文件类型:ftp.setFileType(FTP.BINARY_FILE_TYPE);
- 创建文件夹:ftp.makeDirectory(path);
- 切换目录:ftp.changeWorkingDirectory(path)
- ftp.enterLocalPassiveMode();
- 上传:flag = ftp.storeFile(fileName, inputStream);
- 关闭输入流:inputStream.close();
- ftp登出:ftp.logout();
- 断开连接:ftp.disconnect();
// 指定要上传的路径、要保存的文件名、输入流
public boolean uploadFile(String path, String fileName, InputStream inputStream) {
boolean success = false;
try {
FTPClient ftp = getConnectionFTP();//这里
// 转到指定上传目录
boolean flag = ftp.changeWorkingDirectory(path);// 转移到指定FTP服务器目录
// FTPFile[] fs = ftp.listFiles();//得到目录的相应文件列表 //deleted by pengmd
// fileName = FTPUtil.changeName(fileName, fs); //deleted by pengmd
// fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
// path = new String(path.getBytes("UTF-8"), "ISO-8859-1");
// 设置缓冲大小200M
ftp.setBufferSize(204800);
// 将上传文件存储到指定目录
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
// 如果缺省该句 传输txt正常 但图片和其他格式的文件传输出现乱码
flag = ftp.storeFile(fileName, inputStream);
// 关闭输入流
inputStream.close();
// 退出ftp
ftp.logout();
// 表示上传成功
success = true;
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
上传后还应该更新数据库,具体不写了
controller
-
post映射:
@PostMapping
-
参数:
- 用户
@RequestParam("spicture") MultipartFile file
@PostMapping("/up")
public String upload1(@RequestParam("spicture") MultipartFile file){
InputStream ins = file.getInputStream();
FtpUtil.uploadFile(ins);
// File localFile = new File("服务器端的绝对路径");
// file.transferTo(localFile);
}
使用postman测试:
选择post方式,选择Body里的form-data
,在下面选项里输入key,然后在下拉菜单中选择file,选择file
jsp
- 依赖:commons-fileupload、commons-io,前者依赖后者
- from表单设置:
- 请求方式:
method="post"
enctype="multipart/form-data"
- from的提交地址,该地址处理上传的文件:
action=
- 请求方式:
- 上传单个文件按钮:
<input type="file">
。如果想支持多文件上传,可以多写几个input标签,name不同即可 - 提交按钮:
<input type="submit">
本初只是简要写出来了如何设置form表单使之能上传文件
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="UploadServet" method="post" enctype="multipart/form-data">
学号:<input name="sno" /><br/>
姓名:<input name="sname" /><br/>
上传照片: <input type="file" name="spicture"/>
<br/>
<input type="submit" value="注册"/>
</form>
<a href="DownloadServlet?filename=MIME.png">MIME</a>
</body>
</html>
文件的浏览
在网页上是无法通过ftp协议显示的,我们要搭建http协议平台。
可以通过Apache2或者nginx提供http协议,让文件可以在网页上显示
nginx.conf
server{
...
location files{
alias hone/username/files;
}