簡體   English   中英

作為 root 用戶,我可以作為另一個用戶在 BASH 中執行命令而不需要密碼嗎?

[英]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 帳戶。 這是可能嗎?

這是我到目前為止所嘗試的:

  1. 使用分隔符執行代碼塊

    #./bin/bash bash /user:sh su other_user <<EOF echo Current user: $USER EOF

    output:

     root Current user: root
  2. 切換到 bash 中的用戶,執行命令然后注銷

    #./bin/bash bash /user.sh su other_user bash /user.sh exit

    output:腳本暫停執行並將我返回到以other_user登錄的終端,但我仍將位於包含user.sh的根帳戶目錄中

    root [other_user@my_server]$

    如果我然后鍵入exit我將返回到我的根帳戶並且腳本完成執行

  3. 使用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
  4. 使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM