如何在初始化脚本中以特定用户身份运行命令? [英] How to run a command as a specific user in an init script?
问题描述
我正在编写一个初始化脚本,它应该以不同于 root 的用户身份执行单个命令.这就是我目前的做法:sudo -u 用户名命令
I'm writing an init script which is supposed to execute a single command as a user different than root. This is how I'm doing it currently:
sudo -u username command
这通常在 Ubuntu/Debian 上按预期工作,但在 RHEL 上,作为 command
执行的脚本挂起.
是否有其他方法可以以其他用户身份运行命令?
(请注意,我不能使用 lsb init 函数,因为它们在 RHEL/Centos 5.x 上不可用.)
This generally works as expected on Ubuntu/Debian, but on RHEL the script which is executed as the command
hangs.
Is there another way to run the command as another user?
(Note that I can't use lsb init functions as they're not available on RHEL/Centos 5.x.)
推荐答案
在 RHEL 系统上,/etc/rc.d/init.d/functions
脚本旨在提供类似于您的想.如果您在初始化脚本的顶部获取它,则它的所有功能都可用.
On RHEL systems, the /etc/rc.d/init.d/functions
script is intended to provide similar to what you want. If you source that at the top of your init script, all of it's functions become available.
提供帮助的具体功能是daemon
.如果你打算用它来启动一个类似守护进程的程序,一个简单的用法是:
The specific function provided to help with this is daemon
. If you are intending to use it to start a daemon-like program, a simple usage would be:
daemon --user=username command
如果这对您的需要来说过于笨拙,则可以使用 runuser
(请参阅 man runuser
了解完整信息;某些版本可能需要 -u
在用户名之前):
If that is too heavy-handed for what you need, there is runuser
(see man runuser
for full info; some versions may need -u
prior to the username):
/sbin/runuser username -s /bin/bash -c "command(s) to run as user username"
这篇关于如何在初始化脚本中以特定用户身份运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!