[英]How can I execute commands as another user with their .bash_profile instead of the current user's?
[英]As a root user can I execute commands in BASH as another user without requiring a password?
我在 RHeL 服务器上有一个 root 用户帐户。 在该服务器上,我有一个名为user.sh
的简单脚本,它只返回当前用户:
#!/bin/bash
echo $USER
从我的根帐户运行时,output 是
bash user.sh
>>>root
从另一个脚本,我希望能够在不输入密码的情况下临时切换用户,将密码存储在脚本或文件中,或修改 /etc/sudoers并执行user.sh
然后返回到我的初始 root 帐户。 这是可能吗?
这是我到目前为止所尝试的:
#./bin/bash bash /user:sh su other_user <<EOF echo Current user: $USER EOF
output:
root Current user: root
切换到 bash 中的用户,执行命令然后注销
#./bin/bash bash /user.sh su other_user bash /user.sh exit
output:脚本暂停执行并将我返回到以other_user
登录的终端,但我仍将位于包含user.sh
的根帐户目录中
root [other_user@my_server]$
如果我然后键入exit
我将返回到我的根帐户并且脚本完成执行
使用su - <username> -c /path/to/the/shellscript.sh
以不同的帐户执行脚本,然后返回
#./bin/bash bash /user.sh su - other_user -c /path/user.sh
output:
root -bash: /path/user.sh: Permission denied
使用sudo -i -u other_user
以用户身份登录并执行脚本,这会产生与尝试 #2 相同的问题,但我被重定向到other_user
的主目录。
值得注意的是,如果我使用方法 2,当我以other_user
登录时,我能够运行bash user.sh
并产生所需的 output: other_user
在第二个示例中, $USER
变量在执行su
之前展开。 这可以通过引用EOF
来防止。
su other_user <<'EOF'
echo Current user: $USER
EOF
或者您可以在根 shell 中执行脚本,也可以使用 here-doc:
su other_user <<END
bash user.sh
END
或者您可以使用-c
选项su
:
su other_user -c 'bash user.sh'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.