以其他用户身份运行Linux服务的最佳实践 [英] Best practice to run Linux service as a different user
问题描述
服务默认在启动时在我的RHEL盒上以root
开头.如果我没记错的话,其他在/etc/init.d
中使用初始化脚本的Linux发行版也是如此.
Services default to starting as root
at boot time on my RHEL box. If I recall correctly, the same is true for other Linux distros which use the init scripts in /etc/init.d
.
您认为让进程以我选择的(静态)用户身份运行的最佳方法是什么?
What do you think is the best way to instead have the processes run as a (static) user of my choosing?
我到达的唯一方法是使用类似的东西:
The only method I'd arrived at was to use something like:
su my_user -c 'daemon my_cmd &>/dev/null &'
但这似乎有点不整洁...
But this seems a bit untidy...
是否存在一些魔术,它们提供了一种简单的机制来像其他非root用户一样自动启动服务?
Is there some bit of magic tucked away that provides an easy mechanism to automatically start services as other, non-root users?
编辑:我应该已经说过,我在此实例中启动的进程是Python脚本或Java程序.我宁愿不为它们编写本机包装,所以很遗憾,我无法调用 setuid() 按照黑色的建议.
I should have said that the processes I'm starting in this instance are either Python scripts or Java programs. I'd rather not write a native wrapper around them, so unfortunately I'm unable to call setuid() as Black suggests.
推荐答案
在Debian上,我们使用start-stop-daemon
实用程序,该实用程序处理pid文件,更改用户,将守护程序置于后台等等.
On Debian we use the start-stop-daemon
utility, which handles pid-files, changing the user, putting the daemon into background and much more.
我不熟悉RedHat,但是到处都提到了您已经在使用的daemon
实用程序(在/etc/init.d/functions
中定义),它等同于start-stop-daemon
,因此它也可以更改程序的uid,或者更改它的方式已经是正确的了.
I'm not familiar with RedHat, but the daemon
utility that you are already using (which is defined in /etc/init.d/functions
, btw.) is mentioned everywhere as the equivalent to start-stop-daemon
, so either it can also change the uid of your program, or the way you do it is already the correct one.
如果您环顾四周,可以使用几种现成的包装纸.有些甚至可能已经打包在RedHat中.例如,请查看 daemonize
.
If you look around the net, there are several ready-made wrappers that you can use. Some may even be already packaged in RedHat. Have a look at daemonize
, for example.
这篇关于以其他用户身份运行Linux服务的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!