[英]What's the best way to test if a user can sudo in Bash?
Reading the sudo man page, I see that the -v flag can be used to check if the user has sudo privileges in his workstation.阅读 sudo 手册页,我看到 -v 标志可用于检查用户是否在其工作站中具有 sudo 权限。 I have a piece of script that needs to test it.
我有一段脚本需要测试它。 If the user has not sudo privileges, it prints on screen:
如果用户没有 sudo 权限,它会在屏幕上打印:
Sorry, user tester may not run sudo on debian.
How can I suppress this message and just execute the rest of the code?我怎样才能抑制这条消息并只执行代码的 rest?
Try to append >/dev/null
in your command. 尝试在命令中附加
>/dev/null
。 In case the message is printed in stderr then use 2>/dev/null
or as advised in comments use &>/dev/null
to redirect both stdout and stderr to null. 如果在stderr中打印消息,则使用
2>/dev/null
或在注释中使用&>/dev/null
将stdout和stderr重定向到null。
If can_auto_sudo=$(sudo -l -n sudo &>/dev/null; echo $?)
is 0, you can sudo as much as you want.如果
can_auto_sudo=$(sudo -l -n sudo &>/dev/null; echo $?)
是0,你想sudo多少就sudo多少。
[ $EUID -eq 0 ] || exit 1
[ $EUID -eq 0 ] || exit 1
# Exit if not effectively root [ $EUID -eq 0 ] || exit 1
# 如果不是有效root则退出
sudo -l /usr/bin/program &>/dev/null || exit 2
sudo -l /usr/bin/program &>/dev/null || exit 2
# Exit if it can't run this as sudo sudo -l /usr/bin/program &>/dev/null || exit 2
# 如果它不能像 sudo 一样运行就退出
sudo -l -n /usr/bin/program &>/dev/null || exit 3
sudo -l -n /usr/bin/program &>/dev/null || exit 3
# Exit if requires interaction sudo -l -n /usr/bin/program &>/dev/null || exit 3
# 如果需要交互则退出
`sudo -ll -U $USER # tells you which commands can be runs with sudo by user (have to parse yourself) `sudo -ll -U $USER # 告诉你用户可以使用 sudo 运行哪些命令(必须自己解析)
[[ "$(printenv SUDO_USER)" = "" ]] || echo "$SUDO_USER is sudoing!" && exit 5
Using sudo -l or --list As per the man page, sudo can be used with -l or --list to get the list of allowed and forbidden commands for any particular user.使用 sudo -l 或 --list 根据手册页,sudo 可以与 -l 或 --list 一起使用以获取任何特定用户允许和禁止命令的列表。
The syntax would be: sudo -l [-AknS] [-a type] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command]语法为:sudo -l [-AknS] [-a type] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command]
If we use sudo --list without any arguments, then it will print the list of allowed and forbidden commands for the user who is executing the sudo command如果我们使用 sudo --list 而没有任何 arguments,那么它将为执行 sudo 命令的用户打印允许和禁止命令的列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.