繁体   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