【问题标题】:Deleting files only with specified permissions in Linux using Python使用 Python 在 Linux 中仅删除具有指定权限的文件
【发布时间】:2021-03-01 15:00:49
【问题描述】:

我只想使用 Python 脚本在 Linux (Ubuntu) 中删除具有 777 权限的文件,但它会删除我创建的所有文件。

立即输出:脚本正在发送有关文件创建的通知,并在脚本运行时删除所有文件。

预期输出:当用户创建具有 777 权限的文件然后将其删除时,脚本会发送通知。不接触其他文件,例如只读取权限文件。

import os
from time import sleep
import subprocess

# folder = os.getcwd()
# folder = r'C:\Users\TheAlestGuy\Desktop\TestPu\Testing'
folder = "/home/alen/Desktop/TestFolder/Teting"

try:
    while True:
        files = os.listdir(folder)

        for file in files:
            if os.stat(folder).st_mode & 0o777:
                os.remove(f'{folder}/{file}')
                subprocess.Popen(['notify-send', "User is trying to create file with 777 permissios"])
                sleep(5)
except KeyboardInterrupt:
    print("Script terminated, no more files will be deleted :)")
    pass

【问题讨论】:

    标签: python python-3.x linux


    【解决方案1】:

    似乎os.stat(file).st_mode 返回的信息不仅仅是访问级别。

    $ touch testme
    $ ls -lah testme
    -rw-rw-r-- 1 ex4 ex4 0 Mar  2 00:10 testme
    
    $ python3
    >>> os.stat("testme").st_mode == 0o664
    False
    >>> oct(os.stat("testme").st_mode)
    '0o100664'
    

    正如 N. Kerm 所说,您的位运算符在这里不正确

    st_mode 有不同部分的掩码,你可以这样使用它们:

    >> from stat import S_IRWXU, S_IRWXG, S_IRWXO
    >> u = os.stat("testme").st_mode & S_IRWXU # User permission
    >> g = os.stat("testme").st_mode & S_IRWXG # Group permission
    >> o = os.stat("testme").st_mode & S_IRWXO # Others permission
    >>> oct(u)
    '0o600'
    >>> oct(g)
    '0o60'
    >>> oct(o)
    '0o4'
    >>> oct(u+g+o)
    '0o664'
    
    

    进一步阅读:https://docs.python.org/3/library/stat.html

    【讨论】:

    • 好点,我相应地更新了我的答案。
    【解决方案2】:

    在你这里:

    if os.stat(folder).st_mode & 0o777:
    

    您正在使用按位与运算符。如果为任何用户设置了任何权限,则结果为非零。您可能想改用==

    另外,我不确定这是否是有意的,但os.stat(folder).st_mode 只是检查文件夹的权限。我想你想要更像这样的东西:

    path = os.path.join(folder, file)
    if os.stat(path).st_mode == 0o777:
        os.remove(path)
    

    编辑:正如 ex4 所指出的,st_mode 也可能包含其他信息。所以最好只对最后 3 位进行切片:

    path = os.path.join(folder, file)
    if oct(os.stat(path).st_mode)[-3:] == '777':
        os.remove(path)
    

    【讨论】:

    • 有一种更优雅的方式来读取权限,而不仅仅是切片。有可用于不同权限的位掩码。
    猜你喜欢
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 2014-08-07
    • 2010-12-24
    • 1970-01-01
    • 2011-08-03
    • 2018-05-28
    • 2012-10-27
    相关资源
    最近更新 更多