sudo 用于 bash 脚本中的单个命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5919108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:57:22  来源:igfitidea点击:

sudo for single command in bash script

bashscriptingsudo

提问by rick

This may be a stupid question.

这可能是一个愚蠢的问题。

I have a script that I want to be portable between Mac OS X and a Linux box I use. In OS X, a command in the script requires sudo, where on the Linux box, it does not.

我有一个脚本,我想在 Mac OS X 和我使用的 Linux 机器之间移植。在 OS X 中,脚本中的命令需要sudo,而在 Linux 机器上则不需要。

Long story short, how does one run one command in a script with sudo, while then removing the elevated privileges for the rest of the script?

长话短说,如何在脚本中使用 运行一个命令sudo,同时删除脚本其余部分的提升权限?

I have tried to use

我试过用

su -

and

su -c

but they both seem to error out. (They say "sorry" and move on, I assume because it is trying to run as rootand rootdoes not have a password).

但他们似乎都出错了。(他们说“对不起”然后继续前进,我猜是因为它试图运行root并且root没有密码)。

I know there has to be a silly and easy way to do this, what does everyone suggest?

我知道必须有一种愚蠢而简单的方法来做到这一点,每个人都有什么建议?

采纳答案by sehe

You can 'revoke' the sudo permission (actually: close the sudo time window early) by doing:

您可以通过执行以下操作来“撤销”sudo 权限(实际上:提前关闭 sudo 时间窗口):

sudo -k

Also, you can configure sudo to only allow elevated permissions on certain commands, or even to impersonate non-root for specific commands. See man sudoers. The examples sectionmakes it exceedingly clear that there is virtually no limit to the configurability of sudo (roles, hosts, commands, allow escaping, allow sudo target users, exceptions to allowed things, password less authorization etc etc).

此外,您可以将 sudo 配置为仅允许对某些命令进行提升的权限,甚至可以为特定命令模拟非 root 用户。见man sudoers。该示例部分使得它非常清楚的是,几乎没有限制须藤的可配置性(角色,主机,命令,允许逃逸,让sudo的目标用户,例外允许的事情,密码授权少等等等等)。

Hopefully an interesting example in your context:

希望在您的上下文中是一个有趣的例子:

The user fred can run commands as any user in the DB Runas_Alias (oracle or sybase) without giving a password.

   fred           ALL = (DB) NOPASSWD: ALL

用户 fred 可以作为 DB Runas_Alias(oracle 或 sybase)中的任何用户运行命令,而无需提供密码。

   fred           ALL = (DB) NOPASSWD: ALL


If you can't / don't really want to meddle with /etc/sudoers (visudo!) then I suggest using something like

如果你不能/不想干涉 /etc/sudoers (visudo!) 那么我建议使用类似的东西

{
     trap "sudo -k" EXIT INT QUIT TERM
     sudo ls # whatever
}

回答by Gordon Davisson

Use sudowithout su:

sudo不使用su

#!/bin/bash
whoami  # Runs under your regular account
sudo whoami  # Runs as root
whoami  # Runs under your regular account again

Here's the output when I run it:

这是我运行时的输出:

$ ./sudotest
gordon
Password:
root
gordon

回答by Adam Rosenfield

Try sudo suinstead of suto change back to a regular user.

尝试sudo su而不是su改回普通用户。