用于查找 777 个文件和文件夹的脚本如何改进并使其与 python 2.4 (RHEL5) 兼容

script to find 777 files and folders how to improve and make it compatible in python 2.4 (RHEL5)

我有以下代码,我的第一个 python 脚本。它应该找到具有 777 权限的文件和文件夹,同时排除一些文件夹,如 /proc 等

有什么方法可以改进脚本吗?

#!/usr/bin/env python


import os, sys, socket,csv

from os.path import join

mode = int('777', 8) 
results = {} 
host = socket.gethostname() 
results[host] = {}

exclude = ['proc', 'run']

def get_username(uid):
    import pwd
    try:
        return pwd.getpwuid(uid).pw_name
    except KeyError:
        return uid


def find_files():
    for (dirpath, dirnames, filenames) in os.walk('/'):
        dirnames[:] = [d for d in dirnames if d not in exclude]
        listoffiles = [join(dirpath, file) for file in filenames]
        listoffiles += [join(dirpath,dir) for dir in dirnames]
        for path in listoffiles:
            try:
                statinfo = os.stat(path)
            except OSError:
               #print(path)
               pass
            if (statinfo.st_mode & 0o777) == mode:
                results[host][path] = {}
                results[host][path]['owner'] = get_username(statinfo.st_uid)
                results[host][path]['perm']  = oct(statinfo.st_mode & 0o777)
    return results

find_files()

resultstxt = csv.writer(open('results_%s.csv' % host, 'w')) for hostname,data in results.items():
    for path, attributes in data.items():
      resultstxt.writerow([hostname, path, attributes['perm'], str(attributes['owner'])])

我还需要修改它,因为我们有几个遗留的 rhel5 服务器,并且代码无法正常工作,出现一个奇怪的语法错误:

 File "./find777.py", line 34
    if (statinfo.st_mode & 0o777) == mode:
                               ^

使用 0777 而不是 0o777

八进制数字的 0o 前缀在 Python 2.4 中不可用。传统的 0 前缀一直有效到 Python 3.