问题描述

        有一个脚本,只能是具有root执行权限的用户来执行。这意味着只有root用户和拥有sudo权限的用户才能执行,因此需要提供一个检测当前用户是否具有root执行权限的方法。

解决方案:

        1. 通过Linux shell command(whoami)命令得到当前用户名称

        2. 使用if语句判断当前用户是否是root?是root则继续执行。

        3. 否则,非root用户就需要检查其是否具有sudo权限,检查方法 sudo -l -U user_name | grep "(root) ALL".  如果查询结果为空代表当前用户没有sudo执行权限。以下shell是sudo -l -U user_name 的输出。

Matching Defaults entries for user_name on workstation:
    !visiblepw, always_set_home, env_reset, env_keep="COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORS", env_keep+="MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE", env_keep+="LC_COLLATE
    LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES", env_keep+="LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE", env_keep+="LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY",
    secure_path=/sbin\:/bin\:/usr/sbin\:/usr/bin

User user_name may run the following commands on workstation:
    (root) ALL
    (root) NOPASSWD: /usr/bin/acm-unlock-nfs4
    (root) NOPASSWD: /opt/ate/tools/bstd_tools/scm/lbin/Lx/chperm
    ...

  完整代码展示如下:           

#!/bin/bash

prefix=""
# determine whether the user has permission to execute this script
current_user=$(whoami)
if [ "$current_user" != "root" ]; then
        has_root_permission=$(sudo -l -U $current_user | grep "(root) ALL")
        if [ -n "$has_root_permission" ]; then
                echo "User $current_user has sudo permission"   
                prefix="sudo"
        else
                echo "User $current_user has no permission to execute this script!"
                exit 1
        fi
fi

# uninstall the existing rpm on the system
result=$(rpm -qa | grep rpm_name)
if [ -n "$result" ]; then
        echo "The existing $result is removed"
        ${prefix} rpm -e $result
fi

  Reference: Linux shell脚本之 if条件判断 https://blog.csdn.net/doiido/article/details/43966819

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐