這是一個添加用戶的小腳本,詳情請看代碼的註釋
#!/bin/bash ## @author enum.Lin ## @desc 這是一個自動生成用戶和密碼,並可以將用戶添加到sudoers 列表中的shell ######### 需要 root 的權限運行 ## 帶錯誤信息的退出函數 ############## function exitWithErrorMsg() { echo -e $1 read andKey exit 1 } # 收集用戶名 echo "please input your username..." read username # 檢測用戶是否存在 USER_COUNT=`cat /etc/passwd | grep "^$username:" -c` if [ $USER_COUNT -ne 0 ]; then exitWithErrorMsg "The account [$username] is exist."; fi # 收集用戶密碼 echo "please first input your paassword..." read -s firstPassword echo "please second input your username..." read -s secondPassword # 檢查兩次密碼輸入是否一致 if [ $firstPassword != $secondPassword ]; then exitWithErrorMsg "two input password is not sample!\ninput andy key exit shell..."; fi # 是否加入到sudoers 文件中 echo "Is add to sudoers 【yes/no】?no" read isSudoer # 新增和修改用戶密碼 adduser $username echo "$firstPassword" | passwd --stdin "$username" # 添加到 sudoers 列表 if [ "$isSudoer" = "yes" ]; then sudo echo "$username ALL=(ALL:ALL) ALL" >> /etc/sudoers echo "add user into sudoers list" fi ## 生成報告 echo "create user is success!" echo -e "username:$username\npaassword:$firstPassword\nadd2SudoerFlag:$isSudoer" echo "輸入任意鍵,退出界面,退出前,請保存好生成的賬號密碼!" read anyKey