shell 脚本中的 su 和 sudo
有一个 shell 脚本(/bin/sh,不是 bash)需要 root 权限才能执行。
如果它是由普通用户运行的,它应该要求用户输入密码以获得 root 访问权限并重新运行。
现在它使用以下代码:
if [ $(id -u) -ne 0 ];然后 su root -- $0 $@ ; ... fi
这工作得很好,但是有一些操作系统,比如 Ubuntu,根本没有 root 密码。另一方面,许多系统使用 sudo 来获取 root 权限。
问题是:脚本如何检测是否使用 su
还是 sudo
而不要求用户输入太多密码(例如输入 sudo
密码) ,如果失败 - 运行 su
)。
There is a shell script (/bin/sh, not bash) that requires root permissions for execution.
If it is ran by a normal user it should ask user a password to get root access and re-run itself.
Now it uses the following code:
if [ $(id -u) -ne 0 ]; then su root -- $0 $@ ; ... fi
That works fine, but there are some OS like Ubuntu that has no root password at all. On the other hand, a lot of systems use sudo for root permissions.
The question is: how can the script detect whether to use su
or sudo
without asking the user to enter too much passwords (e.g. enter sudo
password, if it fails - run su
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不应该。如果脚本需要 root 权限,则应以 root 身份运行。如何实现这一点是用户的事——使用 su、sudo 或其他机制。
如果您担心安全问题并且不想从 root 执行所有操作,则可以放弃这些部分的 root 权限。
It shouldn't. If script requires root privileges, it should be run as root. It's the user's business how he's going to accomplish that -- using su, sudo or some other mechanism.
If you are concerned with security issues and don't want to do everything from root, you can drop root privileges for those parts.
没有一种万无一失的方法可以做到这一点,因为任何发行版都可以按照它想要的任何方式放置文件。例如,Debian 和 Ubuntu 经常将系统文件放置在 Red Hat 以外的目录中。为所安装的操作系统自定义脚本要容易得多。
There isn't a bullet-proof way of doing this, because any distribution can lay files in any way it wants. Debian and Ubuntu often place system files in directories other than Red Hat, for example. It's much easier to customize the script for the OS it's installed on.
您可以在 /etc/sudoers 中将帐户设置为不需要 sudo 密码:
如果您不想这样做,您可以强制他们以 root 身份运行脚本。将类似这样的内容添加到 shell 脚本的顶部:
这样,用户可以通过选择(su 或 sudo)成为 root。
You can setup the account not to need a password for sudo in /etc/sudoers:
If you don't want to do that, you can force them to run the script as root. Add something like this to the top of your shell script:
This way, the user can get to be root however they choose (su or sudo).
从此文件再创建一个 .sh 文件,调用您的原始
.sh
文件,例如 -Create one more .sh file from this file call your original
.sh
file like -检查是否安装了 sudo
Check if
sudo
ist installed虽然这并不能完全回答您的问题,但值得注意的是,您可以使用以下命令检查 sudo 软件包是否已安装:
基于 Debian 的系统:
基于 RPM 的系统:
While this doesn't fully answer your question, it's worth noting that you can check if the sudo package is installed using the following:
Debian based systems:
RPM based systems: