跳到主內容

【Shell】【Tool】批次更新密碼

如果有許多使用者需要批次重設密碼並強制其在下次登入時更新,可以使用一個簡單的 Shell 腳本來自動化這個過程。假設你有一個包含所有目標使用者名稱的文字檔,例如 users.txt,可以按照以下步驟操作:

  1. 建立使用者清單

    在 users.txt 中列出所有需要重設密碼的使用者名稱,每行一個。例如:

    user1
    user2
    user3
    
  2. 編寫批次重設密碼的腳本

    建立一個 Shell 腳本,批次執行密碼重設並強制更新。例如,將以下內容儲存為 reset_password.sh

    #!/bin/bash
    
    # 檢查 users.txt 是否存在
    if [[ ! -f users.txt ]]; then
        echo "Error: users.txt not found!"
        exit 1
    fi
    
    # 循環讀取每一個使用者
    while IFS= read -r username; do
        # 跳過空行
        if [[ -z "$username" ]]; then
            continue
        fi
    
        # 設定預設密碼或隨機密碼
        new_password="DefaultPassword123" # 或使用 `new_password=$(openssl rand -base64 12)` 生成隨機密碼
        echo "重設 $username 的密碼為 $new_password"
    
        # 重設密碼
        echo "$username:$new_password" | sudo chpasswd
    
        # 強制下次登入時更改密碼
        sudo chage -d 0 "$username"
    
        echo "$username 的密碼已重設並強制更新"
    done < users.txt
    
  3. 執行腳本

    為腳本增加執行權限,然後執行:

    chmod +x reset_password.sh
    sudo ./reset_password.sh
    
  4. 檢查結果

    執行完成後,你可以再次使用 chage -l username 指令逐一檢查使用者的密碼到期設定,確認是否成功。

這樣便可批次重設多位使用者的密碼,並強制其在下次登入時更新密碼。