bash 如何在shell脚本中切换到不同的用户并使用新用户执行一些命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40668512/
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 switch to different user inside a shell script and execute some command with the new user?
提问by Rohith
I am currently logged into "SERVER1" with user "USER1", and i have placed my bash script here. This script has to switch to different user "USER2" on the same server "SERVER1" and execute some commands with the new switched user.
我目前使用用户“USER1”登录到“SERVER1”,并将我的 bash 脚本放置在这里。此脚本必须切换到同一服务器“SERVER1”上的不同用户“USER2”,并使用新切换的用户执行一些命令。
Note: USER1 is not a root user, so i need to specify the USER2 password inside the script, but in a encrypted format.
注意:USER1 不是 root 用户,所以我需要在脚本中指定 USER2 密码,但要采用加密格式。
Please help me in achieving this..!
请帮助我实现这一目标..!
#!/bin/bash
command1
command2
.
.
...
echo "PASSWORD" | su USER2 << EOF
command1
command2
.
.
...
Please note, i don't want to change any configuration files here to achieve this.
请注意,我不想在这里更改任何配置文件来实现这一点。
回答by paddy
It's not a good idea to store passwords in scripts, or attempt to stream them into su
. The better approach is to use sudo
.
将密码存储在脚本中或尝试将它们流式传输到su
. 更好的方法是使用sudo
.
Since you're allowing USER1 to act as USER2 without a password, you can set up /etc/sudoers
like this:
由于您允许 USER1 在没有密码的情况下充当 USER2,您可以这样设置/etc/sudoers
:
USER1 localhost=(USER2) NOPASSWD: ALL
Then you can invoke sudo
as USER1 as follows:
然后您可以sudo
以 USER1 身份调用,如下所示:
sudo -u USER2 bash
If you want to lock it down a bit more, you can specify a script that the user is allowed to execute. The line in /etc/sudoers
might look like:
如果你想再锁定一点,你可以指定一个允许用户执行的脚本。中的行/etc/sudoers
可能如下所示:
USER1 localhost=(USER2) NOPASSWD: /home/USER1/setup.sh
And you would call:
你会打电话给:
sudo -u USER2 /home/USER1/setup.sh
Note in this last example, I think that USER2 would need to have an actual shell configured in /etc/passwd
(i.e. NOT /bin/false
).
请注意,在最后一个示例中,我认为 USER2 需要在/etc/passwd
(即 NOT /bin/false
)中配置一个实际的外壳。