0

我有一个以 root 身份运行的进程,需要分离线程才能以各种用户身份运行。这部分工作正常,但我需要一种在子进程和父进程之间进行通信的方法。

当我尝试将 multiprocessing.Manager() 与某些列表、字典、锁、队列等一起使用时,它总是在降低权限的进程上出现权限被拒绝错误。

有没有办法授予用户或 PID 访问权限来解决这个问题?

代表我遇到的基本代码(以root身份运行):

#!/usr/bin/env python
import multiprocessing, os
manager = multiprocessing.Manager()
problematic_list = manager.list()
os.setuid(43121) # or whatever your user is
problematic_list.append('anything')

结果:

root@liberator:/home/bscable# python asd.py
Traceback (most recent call last):
  File "asd.py", line 8, in <module>
    problematic_list.append('anything')
  File "<string>", line 2, in append
  File "/usr/lib/python2.7/multiprocessing/managers.py", line 755, in _callmethod
    self._connect()
  File "/usr/lib/python2.7/multiprocessing/managers.py", line 742, in _connect
    conn = self._Client(self._token.address, authkey=self._authkey)
  File "/usr/lib/python2.7/multiprocessing/connection.py", line 169, in Client
    c = SocketClient(address)
  File "/usr/lib/python2.7/multiprocessing/connection.py", line 293, in SocketClient
    s.connect(address)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 13] Permission denied
Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/util.py", line 261, in _run_finalizers
    finalizer()
  File "/usr/lib/python2.7/multiprocessing/util.py", line 200, in __call__
    res = self._callback(*self._args, **self._kwargs)
  File "/usr/lib/python2.7/multiprocessing/managers.py", line 625, in _finalize_manager
    process.terminate()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 137, in terminate
    self._popen.terminate()
  File "/usr/lib/python2.7/multiprocessing/forking.py", line 165, in terminate
    os.kill(self.pid, signal.SIGTERM)
OSError: [Errno 1] Operation not permitted

第一个例外似乎在这里很重要。

4

1 回答 1

0

Python(至少 2.6)使用 UNIX 套接字进行通信,如下所示:

/tmp/pymp-eGnU6a/listener-BTHJ0E

我们可以抓取该路径并更改其权限,如下所示:

#!/usr/bin/env python
import multiprocessing, os, grp, pwd
manager = multiprocessing.Manager()
problematic_list = manager.list()

fullname = manager._address
dirname = os.path.dirname(fullname)

gid = grp.getgrnam('some_group').gr_gid
uid = pwd.getpwnam('root').pw_uid # should always be 0, but you never know

os.chown(dirname, uid, gid)
os.chmod(dirname, 0770)

os.chown(fullname, uid, gid)
os.chmod(fullname, 0770)

os.setgid(gid)
os.setuid(43121) # or whatever your user is
problematic_list.append('anything')

于 2013-02-07T18:10:08.120 回答