加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

将python-daemon作为非特权用户运行并保留组成员身份

发布时间:2020-12-16 23:52:32 所属栏目:Python 来源:网络整理
导读:我正在使用python-daemon软件包在python中编写一个守护进程.守护进程在启动时(init.d)启动,需要访问各种设备. 守护进程在运行ubuntu的嵌入式系统(beaglebone)上运行. 现在我的问题是我想将守护进程作为非特权用户运行(例如mydaemon)而不是root. 为了允许守护

我正在使用python-daemon软件包在python中编写一个守护进程.守护进程在启动时(init.d)启动,需要访问各种设备.
守护进程在运行ubuntu的嵌入式系统(beaglebone)上运行.

现在我的问题是我想将守护进程作为非特权用户运行(例如mydaemon)而不是root.

为了允许守护进程访问设备,我将该用户添加到所需的组中.
在python代码中我使用daemon.DaemonContext(uid = uidofmydamon).

由root daemonizes启动的进程很好并且由正确的用户拥有,但是在尝试访问设备时我得到权限被拒绝的错误.
我写了一个小的测试应用程序,似乎该进程没有继承用户的组成员身份.

#!/usr/bin/python
import logging,daemon,os

if __name__ == '__main__':
  lh=logging.StreamHandler()
  logger = logging.getLogger()
  logger.setLevel(logging.INFO)
  logger.addHandler(lh)

  uid=1001 ## UID of the daemon user
  with daemon.DaemonContext(uid=uid,files_preserve=[lh.stream],stderr=lh.stream):
    logger.warn("UID : %s" % str(os.getuid()))
    logger.warn("groups: %s" % str(os.getgroups()))

当我以uid = 1001的用户运行上面的代码时,我得到类似的东西

$./testdaemon.py
UID: 1001
groups: [29,107,1001]

而当我以root(或su)运行上面的代码时,我得到:

$sudo ./testdaemon.py
UID: 1001
groups: [0]

如何创建由root启动的守护程序进程,但具有不同的有效uid和完整的组成员身份?

最佳答案
我当前的解决方案涉及在启动实际守护进程之前删除root权限,使用start-stop-daemon的chuid参数:

 start-stop-daemon 
      --start 
      --chuid daemonuser 
      --name testdaemon 
      --pidfile /var/run/testdaemon/test.pid 
      --startas /tmp/testdaemon.py 
     -- 
      --pidfile /var/run/testdaemon/test.pid 
      --logfile=/var/log/testdaemon/testdaemon.log

这个解决方案的缺点是,我需要在启动实际守护进程(具有适当的文件权限)之前创建守护进程应该写入的所有目录(注意/ var / run / testdaemon和/ var / log / testdaemon) ).

我宁愿在python而不是bash中编写该逻辑.

对于现在这样有效,但我认为这应该以更优雅的方式解决.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读