使用CentOs,我想运行一个脚本作为用户“培训”作为系统服务。 我使用daemontools监视进程,这需要一个以root身份运行的启动脚本,并且没有tty标准。
下面我给我五个不同的尝试都失败了。
:
#!/bin/bash exec >> /var/log/training_service.log 2>&1 setuidgid training training_command
这最后一行不够好,因为对于training_command,我们需要设置trqaining用户的环境。
:
su - training -c 'training_command'
这看起来像( 运行一个shell脚本作为一个不同的用户 ),但提供了“ standard in must be tty
”作为苏确保tty存在可能接受密码。 我知道我可以通过修改/ etc / sudoers来使这个消失(a la https://superuser.com/questions/119376/bash-su-script-giving-an-error-standard-in-must-bea-a- tty ),但我不情愿,不确定的后果。
:
sudo -u training -i bash -c 'source $HOME/.bashrc; training_command'
一个相同的主题的变化:' sudo: sorry, you must have a tty to run sudo
'
:
runuser - training -c 'training_command'
这一个给runuser: cannot set groups: Connection refused
。 我发现没有任何意义或解决这个错误。
:
ssh -p100 training@localhost 'source $HOME/.bashrc; training_command'
这更像是一个笑话,performance出绝望。 即使这个Host key verification failed.
(主机密钥IS在known_hosts等)。
注意:如果我从根shell运行包装脚本,2,3,4的所有工作都应该如此。 问题只发生在系统服务监视器(daemontools)启动它(没有ttyterminal,我猜)。
我被困住了。 这是难以实现的吗?
我感谢所有的洞察力和指导最佳实践。
(这也被张贴在超级用户上: https : //superuser.com/questions/434235/script-calling-script-as-other-user )
您将需要禁用/etc/sudoers
的requiretty
设置。 通过visudo
添加以下行:
Defaults:root !requiretty
你还需要/etc/sudoers
的以下行,这样root
可以做所有的事情(默认情况下这应该是启用的,但是检查确定):
root ALL=(ALL) ALL
然后你可以做到以下几点:
sudo -u training /path/to/training_command
这似乎本质上是这个问题的一个特例。 我们可以用script -c
来伪造一个tty。 唯一的问题是,由于某些原因,我无法直接使用su
来操作sudo
如果你真的需要在training_command
之前获取~/.bashrc
, sudo
有点难看。 尝试:
echo password | script -c "sudo su - training -c training_command"
select第一个,然后设置你需要的环境variables。
如果您已经使用daemontools,那么您不会手动创build或混淆日志文件。 Daemontools为你做这个工作。
这是应用程序运行脚本的脚本
#!/bin/bash exec 2>&1 exec setuidgid training sh -c 'YOURVARIABLE=yourvalue exec training_command'
然后你用自己的脚本创build一个log
目录运行脚本。
请参阅此条目以设置日志: http : //cr.yp.to/daemontools/faq/create.html#runlog
剽窃我的答案在这里: 作为另一个用户启动一个脚本
你可以使用start-stop-daemon这样的东西:
/sbin/start-stop-daemon --background --start --exec /path/to/training.sh --user training --pidfile=/path/to/training.pid --make-pidfile
其中training.sh是这样的:
#!/bin/sh exec >> /var/log/training_service.log 2>&1 source /home/training/.bashrc training_command
在SSH下,你可以在普通用户下运行命令foo.sh
:
$ ssh [email protected] bash /path/to/foo.sh
如果有一个foo.sh
的命令需要root权限,例如netstat
,像这样在su
命令中包装它(replace原始的netstat -tunple
):
su -c "netstat -tunpl" root
并像这样运行foo.sh
:
$ ssh -t [email protected] bash /path/to/foo.sh
这将提示input密码,第一个是normal_user
,第二个是root
。
用SSH运行你的命令。
使ssh密钥configuration为其他用户无需密码login。 这是一个教程为此目的: https : //www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys–2
用ssh运行命令:ssh -l training -i key_file“training_command”
尝试这个:
#!/bin/bash sudo -u training training_command > /var/log/training_service.log 2>&1
如果失败,请发布/var/log/training_service.log的输出。