文件权限获取

本文介绍了如何使用Python编程,通过import模块如sys,os,subprocess来执行Linuxfind命令,查找指定文件模式并解析文件权限。代码示例展示了如何获取文件的权限信息,并处理可能出现的异常。
摘要由CSDN通过智能技术生成

代码命令:

import stat 

import sys 

import os 

import subprocess 

 

try: 

    # 程序开始 

    pattern = input("Enter the file pattern to search for:\n")  # Python 3 使用 input 而不是 raw_input 

    # 获取文档的路径并且存入 pattern 中 

    commandString = "find " + pattern 

    # 调用 Linux 中的 find 命令 

    # 在 Python 3 中,应使用 subprocess 替代 commands 

    commandOutput = subprocess.check_output(commandString, shell=True).decode('utf-8') 

    # 将输出结果分块 

    findResults = commandOutput.split("\n") 

    # 输出文件列表 

    print("Files:") 

    print(commandOutput) 

    print("=======================")  # 输出一个空行 

     

    for file in findResults: 

        if file:  # 跳过空行 

            mode = stat.S_IMODE(os.lstat(file)[stat.ST_MODE]) 

            # 输出文件权限 

            print("\nPermissions for file", file, ":") 

            for level in "USR", "GRP", "OTH": 

                for perm in "R", "W", "X": 

                    if mode & getattr(stat, "S_I" + perm + level): 

                        print(level, "has", perm, "permission") 

                    else: 

                        print(level, "does NOT have", perm, "permission") 

except Exception as e:  # 捕获所有异常并打印异常信息 

    print("There was a problem:", e)

效果图:

文件演示

目录演示

代码详释:

1.import stat : 表示导入stat模块,用于获取文件的权限信息。

2.import sys : 表示导入sys模块,可能用于与系统相关的操作。

3.import os : 表示导入os模块,用于操作文件和目录。

4.import subprocess : 表示导入subprocess模块,用于执行系统命令。

5.pattern = input("Enter the file pattern to search for:\n") : 表示使用input函数获取用户输入的文件模式。

6.commandString = "find " + pattern : 表示构建find命令的字符串,将用户输入的模式添加到命令中。

7.commandOutput = subprocess.check_output(commandString, shell=True).decode('utf-8') : 表示使用subprocess.check_output执行find命令,并将输出结果转换为utf-8编码。

8. findResults = commandOutput.split("\n") : 表示将输出结果按行分割,存储在findResults列表中。

9. 遍历findResults列表,对于每个文件:获取文件的权限模式。

打印文件的权限信息,包括每个用户组(USR 、GRP 、OTH)对每个权限(R 、W 、X)的拥有情况。

10.except Exception as e : 表示捕获可能发生的异常,并打印异常信息。

常见问题:

There was a problem: Command 'find/home/yizhi/Desktop/code/Permission acquisition.py' returned non-zero exit status 127.

问题原因:

Find的用法的使用有误。

解决方法:

在{commandString = "find" + pattern}语句中find后面加个空格。 

注意事项:

commandString = "find " + pattern 

该语句中的find后面要加一个空格,其是find的特定用法,用于查看指定文件。

  • 23
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值