PCDVD數位科技討論區
(https://www.pcdvd.com.tw/index.php)
- 疑難雜症區
(https://www.pcdvd.com.tw/forumdisplay.php?f=34)
- - 用shell寫一個script來建帳戶
(https://www.pcdvd.com.tw/showthread.php?t=1189341)
|
---|
用shell寫一個script來建帳戶
大家好,學校作業要求製作一個建user帳號的shell script,東拼西湊的,我寫得很心虛,希望大家幫我看看如何改進,謝謝
(建組名,建帳戶名,設密碼,提供改user id 與 group id的機會) #!/bin/bash if [ `whoami` = root ]; then echo "Please provide a group name:" else echo "Permission denied." fi read g groupadd $g echo "Group name '$g' has been created successfully." echo "Please provide a user name:" read u useradd $u echo "User account '$u' has been created successfully." read -p "Please enter the password for '$u' : " PASSWD echo "$PASSWD" | passwd --stdin $u &> /dev/null echo "Do you want to change group ID for '$g' (y/n)?" read gyn echo if [ $gyn == y ] then echo "Please enter the group ID for '$g':" read gid groupmod $g -g $gid echo echo "The group ID $gid is with the group '$g' now." elif [ $gyn == n ] then echo "Ok, nothing to change" fi echo "Do you want to change user ID for '$u' (y/n)?" read uyn echo if [ $uyn == y ] then echo "Please enter the user ID for '$u':" read uid usermod $u -u $uid echo echo "The user ID $uid is with the user '$u' now." elif [ $uyn == n ] then echo "Ok, nothing to change" fi |
可以考慮使用crack-lib 先檢查一下密碼不能設定太簡單
|
引用:
好的謝謝,這個作業讓我覺得寫東西真的不容易,要能夠用,真的還差太遠。 |
檢查有沒有重復ID!
|
引用:
我要先謝謝你20年的資深帳戶! 我試過建 '第二個peter',如果我記得沒錯,系統是回應peter已經存在,所以我就沒寫這個步驟。請問這樣正常嗎? |
可以參考 Debian 系列裡頭的 /usr/sbin/adduser 指令.
這是一個 perl script, 跟你要做的類似, 最後去執行真的 useradd 指令來新增使用者. |
引用:
好我再試試看! |
請善用function,這樣可以大幅減少程式碼,也好讀
還有~~有些時候善用return code可以讓工作更簡單 ex: 假設你系統有一個帳號叫做ansible,然後你又新增了ansible這個帳號 只要單純的檢查return code,就可以確認帳號有沒有建好 一些檢查工作就讓系統自己去處理即可 如果要做到更靈活應用,那麼getopt是一個不可或缺的功能 function範例 function get_input() { local q=$1 local v=$2 local answer="" read -p "${q}" -e -i ${v} answer [[ ${#answer} -eq 0 ]] && answer=$v echo $answer } gyn=$(get_input "Do you want to change user ID for ${u} (y/n)?" "y") 如果你if裡面要包的東西很少,可以考慮一行式判斷 [[ $gyn == n ]] && echo "Ok, nothing to change" PASSWD=$(get_input "Please enter the password for ${u}" $PASSWD) |
引用:
好強大! 請問哪本書可以學到這些專業技巧? 我買了一本酆士昌的「Linux Shell程式設計實力養成:225個實務關鍵技巧徹底詳解(附DVD)(第二版)」好像沒有您提到的內容? 感謝! |
引用:
你想問哪一塊? shell script基本上google一下一堆阿,我個人沒啥買書的 除了基本的case, do, while, if這些知道怎樣用 awk, sed, wc, sort, grep會組合(regular expression可以的話看一下) 加上function/array用法,應該就差不多了吧? 頂多有人會遇到IFS要特別處理問題 至於return code這個就真的是基礎到不行的東西 程式間交換狀態一般都是靠他 有些時候shell script寫太長,就會把每個function放到library來引用 舉例: lib.sh 裡面塞前面給你的function範例 main.sh source PATH/lib.sh gyn=$(get_input "Do you want to change user ID for ${u} (y/n)?" "y") 這樣你main裡面就會出現大量"人"讀得懂的邏輯,看起來也會清爽很多 |
所有的時間均為GMT +8。 現在的時間是07:01 PM. |
vBulletin Version 3.0.1
powered_by_vbulletin 2024。