在 Python 中删除根权限 [英] Dropping Root Permissions In Python

查看:29
本文介绍了在 Python 中删除根权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让 Python 程序开始侦听端口 80,但之后在没有 root 权限的情况下执行.有没有办法删除 root 或在没有它的情况下获取端口 80?

I'd like to have a Python program start listening on port 80, but after that execute without root permissions. Is there a way to drop root or to get port 80 without it?

推荐答案

如果没有 root 权限,您将无法在端口 80 上打开服务器,这是操作系统级别的限制.所以唯一的解决办法是打开端口后删除root权限.

You won't be able to open a server on port 80 without root privileges, this is a restriction on the OS level. So the only solution is to drop root privileges after you have opened the port.

这是在 Python 中删除 root 权限的可能解决方案:删除权限在 Python 中.一般来说,这是一个很好的解决方案,但您还必须将 os.setgroups([]) 添加到函数中,以确保不保留 root 用户的组成员身份.

Here is a possible solution to drop root privileges in Python: Dropping privileges in Python. This is a good solution in general, but you'll also have to add os.setgroups([]) to the function to ensure that the group membership of the root user is not retained.

我复制并清理了一点代码,并删除了日志记录和异常处理程序,因此由您来正确处理OSError(当进程不允许时会抛出它)切换其有效的 UID 或 GID):

I copied and cleaned up the code a little bit, and removed logging and the exception handlers so it is left up to you to handle OSError properly (it will be thrown when the process is not allowed to switch its effective UID or GID):

import os, pwd, grp

def drop_privileges(uid_name='nobody', gid_name='nogroup'):
    if os.getuid() != 0:
        # We're not root so, like, whatever dude
        return

    # Get the uid/gid from the name
    running_uid = pwd.getpwnam(uid_name).pw_uid
    running_gid = grp.getgrnam(gid_name).gr_gid

    # Remove group privileges
    os.setgroups([])

    # Try setting the new uid/gid
    os.setgid(running_gid)
    os.setuid(running_uid)

    # Ensure a very conservative umask
    old_umask = os.umask(077)

这篇关于在 Python 中删除根权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆