zoukankan      html  css  js  c++  java
  • Python判断某个用户对某个文件的权限


    在Python我们要判断一个文件对当前用户有没有读、写、执行权限,我们通常可以使用os.access函数来实现,比如:

    # 判断读权限
    os.access(<my file>, os.R_OK)
    # 判断写权限
    os.access(<my file>, os.W_OK)
    # 判断执行权限
    os.access(<my file>, os.X_OK)
    # 判断读、写、执行权限
    os.access(<my file>, os.R_OK | os.W_OK | os.X_OK)
    1
    2
    3
    4
    5
    6
    7
    8
    但是如果要判断任意一个指定的用户对某个文件是否有读、写、执行权限,Python中是没有默认实现的,此时我们可以通过下面的代码断来判断

    import os
    import pwd
    import stat

    def is_readable(cls, path, user):
    user_info = pwd.getpwnam(user)
    uid = user_info.pw_uid
    gid = user_info.pw_gid
    s = os.stat(path)
    mode = s[stat.ST_MODE]
    return (
    ((s[stat.ST_UID] == uid) and (mode & stat.S_IRUSR > 0)) or
    ((s[stat.ST_GID] == gid) and (mode & stat.S_IRGRP > 0)) or
    (mode & stat.S_IROTH > 0)
    )

    def is_writable(cls, path, user):
    user_info = pwd.getpwnam(user)
    uid = user_info.pw_uid
    gid = user_info.pw_gid
    s = os.stat(path)
    mode = s[stat.ST_MODE]
    return (
    ((s[stat.ST_UID] == uid) and (mode & stat.S_IWUSR > 0)) or
    ((s[stat.ST_GID] == gid) and (mode & stat.S_IWGRP > 0)) or
    (mode & stat.S_IWOTH > 0)
    )

    def is_executable(cls, path, user):
    user_info = pwd.getpwnam(user)
    uid = user_info.pw_uid
    gid = user_info.pw_gid
    s = os.stat(path)
    mode = s[stat.ST_MODE]
    return (
    ((s[stat.ST_UID] == uid) and (mode & stat.S_IXUSR > 0)) or
    ((s[stat.ST_GID] == gid) and (mode & stat.S_IXGRP > 0)) or
    (mode & stat.S_IXOTH > 0)
    )

  • 相关阅读:
    Delphi 多线程知识
    程序员最后归宿是什么?30或35想转行?
    做技术的最终出路!
    路在何方?分析程序员人生之路
    一个垂直滚动的插件
    jQuery 动画中 缓动效果的应用
    [转]jQuery性能优化指南 I
    jQuery 标记当前函数 开始写一个简单的插件
    我发现我写的这俩函数太好用了~~
    jQuery浏览器版本判断
  • 原文地址:https://www.cnblogs.com/alexzu/p/9810774.html
Copyright © 2011-2022 走看看