简体   繁体   English

如何在Shell脚本中切换到其他用户并用新用户执行一些命令?

[英]How to switch to different user inside a shell script and execute some command with the new user?

I am currently logged into "SERVER1" with user "USER1", and i have placed my bash script here. 我目前使用用户“ USER1”登录到“ SERVER1”,并且已将bash脚本放在此处。 This script has to switch to different user "USER2" on the same server "SERVER1" and execute some commands with the new switched user. 该脚本必须切换到同一服务器“ 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. 请注意,我不想在这里更改任何配置文件来实现此目的。

It's not a good idea to store passwords in scripts, or attempt to stream them into su . 将密码存储在脚本中或尝试将其流式传输到su不是一个好主意。 The better approach is to use sudo . 更好的方法是使用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: 然后,您可以按USER1的方式调用sudo ,如下所示:

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 (ie NOT /bin/false ). 注意在最后一个示例中,我认为USER2需要在/etc/passwd配置一个实际的shell(即NOT /bin/false )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM