bash shell脚本中的su命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25619734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:16:31  来源:igfitidea点击:

su command in shell script

linuxbashshellunix

提问by user3331975

I have a script which copies a file, then untar and install it (agent-service) on multiple systems (IPs are read from systems.txt file). In the script, I wanted to start the agent-service as user "test". However after the script execution, when I check the target system, the agent-service is shown as running as "root" user. What could be wrong here? Am I not using su command correct within the script?

我有一个脚本,它复制一个文件,然后解压并在多个系统上安装它(代理服务)(IP 从 systems.txt 文件中读取)。在脚本中,我想以用户“test”的身份启动代理服务。但是,在脚本执行后,当我检查目标系统时,代理服务显示为以“root”用户身份运行。这里可能有什么问题?我在脚本中没有正确使用 su 命令吗?

~]# ps -ef | grep agent-service

    root     23511 15196  0 02:12 pts/3    00:00:00 agent-service

Script>

脚本>

#!/bin/bash
export AGENT=linux-5.8.1.tar.gz

while read host; do

scp $AGENT root@$host:/opt


ssh -n root@$host 'cd /opt/linux;
tar zxvf linux-5.8.1.tar.gz;
mkdir /opt/hyperic;
useradd -m test;
chown -R test:test /opt/linux;
su - test;
/opt/linux/agent-service start'

done < systems.txt

回答by Jean-Karim Bockstael

Using suas you do here spawns a new shell that has nothing to do thus exits immediately.

su像你在这里一样使用会产生一个新的外壳,它没有任何关系,因此会立即退出。

Either pass the command to su:

要么将命令传递给su

su - test -c /opt/linux/agent-service start

Or use sudoin a similar manner:

sudo以类似方式使用:

sudo -u test /opt/linux/agent-service start