Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 批量建立用戶 Shell 腳本(有規律/無規律雙模式)

編輯:Linux 教學

模式一:有規律用戶名(前綴 + 數字)

#!/bin/bash
# batch_user_regular.sh
# 互動式輸入:前綴、數量、密碼前綴

read -p "用戶名前綴: " PREFIX
read -p "建立數量: " COUNT
read -p "密碼前綴: " PASS_PREFIX
read -p "加入附屬群組 (預設 sshd): " GROUP
GROUP=${GROUP:-sshd}

for ((i=1; i<=COUNT; i++)); do
    USER="${PREFIX}${i}"
    PASS="${PASS_PREFIX}${i}"
    if id "$USER" &>/dev/null; then
        echo "用戶 $USER 已存在,跳過"
        continue
    fi
    useradd -m -s /bin/bash "$USER"
    usermod -aG "$GROUP" "$USER"
    echo "$USER:$PASS" | chpasswd
    echo "建立 $USER 密碼 $PASS"
done
echo "批量建立完成"

模式二:無規律用戶名(從檔案讀取)

#!/bin/bash
# batch_user_list.sh
# 用法:./batch_user_list.sh user_list.txt
# 檔案每行一個用戶名,密碼統一為 "用戶名+888" 或自定義

LIST_FILE=$1
DEFAULT_SUFFIX="888"
GROUP="sshd"

[ -f "$LIST_FILE" ] || { echo "檔案 $LIST_FILE 不存在"; exit 1; }

while IFS= read -r USER; do
    [ -z "$USER" ] && continue
    if id "$USER" &>/dev/null; then
        echo "用戶 $USER 已存在,跳過"
        continue
    fi
    PASS="${USER}${DEFAULT_SUFFIX}"
    useradd -m -s /bin/bash "$USER"
    usermod -aG "$GROUP" "$USER"
    echo "$USER:$PASS" | chpasswd
    echo "建立 $USER 密碼 $PASS"
done < "$LIST_FILE"
echo "批量建立完成"

user_list.txt 範例

zhangsan
lisi
wangwu
zhaoliu

安全加固建議

  • 密碼複雜度: 生產環境請用 openssl rand -base64 12 生成隨機密碼,並透過安全管道分發(如加密郵件、密碼管理器),不可寫死在腳本或日誌中。
  • 最小權限: 僅加入必要群組(如 sshd),避免加入 wheel/sudo。
  • 審計日誌: 腳本輸出重導向至 /var/log/batch_user.log,保留操作紀錄。
  • 鎖定未用帳號: 批量建立後,定期 lastlog -b 90 檢查長期未登入帳號並 usermod -L 鎖定。

進階:使用 newusers 批量導入(非互動、極快)

# 準備輸入檔 newusers.txt
# 格式:用戶名:密碼:UID:GID:註釋:家目錄:Shell
user001:Passw0rd1:1001:1001:Batch User:/home/user001:/bin/bash
user002:Passw0rd2:1002:1001:Batch User:/home/user002:/bin/bash

newusers newusers.txt
# 自動建立用戶、家目錄、設定密碼

注意: newusers 不支援附屬群組,需後續 usermod -aG 補充。

總結

根據用戶名是否有規律,選擇迴圈建立或讀檔建立;大量(百以上)可用 newusers 提速。務必遵循最小權限、強密碼、操作留痕三原則,將批量建帳變為可控、可審計的標準化運維動作。

Copyright © Windows教程網 All Rights Reserved