我有一个以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
第一个例外似乎是重要的例外。
答案 0 :(得分: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')