我有一个程序,如果它在“sudo”下运行,应该有不同的行为.有没有办法可以找出它是否在sudo下运行?
更新:有人问我为什么要这样做.在这种情况下,在使用MacPorts的Mac上有输出,告诉您剪切并粘贴特定命令.如果MacPorts命令使用“sudo”运行,则它应该在示例命令中包含sudo:
$sudo port selfupdate ---> Updating MacPorts base sources using rsync MacPorts base version 2.2.1 installed,MacPorts base version 2.2.1 downloaded. ---> Updating the ports tree ---> MacPorts base is already the latest version The ports tree has been updated. To upgrade your installed ports,you should run port upgrade outdated ^^^^^^^^^ it would be really sweet if it output "sudo port upgrade outdated" instead. It would be even better if it just did it for you :-)
解决方法
是的,当程序在sudo下运行时,设置了4个环境变量:
$sudo env |grep SUDO SUDO_COMMAND=/usr/bin/env SUDO_USER=tal SUDO_UID=501 SUDO_GID=20
请注意,只需设置它们即可伪造.不要相信任何关键的东西.
例如:在此程序中,我们需要告诉用户运行其他程序.如果当前的一个是用sudo运行的,那么另一个也是.
#!/bin/bash echo 'Thank you for running me.' if [[ $(id -u) == 0 ]]; then if [[ -z "$SUDO_COMMAND" ]]; then echo 'Please now run: next_command' else echo 'Please now run: sudo next_command' fi else echo 'Error: Sadly you need to run me as root.' exit 1 fi
请注意,它只测试SUDO_ *变量,如果它可以首先证明它以root身份运行.即便如此,它只用它来改变一些有用的文字.