首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在bash脚本中,如何使用su将根用户更改为另一个用户,然后退出?

在bash脚本中,如何使用su将根用户更改为另一个用户,然后退出?
EN

Ask Ubuntu用户
提问于 2023-02-25 21:01:09
回答 1查看 444关注 0票数 0

我看过如何在脚本中运行“sudo”命令?,但这似乎是另一个问题。

我想要运行一个脚本,使用su从root用户更改为主用户,运行Rails命令,然后退出到根帐户并重新启动mastodon。

手动,我可以通过ssh root@123.456.78.90登录到根目录,这给了我root@Mastodon:~# shell。然后,我使用sudo su - mastodon更改为乳齿象帐户(没有提示输入密码),然后是cd live。然后我可以运行Rails命令等等,它们可以工作,然后我可以exit和运行systemctl restart mastodon-*

但是我的shell脚本做同样的事情不起作用。restartall脚本是

代码语言:javascript
复制
#!/bin/bash

sudo su - mastodon

cd live

RAILS_ENV=production bundle exec rake tmp:cache:clear

RAILS_ENV=production bundle exec rails assets:generate_static_pages

RAILS_ENV=production bundle exec rails assets:precompile

exit

systemctl restart mastodon-*

我是这样运行的,root@Mastodon:~# ./restartall

终端用户和路径更改为mastodon@MyMastodon,但仅此而已;脚本在wth:./restartall: line 5: cd: live: No such file or directory中失败

我也试过root@Mastodon:~# sudo ./restartall

在使用su更改为mastodon用户时,我做错了什么?

简单地使用exit是否会正确地将脚本带回systemctl restart mastodon-*之前的root@Mastodon

EN

回答 1

Ask Ubuntu用户

回答已采纳

发布于 2023-02-25 22:31:10

这一失败的原因是sudo su - mastodon以用户mastodon的身份启动了一个新的交互式shell。下面的任何命令在shell退出之前都不会执行。

您可以通过其su选项将命令传递给-c,如前面的问题苏之后,脚本就停止工作了.中所述,因此

代码语言:javascript
复制
#!/bin/bash

sudo su -l mastodon -c '
  cd live
  RAILS_ENV=production bundle exec rake tmp:cache:clear
  RAILS_ENV=production bundle exec rails assets:generate_static_pages
  RAILS_ENV=production bundle exec rails assets:precompile
'

systemctl restart mastodon-*

(在通过-c传递的命令的末尾不需要显式的su,因为非交互式D8外壳在要执行的命令用完后自然退出)。

或者,您可以使用这里的文档通过标准输入将命令传递给su shell,如如何编写脚本,在su之后运行命令,而不使用-c中所描述的,但是请注意警告本身从stdin读取的命令。

但是,您可以考虑完全避免使用su,并编写脚本,以便它检查运行它的人,并在需要时作为目标用户重新执行自己,如

代码语言:javascript
复制
#!/bin/bash

rails_user=mastodon

if [[ $EUID -ne $(id -u $rails_user) ]]; then
  echo "Switching to user '$rails_user' to perform tasks"
  exec sudo -iu "$rails_user" "$(realpath $0)"
fi

cd live
# etc.
票数 2
EN
页面原文内容由Ask Ubuntu提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://askubuntu.com/questions/1456730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档