如何在shell脚本中切换到其他用户并用新用户执行一些命令? [英] How to switch to different user inside a shell script and execute some command with the new user?
问题描述
我当前使用用户"USER1"登录到"SERVER1",并且我将bash脚本放在了这里.该脚本必须切换到同一服务器"SERVER1"上的不同用户"USER2",并用新切换的用户执行一些命令.
注意:USER1不是root用户,因此我需要在脚本中指定USER2密码,但是要采用加密格式.
请帮助我实现这一目标..
#!/bin/bashcommand1命令2.....回显"PASSWORD" |su USER2<<紧急行动command1命令2.....
请注意,我不想在此处更改任何配置文件来实现此目的.
将密码存储在脚本中或尝试将其流式传输到 su
中不是一个好主意.更好的方法是使用 sudo
.
由于您允许USER1在没有密码的情况下充当USER2,因此可以这样设置/etc/sudoers
:
USER1 localhost =(USER2)NOPASSWD:全部
然后您可以按USER1的方式调用 sudo
,如下所示:
sudo -u USER2 bash
如果要进一步锁定它,可以指定允许用户执行的脚本./etc/sudoers
中的行可能看起来像:
USER1 localhost =(USER2)NOPASSWD:/home/USER1/setup.sh
然后您会打电话给
sudo -u USER2/home/USER1/setup.sh
请注意,在最后一个示例中,我认为USER2需要在/etc/passwd
中配置一个实际的shell(即NOT /bin/false
)./p>
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.
Note: USER1 is not a root user, so i need to specify the USER2 password inside the script, but in a encrypted format.
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.
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
.
Since you're allowing USER1 to act as USER2 without a password, you can set up /etc/sudoers
like this:
USER1 localhost=(USER2) NOPASSWD: ALL
Then you can invoke sudo
as USER1 as follows:
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:
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
).
这篇关于如何在shell脚本中切换到其他用户并用新用户执行一些命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!