![](/img/trans.png)
[英]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.