简体   繁体   English

su和sudo在shell脚本中

[英]su and sudo in a shell script

There is a shell script (/bin/sh, not bash) that requires root permissions for execution. 有一个shell脚本(/ bin / sh,而不是bash)需要root权限才能执行。

If it is ran by a normal user it should ask user a password to get root access and re-run itself. 如果它由普通用户运行,它应该询问用户密码以获得root访问权并重新运行。

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. 这工作正常,但有一些像Ubuntu的操作系统根本没有root密码。 On the other hand, a lot of systems use sudo for root permissions. 另一方面,许多系统使用sudo进行root权限。

The question is: how can the script detect whether to use su or sudo without asking the user to enter too much passwords (eg enter sudo password, if it fails - run su ). 问题是:脚本如何检测是否使用susudo而不要求用户输入太多密码(例如输入sudo密码,如果失败 - 运行su )。

It shouldn't. 它不应该。 If script requires root privileges, it should be run as root. 如果脚本需要root权限,则应以root身份运行。 It's the user's business how he's going to accomplish that -- using su, sudo or some other mechanism. 这是用户的业务,他将如何实现这一目标 - 使用su,sudo或其他一些机制。

If you are concerned with security issues and don't want to do everything from root, you can drop root privileges for those parts. 如果您担心安全问题并且不想从root执行所有操作,则可以删除这些部分的root权限。

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. 例如,Debian和Ubuntu经常将系统文件放在Red Hat以外的目录中。 It's much easier to customize the script for the OS it's installed on. 为其安装的操作系统自定义脚本要容易得多。

You can setup the account not to need a password for sudo in /etc/sudoers: 您可以在/ etc / sudoers中设置帐户不需要sudo的密码:

yourusername ALL=(ALL) NOPASSWD: ALL

If you don't want to do that, you can force them to run the script as root. 如果您不想这样做,可以强制它们以root身份运行脚本。 Add something like this to the top of your shell script: 将这样的内容添加到shell脚本的顶部:

if [ "$UID" -ne 0 ]; then
    echo "You must be root to run this script"
    exit 1
fi

This way, the user can get to be root however they choose (su or sudo). 这样,用户可以选择root(但su或sudo)。

从此文件中再创建一个.sh文件,调用原始的.sh文件,如 -

su - oracle /u01/enlightics/Enlightiks/UploadFTP/ExportScript2.sh

Check if sudo ist installed 检查是否安装了sudo

SU='su'
which sudo > /dev/null && SU='sudo'

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: 虽然这不能完全回答您的问题,但值得注意的是,您可以使用以下方法检查是否安装了sudo软件包:

Debian based systems: 基于Debian的系统:

dpkg -s sudo

RPM based systems: 基于RPM的系统:

rpm -q sudo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM