【问题标题】:Can I run 'su' in the middle of a bash script?我可以在 bash 脚本中间运行“su”吗?
【发布时间】:2011-03-26 02:50:36
【问题描述】:

我可以在脚本中间更改/su 用户吗?

if [ "$user" == "" ]; then
  echo "Enter the table name";
  read user
fi

gunzip *
chown postgres *
su postgres 
dropdb $user
psql -c "create database $user with encoding 'unicode';" -U dbname template1
psql -d $user -f *.sql

【问题讨论】:

标签: bash shell


【解决方案1】:

参考下面问题的答案,

您可以在

#!/bin/bash
whoami
sudo -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami

How do I use su to execute the rest of the bash script as that user?

【讨论】:

  • 在 sudo 中添加 -i 以获取某些用户的环境。
【解决方案2】:

您可以使用here document 在脚本中嵌入多个su 命令:

if [ "$user" == "" ]; then
  echo "Enter the table name";
  read user
fi

gunzip *
chown postgres *
su postgres <<EOSU
dropdb $user
psql -c "create database $user with encoding 'unicode';" -U dbname template1
psql -d $user -f *.sql
EOSU

【讨论】:

  • 小心,我认为有些字符,比如反引号,如果你把它们放在一个here文档中,需要被转义。
  • 还要注意,heredoc 中的所有变量都在 传递给su 之前被替换。当您在内部创建和使用变量时,这可能是一个问题。为避免这种情况,请通过用单引号将第一个 EOSU 括起来来关闭参数替换,如下所示:su postgres &lt;&lt;'EOSU'
  • 请注意,== 不能保证在 [ 内工作。唯一的标准强制字符串比较运算符是=
【解决方案3】:

我今天听到的另一个有趣的想法是对脚本进行递归调用,当您以 root 身份运行并且想要以另一个用户身份运行脚本时。请看下面的例子:

我以“root”身份运行脚本“my_script”并希望该脚本以用户“raamee”身份运行


#!/bin/bash

#Script name is: my_script

user=`whoami`

if [ "$user" == "root" ]; then
  # As suggested by glenn jackman. Since I don't have anything to run once 
  # switching the user, I can modify the next line to: 
  # exec sudo -u raamee my_script and reuse the same process
  sudo -u raamee my_script
fi

if [ "$user" == "raamee" ]; then
  #put here the commands you want to perform
  do_command_1
  do_command_2
  do_command_3
fi

【讨论】:

  • 如果你在 "raamee" 工作后无事可做,那么你可以:exec sudo -u raamee my_script -- 替换当前进程而不是让它一直挂着。
  • 聪明,但这里的文档更简单(见我的回答)。
  • 需要记住的一点是 sudo`d 用户(如果不是 root)需要具有运行脚本本身的权限。
【解决方案4】:

可以,但是 bash 不会将后续命令作为 postgres 运行。相反,这样做:

su postgres -c 'dropdb $user'

-c 标志以用户身份运行命令(请参阅man su)。

【讨论】:

  • 你想在此处使用双引号:su postgres -c "dropdb $user"
  • 如果结束引号出现在另一行,您可以放置​​多行。在这种情况下请注意引用。
【解决方案5】:

不是这样的。 su 将调用一个进程,该进程默认为一个 shell。在命令行上,此 shell 将是交互式的,因此您可以输入命令。在脚本的上下文中,shell 将立即结束(因为它无事可做)。

su user -c command

command 将作为 user 执行 - 如果 su 成功,通常只有无密码用户或以 root 身份运行脚本时才会出现这种情况。

使用sudo 获得更好、更细粒度的方法。

【讨论】:

    【解决方案6】:

    不,你不能。或者至少...你可以 su 但 su 会在那时打开一个新的 shell,完成后它将继续执行脚本的其余部分。

    一种解决方法是使用su -c 'some command'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 2015-03-07
      • 2014-05-13
      • 1970-01-01
      相关资源
      最近更新 更多