我是这里的新手,也是bash / linux的新手。
我的老师给我分配了一个任务,使脚本仅在您是“真正” root时才可以运行,而在您使用sudo时不可以。经过两个小时的搜索和尝试,我开始认为他在欺骗我。只允许root是容易的,但是如何排除使用sudo运行root的用户呢?
这就是我所拥有的:
if [[ $EUID -ne 0 ]]; then
echo "You must be root to run this script."
exit
fi
我能想到的唯一方法是检查SUDO_*
sudo设置的环境变量之一:
#!/usr/bin/env sh
if [ "$(id -u)" -eq 0 ]
then
if [ -n "$SUDO_USER" ]
then
printf "This script has to run as root (not sudo)\n" >&2
exit 1
fi
printf "OK, script run as root (not sudo)\n"
else
printf "This script has to run as root\n" >&2
exit 1
fi
请注意,该解决方案当然不是面向未来的,因为您无法在运行脚本之前阻止任何人设置变量:
$ su
Password:
# SUDO_USER=whatever ./root.sh
This script has to run as root (not sudo)
# ./root.sh
OK, script run as root (not sudo)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句