[英]As a root user can I execute commands in BASH as another user without requiring a password?
I have a root user account on an RHeL server.我在 RHeL 服务器上有一个 root 用户帐户。 On that server I have a simple script called user.sh
that just returns the current user:在该服务器上,我有一个名为user.sh
的简单脚本,它只返回当前用户:
#!/bin/bash
echo $USER
when run from my root account the output is从我的根帐户运行时,output 是
bash user.sh
>>>root
From another script I would like to be able to temporarily switch between users without entering a password, storing the password in the script or a file , or modifying /etc/sudoers and execute user.sh
and then return back to my initial root account.从另一个脚本,我希望能够在不输入密码的情况下临时切换用户,将密码存储在脚本或文件中,或修改 /etc/sudoers并执行user.sh
然后返回到我的初始 root 帐户。 Is this at all possible?这是可能吗?
Here's what I've tried so far:这是我到目前为止所尝试的:
Using delimeters to execute a block of code 使用分隔符执行代码块
#./bin/bash bash /user:sh su other_user <<EOF echo Current user: $USER EOF
output: output:
root Current user: root
switching to a user in bash, executing a command and then logging back out切换到 bash 中的用户,执行命令然后注销
#./bin/bash bash /user.sh su other_user bash /user.sh exit
output: The script pauses execution and returns me to the terminal logged in as other_user
however I will still be in my root account's directory that contains user.sh
output:脚本暂停执行并将我返回到以other_user
登录的终端,但我仍将位于包含user.sh
的根帐户目录中
root [other_user@my_server]$
if I then type exit
I'm returned to my root account and the script completes execution如果我然后键入exit
我将返回到我的根帐户并且脚本完成执行
using the su - <username> -c /path/to/the/shellscript.sh
to execute a script as a different account and then return 使用su - <username> -c /path/to/the/shellscript.sh
以不同的帐户执行脚本,然后返回
#./bin/bash bash /user.sh su - other_user -c /path/user.sh
output: output:
root -bash: /path/user.sh: Permission denied
using sudo -i -u other_user
to log in as the user and execute the script which yields the same problem experienced with attempt #2 but I am redirected to other_user
's home directory.使用sudo -i -u other_user
以用户身份登录并执行脚本,这会产生与尝试 #2 相同的问题,但我被重定向到other_user
的主目录。
It may be worth noting that if I use method 2, while I'm logged in as other_user
I am able to run bash user.sh
and yield the desired output: other_user
值得注意的是,如果我使用方法 2,当我以other_user
登录时,我能够运行bash user.sh
并产生所需的 output: other_user
In the second example, the $USER
variable is expanded before su
is executed.在第二个示例中, $USER
变量在执行su
之前展开。 This can be prevented by quoting EOF
.这可以通过引用EOF
来防止。
su other_user <<'EOF'
echo Current user: $USER
EOF
Or you can execute the script to do it in the root shell, also using a here-doc:或者您可以在根 shell 中执行脚本,也可以使用 here-doc:
su other_user <<END
bash user.sh
END
or you can use the -c
option to su
:或者您可以使用-c
选项su
:
su other_user -c 'bash user.sh'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.