我想要求使用 以当前用户身份运行 bash 脚本sudo
,但如果直接以 root 用户身份执行,则阻止其运行。这是因为我正在为当前用户执行一些需要 root 权限的设置操作,但取决于SUDO_USER
正在设置的环境变量。
这是我目前所拥有的:
#!/usr/bin/env bash
# Require script to be run via sudo, but not as root
if [[ $EUID != 0 ]]; then
echo "Script must be run with root privilages!"
exit 1
elif [[ $EUID = $UID && "$SUDO_USER" = "" ]]; then
echo "Script must be run as current user via 'sudo', not as the root user!"
exit 1
fi
EUID
目前这可靠吗?我对检查 if和match有点不确定UID
,因为我不知道 ifUID
是否总是可靠地正确设置。检查 if 是否为空是否足够简单SUDO_USER
?
答案1
我认为这还不够,因为任何人都可以对 root 以外的用户使用 sudo:
[my.username@some_hostname ~]$ echo "'$SUDO_USER':'$UID':'$EUID'"
'':'503':'503'
[my.username@some_hostname ~]$ sudo -i -u zenoss
[zenoss@some_hostname ~]$ echo "'$SUDO_USER':'$UID':'$EUID'"
'my.username':'1337':'1337'
(CentOS 6.5,GNU bash,版本 4.1.2(1)-release(x86_64-redhat-linux-gnu))
我理解你对 UID/EUID 的看法,但我可能还是会坚持使用 $UID。不幸的是,即使是“bash info”也不是特别详细,但是一个受人尊敬的来源说:
$UID
User ID number
Current user's user identification number, as recorded in /etc/passwd
This is the current user's real id, even if she has temporarily assumed another
identity through su. $UID is a readonly variable, not subject to change from
the command line or within a script, and is the counterpart to the id builtin.
$EUID
"effective" user ID number
Identification number of whatever identity the current user has assumed,
perhaps by means of su.
Caution
The $EUID is not necessarily the same as the $UID.
答案2
ID=`id -u`
if [ $ID -ne 0 ]; then
echo "This command must be run as root."
exit 1
fi