以另一个没有密码的用户身份运行shell脚本
我想从主ubuntu shell运行一个脚本作为没有密码的其他用户。
我有完整的sudo权限,所以我尝试了这个:
sudo su -c "Your command right here" -s /bin/sh otheruser
然后我必须输入我的密码,但我不确定该脚本现在是否真的在该用户下运行。
如何确认脚本现在真的在该用户下运行?
你可以用su
或sudo
来做到这一点,两者都不需要。
sudo -H -u otheruser bash -c 'echo "I am $USER, with uid $UID"'
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.
-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.
如果你是root用户, su
只能在不提供密码的情况下切换用户。 见迦勒的答案
您可以修改/etc/pam.d/su
文件以允许su
无密码。 看到这个答案 。
如果您将auth文件修改为以下内容,则属于somegroup
组的任何用户somegroup
可以在没有密码的情况下转到otheruser
用户。
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
然后从终端测试
rubo77@local$ su otheruser -c 'echo "hello from $USER"' hello from otheruser
如果你想使用su而不是sudo,我相信你可以使用这样的东西:
su - -c ""
-
-
将模拟指定用户的登录 -
-c
告诉它您要运行命令
PS。 不幸的是我无法使用rvm使用此方法安装ruby,但这可能与此无关。
上面的答案对我来说真的很有用,但回答实际问题……
我如何确认脚本现在真的在该用户下运行? –
使用:
ps -ef | grep
输出应包括您的脚本和执行它的实际用户。 类似BSD的系统上的人,例如MAC可以找到类似的信息:
ps aux | grep
我有同样的问题。 只需输入命令screen -dmS testscreen
这将在您的非sudo用户帐户上创建一个分离的屏幕,然后您可以记录它并通过screen -ls
检查该屏幕是否存在。