萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 建立使用者與配置 FTP 存取權限完整教學:useradd、vsftpd、chroot 限制實戰

環境假設

  • CentOS/RHEL 5.6(舊版,現代系統請參考 systemd 版本)
  • Root 權限操作
  • FTP 服務為 vsftpd

一、建立使用者與基本屬性

1. 新增使用者(指定家目錄、主群組)

useradd -d /home/lch -g root lch
# -d 家目錄 -g 主群組 -s 指定 shell(如 /bin/bash)

2. 設定密碼

passwd lch

3. 群組管理

# 查看使用者群組
groups lch

# 變更主群組(-g)
usermod -g www lch

# 附加次要群組(-G,覆蓋原有次要群組)
usermod -G root,www lch

# 單純新增次要群組(-aG)
usermod -aG docker lch

4. 刪除使用者

userdel -r lch   # -r 連同家目錄一併刪除

二、vsftpd 核心配置(/etc/vsftpd/vsftpd.conf)

# 基礎安全
anonymous_enable=NO           # 禁止匿名登入
local_enable=YES              # 允許本地使用者
write_enable=YES              # 允許寫入
local_umask=022               # 上傳檔案權限遮罩

# 使用者清單控制(白名單模式)
userlist_enable=YES
userlist_deny=NO              # NO=白名單,YES=黑名單
userlist_file=/etc/vsftpd/user_list

# chroot 限制使用者無法跳出家目錄
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd/chroot_list
# 注:被列入 chroot_list 的使用者「不受」chroot 限制
# 若想「所有使用者都 chroot」,設定 chroot_local_user=YES 並留空 chroot_list

三、建立存取控制清單

# 1. 允許 FTP 登入的使用者白名單
echo "lch" >> /etc/vsftpd/user_list

# 2. 需要「不受 chroot 限制」的使用者(如管理員)
echo "admin" >> /etc/vsftpd/chroot_list

四、限制特定使用者僅能存取自身家目錄

預設情況下,使用者屬於同群組可互相存取。強制 chroot 隔離:

  1. 編輯 /etc/vsftpd/vsftpd.conf:
    chroot_local_user=YES # 所有本地使用者 chroot 到家目錄
  2. (可選)allow_writeable_chroot=YES # 允許家目錄可寫(vsftpd 2.3.5+ 安全要求)
  3. 重啟服務:service vsftpd restart

五、SELinux 相關設定(CentOS/RHEL 必看)

# 允許 FTP 讀寫家目錄
setsebool -P ftp_home_dir on
# 允許 FTP 完整存取
setsebool -P allow_ftpd_full_access on
# 查看 FTP 相關布林值
getsebool -a | grep ftp

六、防火牆開放端口

# iptables
iptables -A INPUT -p tcp --dport 21 -j ACCEPT
# 被動模式需開放資料連接埠範圍(vsftpd.conf 設定 pasv_min_port/pasv_max_port)
iptables -A INPUT -p tcp --dport 40000:40100 -j ACCEPT

# firewalld
firewall-cmd --permanent --add-service=ftp
firewall-cmd --permanent --add-port=40000-40100/tcp
firewall-cmd --reload

七、驗證測試

# 本機測試
ftp localhost
# 輸入 lch / 密碼
# 成功登入後
ls
put test.txt
get test.txt
bye

現代系統補充

  • CentOS 7+/RHEL 7+:systemctl enable --now vsftpd
  • Ubuntu/Debian:apt install vsftpd,配置檔在 /etc/vsftpd.conf
  • 建議改用 SFTP (SSH File Transfer Protocol):
    Subsystem sftp internal-sftp + ChrootDirectory %h 在 /etc/ssh/sshd_config,無需額外 FTP 服務,更安全。

遵循「建立帳號 → 配置 vsftpd 白名單與 chroot → SELinux/防火牆放行 → 測試驗證」流程,即可建立安全可控的 FTP 存取環境。

copyright © 萬盛學電腦網 all rights reserved