Web 表單收集帳號密碼 → PHP 呼叫系統指令建立 FreeBSD 系統使用者(等同 FTP 帳號) → 設定專用 Shell 禁止 Telnet/SSH → 建立家目錄與 public_html → 設定擁有者權限。
# 建立 ftpuser 群組(一次性)
pw groupadd ftpuser
# 建立限制 Shell(/bin/ftponly)
#!/bin/csh
cat << 'EOF'
You can only use this username to login FTP server!
And you can not use it to telnet to this system!
EOF
sleep 10
exit
# chmod +x /bin/ftponly
# 將 /bin/ftponly 加入 /etc/shells
<?php
if (isset($_POST['username'], $_POST['userpasswd'])) {
$username = escapeshellarg($_POST['username']);
$password = escapeshellarg($_POST['userpasswd']);
$rootPwd = 'your_root_password'; // 建議用 SSH Key 或 sudoers 免密執行特定指令
// 1. 建立系統使用者(需 root 權限)
$cmd = "echo $password | pw useradd $username -s /bin/ftponly -g ftpuser -h 0";
exec("su root -c $cmd", $out, $ret);
if ($ret !== 0) die("建立使用者失敗: " . implode("\n", $out));
// 2. 建立家目錄
foreach (['', '/public_html'] as $sub) {
$dir = "/home/$username$sub";
exec("su root -c 'mkdir -p " . escapeshellarg($dir) . "'", $out, $ret);
if ($ret !== 0) die("建立目錄 $dir 失敗");
// 設定擁有者
exec("su root -c 'chown " . escapeshellarg($username) . " " . escapeshellarg($dir) . "'", $out, $ret);
if ($ret !== 0) die("chown $dir 失敗");
}
echo "恭喜 $username,FTP 帳號建立成功!請使用 FTP 客戶端登入(無 Telnet 權限)。";
exit;
}
?>
escapeshellarg() 防指令注入,帳號密碼僅允許字母數字底線。wheel 群組,配置 sudoers 僅允許執行特定 pw useradd/mkdir/chown 指令,免輸入 root 密碼。ssh root@localhost "cmd" 金鑰認證,或 sudo -u root。/bin/ftponly 只顯示警告訊息並睡眠 10 秒退出,有效阻擋 Telnet/SSH 互動登入。public_html 755,FTP 根目錄限制在 public_html(vsftpd local_root=public_html)。