以另一个没有密码的用户身份运行 shell 脚本

rub*_*o77 329 command-line bash sudo

我想以没有密码的其他用户身份从主 ubuntu shell 运行脚本。

我有完整的 sudo 权限,所以我尝试了这个:

sudo su -c "Your command right here" -s /bin/sh otheruser
Run Code Online (Sandbox Code Playgroud)

然后我必须输入我的密码,但我不确定该脚本现在是否真的在该用户下运行。

我如何确认脚本现在确实在该用户下运行?

gei*_*rha 464

你可以用su或来做到这一点sudo,不需要两者兼而有之。

sudo -H -u otheruser bash -c 'echo "I am $USER, with uid $UID"' 
Run Code Online (Sandbox Code Playgroud)

的相关部分man sudo

-H   The -H (HOME) option requests that the security policy set
     the HOME environment variable to the home directory of the
     target user (root by default) as specified by the password
     database.  Depending on the policy, this may be the default
     behavior.
Run Code Online (Sandbox Code Playgroud)
-u user     The -u (user) option causes sudo to run the specified
      command as a user other than root.  To specify a uid
      instead of a user name, use #uid.  When running commands as
      a uid, many shells require that the '#' be escaped with a
      backslash ('\').  Security policies may restrict uids to
      those listed in the password database.  The sudoers policy
      allows uids that are not in the password database as long
      as the targetpw option is not set.  Other security policies
      may not support this.
Run Code Online (Sandbox Code Playgroud)

su如果您是 root,则只能在不提供密码的情况下切换用户。见迦勒的回答

您可以修改/etc/pam.d/su文件以允许su无需密码。看到这个答案

如果您将 auth 文件修改为以下内容,则属于组的任何用户somegroup都可以suotheruser没有密码的情况下进行。

auth       sufficient pam_rootok.so
auth       [success=ignore default=1] pam_succeed_if.so user = otheruser
auth       sufficient   pam_succeed_if.so use_uid user ingroup somegroup
Run Code Online (Sandbox Code Playgroud)

然后从终端测试

rubo77@local$ su otheruser -c 'echo "hello from $USER"'
hello from otheruser
Run Code Online (Sandbox Code Playgroud)

  • 你也可以添加如何只用`su`来做到这一点吗? (4认同)
  • 这要求我输入密码:-( (2认同)

小智 140

如果你想使用 su 而不是 sudo,我相信你可以使用这样的东西:

su - <username> -c "<commands>"
Run Code Online (Sandbox Code Playgroud)
  • - 将模拟指定用户的登录
  • -c 告诉它你想运行一个命令

附:不幸的是,我无法通过这种方法使用 rvm 安装 ruby​​,但这可能无关。

  • 我需要在开头添加 `sudo`,否则它会询问我的密码。 (7认同)
  • 如果没有 `sudo`,这绝对行不通。使用 sudo 它可以工作,例如:`sudo su - www-data -c "touch /tmp/test"`成功创建了一个文件为 www-data (2认同)

Sam*_*und 11

上面的答案对我来说真的很有用,但要回答实际问题...

我如何确认脚本现在确实在该用户下运行? -

用:

ps -ef | grep <command-name>
Run Code Online (Sandbox Code Playgroud)

输出应包括您的脚本和执行它的实际用户。使用类似 BSD 的系统(例如 MAC)的人可以通过以下方式找到类似信息:

ps aux | grep <command-name>
Run Code Online (Sandbox Code Playgroud)


Res*_*zai 5

确保使用命令切换到 root 用户,sudo su然后使用命令

su user -s <command>
Run Code Online (Sandbox Code Playgroud)

例如: su www-data -s bin/magento cache:clean