标签:
将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命令将用户添加到这些组即可。但每回如此操作多有不便,于是就可以写一个脚本程序来自动做这件事情。脚本设计功能为:
基于自己制订的Bash脚本模板,写成的脚本add_admin.sh如下:
#!/bin/bash script_name="add_admin.sh" script_usage=$(cat <<EOF $script_name [USER NAME] EOF ) script_function=$(cat <<EOF This 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 <<EOF EOF ) 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 "$@" ; 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 options while getopts ":h" opt; do case $opt in h ) display_help exit 0 ;; \? ) display_help exit 1 ;; esac done shift $(($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 command if [ $OSTYPE = ‘linux-gnu‘ ]; then # Get the user name if [ -n "$*" ]; then for the_user in "$@" ; 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 0 fi echo "$warning_prefix Operating system or host name is not supported!"
标签:
原文地址:http://www.cnblogs.com/quantumman/p/4581846.html