標籤:
將Linux普通使用者添加為系統管理員在Gnome或KDE這樣強大與完善的案頭環境下是非常簡單的事情,一般來說在使用者佈建的對話方塊裡就直接有相應選項。不過,出於簡潔與高效的風格,自己目前並未使用這些高端但吃記憶體的“重量級”案頭環境,使用的就是最基本的X視窗+Sawfish視窗管理器的組合。在這樣的環境下進行使用者管理,都是通過命令列來完成。如,使用useradd命令添加新使用者。不過,由useradd命令添加的使用者只具有普通使用者的許可權,不具備系統管理的能力。這樣一來,就給一些常見的操作帶來不便,如,使用sudo命令臨時升級為管理員,燒錄光碟片,訪問藍牙裝置等。導致此現象的原因是,由useradd命令產生的使用者預設不屬於一些關鍵的系統管理組,比如:
adm dialout fax cdrom floppy tape sudo audio dip video plugdev netdev bluetooth lpadmin fuse scanner powerdev burning
為此,只要使用usermod命令將使用者添加到這些組即可。但每回如此操作多有不便,於是就可以寫一個指令碼程式來自動做這件事情。指令碼設計功能為:
- 將上述列出的組定義為系統管理員組列表。
- 指令碼程式可將命令列中指定的使用者添加到每個組中。若不指定使用者名稱,則將當前登入的使用者加入到組中。注,當前登入的使用者名稱可以用whoami命令查詢。
- 指令碼中定義函數add_to_groups。其第一個參數是待加為管理員的使用者名稱,第二個及之後所有的參數為上述Administrator 群組列表。函數會檢查指定使用者是否已經在Administrator 群組中。如果不在,則使用usermod命令將其加到組內。
基於自己制訂的Bash指令碼模板,寫成的指令碼add_admin.sh如下:
#!/bin/bashscript_name="add_admin.sh"script_usage=$(cat <<EOF$script_name [USER NAME]EOF)script_function=$(cat <<EOFThis script is used to add the current or specified users as system administrator.EOF)script_doc=$(cat <<EOF-h Display this help.EOF)script_examples=$(cat <<EOFEOF)state_prefix="==="warning_prefix="***"error_prefix="!!!"function display_help() { if [ -n "$script_usage" ]; then echo -e "Usage: $script_usage" fi if [ -n "$script_function" ]; then echo -e "$script_function" fi if [ -n "$script_doc" ] ; then echo -e "\n$script_doc" fi if [ -n "$script_examples" ]; then echo -e "\nExamples" echo -e "$script_examples" fi}function add_to_groups() { the_user="$1" shift 1 for the_group in "[email protected]" ; do if [ -n "`cat /etc/group | grep $the_group`" ]; then if [ -n "`groups $the_user | grep $the_group | cut -d ‘:‘ -f 2`" ]; then echo "$warning_prefix User ‘$the_user‘ has already been in the group ‘$the_group‘!" else sudo usermod -a -G $the_group $the_user echo "$state_prefix User ‘$the_user‘ has been added to the group ‘$the_group‘!" fi else echo "$warning_prefix The group ‘$the_group‘ does not exist!" fi done}# Process command optionswhile getopts ":h" opt; do case $opt in h ) display_help exit 0 ;; \? ) display_help exit 1 ;; esacdoneshift $(($OPTIND - 1))admin_groups="adm dialout fax cdrom floppy tape sudo audio dip video plugdev netdev bluetooth lpadmin fuse scanner powerdev burning"# Start execute the commandif [ $OSTYPE = ‘linux-gnu‘ ]; then # Get the user name if [ -n "$*" ]; then for the_user in "[email protected]" ; do if [ -n "`cat /etc/passwd | grep $the_user | cut -d ‘:‘ -f 1`" ]; then add_to_groups $the_user $admin_groups echo "$state_prefix User ‘$the_user‘ has been set as administrator!" else echo "$warning_prefix ‘$the_user‘ is not a valid user!" fi done else the_user=`whoami` echo "$state_prefix The current logged-on user ‘$the_user‘ will be set as administrator!" add_to_groups $the_user $admin_groups echo "$state_prefix User ‘$the_user‘ has been set as administrator!" fi exit 0fiecho "$warning_prefix Operating system or host name is not supported!"
用Bash指令碼將Linux普通使用者添加為系統管理員