基于centos7.9搭建SFTP服务

SFTP(Secure File Transfer Protocol)是一种安全的文件传输协议,它基于SSH协议,提供了加密的文件传输功能。

安装OpenSSH服务器,默认已经安装

yum install openssh-server -y

创建SFTP用户组和用户

groupadd sftp_users
useradd -g sftp_users -s /sbin/nologin sftp_user
passwd sftp_user

创建SFTP目录结构并设置正确的权限

mkdir -p /sftp/sftp_user/upload
chown root:root /sftp
chmod 755 /sftp
chown root:root /sftp/sftp_user
chmod 755 /sftp/sftp_user
chown sftp_user:sftp_users /sftp/sftp_user/upload
chmod 775 /sftp/sftp_user/upload

修改SSH配置文件

vi /etc/ssh/sshd_config

文件末尾添加

Match Group sftp_users
    ChrootDirectory /sftp/%u
    ForceCommand internal-sftp
    X11Forwarding no
    AllowTcpForwarding no

配置参数详解

  • Match Group sftp_users
    这行开始一个条件块,指定后续的设置只适用于 sftp_users 组的成员。
  • ChrootDirectory /sftp/%u
    将用户限制在指定的目录中。%u 是一个变量,代表用户名。
    例如,对于用户 “sftp_user”,实际的 chroot 目录将是 /sftp/sftp_user。
  • ForceCommand internal-sftp
    强制使用内部 SFTP 服务器,而不允许普通的 SSH 访问。
  • X11Forwarding no
    禁止 X11 转发,这是一种图形界面转发技术。
  • AllowTcpForwarding no
    禁止 TCP 端口转发,增加安全性。

其他可以配置的参数:

  • PasswordAuthentication yes/no
    允许或禁止密码认证。
  • PermitRootLogin no
    禁止 root 用户直接登录。
  • AllowUsers user1 user2
    指定允许登录的用户列表。
  • AllowGroups group1 group2
    指定允许登录的组列表。
  • DenyUsers user1 user2
    指定禁止登录的用户列表。
  • DenyGroups group1 group2
    指定禁止登录的组列表。
  • PermitEmptyPasswords no
    禁止空密码登录。
  • MaxAuthTries 3
    设置最大认证尝试次数。
  • LoginGraceTime 60
    设置登录超时时间(秒)。
  • ClientAliveInterval 300
    设置服务器向客户端发送保活消息的间隔(秒)。
  • ClientAliveCountMax 3
    设置服务器在断开连接前等待客户端响应的最大次数。
  • UseDNS no
    禁用 DNS 反向查询,可以加快登录速度。
  • AllowAgentForwarding no
    禁止 SSH 代理转发。
  • Banner /etc/ssh/banner
    指定登录前显示的欢迎信息文件。
  • Compression delayed
    延迟压缩直到用户认证成功,可以防止某些攻击

重启

systemctl restart sshd

防火墙开启端口

firewall-cmd --permanent --add-service=ssh
firewall-cmd --reload

关闭selinux

setenforce 0

测试SFTP连接;连接时会把当前位置默认设置为根目录,上传和下载的默认位置

sftp sftp_user@localhost

上传测试

[root@localhost ~]# cd /opt/
[root@localhost opt]# ls
[root@localhost opt]# touch test.txt
[root@localhost opt]# sftp sftp_user@localhost
sftp_user@localhost's password:
Connected to localhost.
sftp> ls
upload
sftp> cd upload/
sftp> ls
sftp> put test.txt
Uploading test.txt to /upload/test.txt
test.txt                                                                              100%    0     0.0KB/s   00:00
sftp>
sftp> exit
[root@localhost opt]# ll /sftp/sftp_user/upload/
total 0
-rw-r--r--. 1 sftp_user sftp_users 0 Sep 20 23:43 test.txt
[root@localhost opt]#

下载测试

[root@localhost ~]# ls
anaconda-ks.cfg
[root@localhost ~]# sftp sftp_user@localhost
sftp_user@localhost's password:
Connected to localhost.
sftp> cd /upload/
sftp> ls
test.txt
Fetching /upload/test.txt to /root/texit
sftp> get test.txt /root/test.txt
Fetching /upload/test.txt to /root/test.txt
sftp> exit
[root@localhost ~]# ls
anaconda-ks.cfg  test.txt
posted @ 2024-09-21 11:49  huhy  阅读(117)  评论(0)    收藏  举报  来源
--> --> /*文章评论*/