【问题标题】:As a root user can I execute commands in BASH as another user without requiring a password?作为 root 用户,我可以作为另一个用户在 BASH 中执行命令而不需要密码吗?
【发布时间】:2019-11-08 20:16:45
【问题描述】:

我在 RHeL 服务器上有一个 root 用户帐户。在该服务器上,我有一个名为 user.sh 的简单脚本,它只返回当前用户:

#!/bin/bash
echo $USER

当从我的 root 帐户运行时,输出是

bash user.sh
>>>root

通过另一个脚本,我希望能够在不输入密码的情况下临时切换用户storing the password in the script or a filemodifying /etc/sudoers 并执行user.sh,然后返回到我的初始root 帐户。这有可能吗?

这是我迄今为止尝试过的:

  1. Using delimeters to execute a block of code

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

    输出:

    root
    Current user: root
    
  2. 在 bash 中切换到用户,执行命令然后退出

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

    输出:脚本暂停执行并将我返回到以other_user 登录的终端,但我仍将位于包含user.sh 的根帐户目录中

    root
    [other_user@my_server]$
    

    如果我随后输入exit,我将返回到我的根帐户并且脚本完成执行

  3. using the su - &lt;username&gt; -c /path/to/the/shellscript.sh to execute a script as a different account and then return

    #!/bin/bash
    
    bash /user.sh
    
    su - other_user -c /path/user.sh
    

    输出:

    root
    -bash: /path/user.sh: Permission denied
    
  4. 使用sudo -i -u other_user 以用户身份登录并执行脚本,这会产生与尝试#2 相同的问题,但我被重定向到other_user 的主目录。

值得注意的是,如果我使用方法 2,当我以 other_user 登录时,我可以运行 bash user.sh 并产生所需的输出:other_user

【问题讨论】:

    标签: linux bash root sudo rhel


    【解决方案1】:

    在第二个示例中,$USER 变量在执行 su 之前展开。这可以通过引用EOF 来防止。

    su other_user <<'EOF'
    echo Current user: $USER
    EOF
    

    或者您可以在 root shell 中执行脚本来执行此操作,也可以使用 here-doc:

    su other_user <<END
    bash user.sh
    END
    

    或者你可以使用-c选项来su

    su other_user -c 'bash user.sh'
    

    【讨论】:

    • 对。澄清一下,echo 命令以other_user 成功运行;您刚刚告诉它打印root,因为$USER 的扩展发生在su 之前。
    • 两种解决方案都有效!一个解决方案比另一个解决方案有什么好处,或者如果您有多个命令要执行,它只是使用第一个答案的问题?作为其他可能需要帮助解决相同问题的人的附注,如果您指定user.sh 的路径而不是保留它,上述代码将产生Permission Denied
    • 使用对特定用例最方便的方法。
    • 只有当other_user无法读取路径中的任何目录时才会产生权限被拒绝。
    猜你喜欢
    • 2013-07-19
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 2023-03-09
    • 2015-06-23
    • 1970-01-01
    • 2019-12-20
    • 2021-10-07
    相关资源
    最近更新 更多