【问题标题】:python3 asyncio start_unix_server permissionpython3 asyncio start_unix_server 权限
【发布时间】:2018-09-09 21:01:22
【问题描述】:

我因特殊情况运行的软件将作为具有root权限的守护程序运行。该软件还将具有 API,以便普通用户每次无需“sudo”即可访问它(API 是只读的,只能从 localhost 访问)。

然后浪费一个带有随机数TCP端口的TCP端口,将来可能会被遗忘,我更喜欢使用UNIX套接字,因为它将在Linux上运行。

我正在使用 asyncio 模块来启动_unix_server 方法,但是我在 Unix 套接字文件权限方面遇到了问题,因为该软件以 root 权限启动,套接字文件具有“srwxr-xr-x root root”权限除非我使用“sudo”,否则我无法连接到这个文件。

我检查 start_unix_server 没有任何更改权限的选项,但具有接受套接字对象的 sock 参数。所以这就是我所做的并且成功了,但不确定是否打算这样做

import socket
import asyncio

async def handler(reader, writer):
    message = data.decode()
    addr = writer.get_extra_info('peername')
    print("Received %r from %r" % (message, addr))

    print("Send: %r" % message)
    writer.write(data)
    await writer.drain()

    print("Close the client socket")
    writer.close()

socket_file = "/tmp/example-server.socket"
if os.path.exists(socket_file):
    os.remove(socket_file)

srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
srv.bind(socket_file)

#Here we set the file permission after bind
os.chmod(socket_file, 0o666)

loop = asyncio.get_event_loop()

#Here we pass the socket object to asyncio
asyncio.ensure_future(asyncio.start_unix_server(handler, sock=s))

try:
    loop.run_forever()
except:
    pass
finally:
    loop.close()
    os.remove(socket_file)

【问题讨论】:

  • 您的umask 控制在您创建文件系统对象时关闭哪些权限。使用umask 000 运行以创建具有全局写入权限的套接字。
  • umask 是全局设置的吗?我应该把这个 umask 放在哪里?

标签: python python-3.x python-asyncio


【解决方案1】:

为避免创建自己的套接字,您可以将path 参数用于start_unix_server(记录在其较低级别的相对create_unix_server 下):

loop = asyncio.get_event_loop()

socket_file = "/tmp/example-server.socket"
if os.path.exists(socket_file):
    os.remove(socket_file)
loop.run_until_complete(
    asyncio.start_unix_server(handler, path=socket_file))
os.chmod(socket_file, 0o666)
loop.run_forever()
# ...

另一种选择是使用umask,但需要注意的是umask 会影响进程中的所有线程,因此如果您有可以创建文件的后台线程,它们可能会受到umask 更改的影响。

【讨论】:

  • 是的,我更喜欢 chmod,我之前没有成功,因为我只将 start_unix_server 包装在 ensure_future 中,但尚未启动。
猜你喜欢
  • 1970-01-01
  • 2014-01-22
  • 2022-12-11
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多