sudo 用于 bash 脚本中的单个命令
这可能是一个愚蠢的问题。
我有一个脚本,希望能够在 Mac OS X 和我使用的 Linux 机器之间移植。在 OS X 中,脚本中的命令需要 sudo
,而在 Linux 机器上则不需要。
长话短说,如何使用 sudo 在脚本中运行一个命令,然后删除脚本其余部分的提升权限?
我尝试过使用
su -
and
su -c
但它们似乎都出错了。 (他们说“抱歉”并继续前进,我认为是因为它试图以 root
身份运行,而 root
没有密码)。
我知道必须有一种愚蠢而简单的方法来做到这一点,每个人都建议什么?
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.
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?
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 root
and root
does not have a password).
I know there has to be a silly and easy way to do this, what does everyone suggest?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过执行以下操作来“撤销” sudo 权限(实际上:提前关闭 sudo 时间窗口):
此外,您可以将 sudo 配置为仅允许对某些命令提升权限,甚至可以模拟非 root 来执行特定命令。请参阅
man sudoers
。 示例部分非常清楚地表明,sudo 的可配置性实际上没有限制(角色、主机、命令、允许转义、允许 sudo 目标用户、允许事物的例外、无密码授权等) )。希望在您的上下文中有一个有趣的例子:
如果你不能/不想干涉 /etc/sudoers (visudo!) 那么我建议使用类似的东西
You can 'revoke' the sudo permission (actually: close the sudo time window early) by doing:
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 section makes 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).Hopefully an interesting example in your context:
If you can't / don't really want to meddle with /etc/sudoers (visudo!) then I suggest using something like
尝试使用
sudo su
而不是su
来改回普通用户。Try
sudo su
instead ofsu
to change back to a regular user.使用
sudo
而不使用su
:这是我运行时的输出:
Use
sudo
withoutsu
:Here's the output when I run it: