首页 > 解决方案 > 查找 777 个文件和文件夹的脚本如何改进并使其在 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:
                               ^

标签: pythonrhel5

解决方案


使用0777而不是0o777.

八进制数的0o前缀在 Python 2.4 中不可用。传统的0前缀在 Python 3 之前有效。


推荐阅读