Home  >  Article  >  Backend Development  >  Python determines a user's permissions on a file

Python determines a user's permissions on a file

WBOY
WBOYOriginal
2016-12-05 13:27:131195browse

In Python, we need to determine whether a file has read, write, and execute permissions for the current user. We can usually use the os.access function to achieve this, such as:

# 判断读权限
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)

But if you want to determine whether any specified user has read, write, and execute permissions on a certain file, there is no default implementation in Python. At this time, we can judge through the following code snippet

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)

    )

The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope that everyone will support Script Home.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn