Linux 如何在没有密码的情况下以另一个用户身份运行脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6905697/
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
How to run script as another user without password?
提问by user788171
I have script.sh that must be run as user2. However, this script can only be run under user1 in my application.
我有必须以 user2 身份运行的 script.sh。但是,此脚本只能在我的应用程序中的 user1 下运行。
I would like the following command to run:
我希望运行以下命令:
su user2 -C script.sh
but be able to run without password.
但无需密码即可运行。
I also want this to be very restrictive, as in user1 can only run script.sh under user2 and nothing else.
我也希望这是非常严格的,因为在 user1 中只能在 user2 下运行 script.sh 而没有别的。
I've tried doing this with sudoers file and just got endlessly confused after hours of trying.
我试过用 sudoers 文件来做这件事,但经过几个小时的尝试,我却无休止地感到困惑。
If somebody can provide an explicit example of how this can be accomplished (instead of something generic like use sudoers), it would be greatly appreciated.
如果有人可以提供一个明确的例子来说明如何实现这一点(而不是像使用 sudoers 这样的通用方法),我们将不胜感激。
采纳答案by pyroscope
Call visudo
and add this:
调用visudo
并添加:
user1 ALL=(user2) NOPASSWD: /home/user2/bin/test.sh
The command paths must be absolute! Then call sudo -u user2 /home/user2/bin/test.sh
from a user1
shell. Done.
该命令路径必须是绝对的!然后sudo -u user2 /home/user2/bin/test.sh
从user1
shell调用。完毕。
回答by Jeronimo Robles
try running:
尝试运行:
su -c "Your command right here" -s /bin/sh username
This will run the command as username given that you have permissions to sudo as that user.
鉴于您有权以该用户的身份执行 sudo,这将以用户名运行命令。
回答by C Jaskoski
`su -c "Your command right here" -s /bin/sh username`
The above command is correct, but on Red Hat if selinux is enforcing it will not allow cron to execute scripts as another user. example;
execl: couldn't exec /bin/sh
execl: Permission denied
上面的命令是正确的,但是在 Red Hat 上,如果 selinux 强制执行,它将不允许 cron 以其他用户身份执行脚本。例子;
execl: couldn't exec /bin/sh
execl: Permission denied
I had to install setroubleshoot and setools and run the following to allow it:
我必须安装 setroubleshoot 和 setools 并运行以下命令以允许它:
yum install setroubleshoot setools
sealert -a /var/log/audit/audit.log
grep crond /var/log/audit/audit.log | audit2allow -M mypol
semodule -i mypol.p