我有以下代码,这是我的第一个python脚本。它应该查找具有777权限的文件和文件夹,同时排除某些文件夹,例如/ proc等
有什么办法可以改善脚本?
DetailsActivity
我还需要对其进行修改,因为我们有几个旧的rhel5服务器,并且代码无法使用奇怪的语法错误进行工作:
#!/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'])])
答案 0 :(得分:0)
使用0777
代替0o777
。
Python 2.4中不提供八进制数字的0o
前缀。传统的0
前缀在Python 3之前有效。