使用 Python 在 Linux 中检查文件权限 [英] Checking File Permissions in Linux with Python

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

问题描述

我正在编写一个脚本来检查用户目录中文件的权限,如果它们不可接受,我会警告他们,但我不仅要检查登录用户的权限,还要检查组和其他人的权限.我怎样才能做到这一点?在我看来,Python 中的 os.access() 只能检查运行脚本的用户的权限.

I'm writing a script to check permissions of files in user's directories and if they're not acceptable I'll be warning them, but I want to check permissions of not just the logged in user, but also group and others. How can i do this? It seems to me that os.access() in Python can only check the permissions for the user running the script.

推荐答案

你说得对 os.access,就像底层的访问a> 系统调用,检查特定用户(真实而不是有效 ID,以帮助解决 suid 情况).

You're right that os.access, like the underlying access syscall, checks for a specific user (real rather than effective IDs, to help out with suid situations).

os.stat 是正确的获取有关文件的更多一般信息的方法,包括每个用户、组和其他人的权限.os.stat 返回的对象的 st_mode 属性具有文件的权限位.

os.stat is the right way to get more general info about a file, including permissions per user, group, and others. The st_mode attribute of the object that os.stat returns has the permission bits for the file.

为了帮助解释这些位,您可能需要使用 stat 模块.具体来说,您需要在此处定义位掩码,并且您将使用 & 运算符(位与)来使用它们来屏蔽 st_mode 属性中的相关位——例如,如果您只需要对某个文件是否为组可读的 True/False 检查,一种方法是:

To help interpret those bits, you may want to use the stat module. Specifically, you'll want the bitmasks defined here, and you'll use the & operator (bit-and) to use them to mask out the relevant bits in that st_mode attribute -- for example, if you just need a True/False check on whether a certain file is group-readable, one approach is:

import os
import stat

def isgroupreadable(filepath):
  st = os.stat(filepath)
  return bool(st.st_mode & stat.S_IRGRP)

注意:os.stat 调用可能会有些开销,因此请确保通过一次调用提取您关心的所有信息,而不是对每个感兴趣的位重复调用;-).

Take care: the os.stat call can be somewhat costly, so make sure to extract all info you care about with a single call, rather than keep repeating calls for each bit of interest;-).

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

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