python - 查找 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:
^
解决方案
使用0777
而不是0o777
.
八进制数的0o
前缀在 Python 2.4 中不可用。传统的0
前缀在 Python 3 之前有效。
推荐阅读
- r - ggplot:如何为多个绘图添加标签(使用 geom_text,没有图例)?
- python - Selenium webdriverwait (.text_to_be_present _in_element 没有) 似乎工作,我找不到任何解决方案
- javascript - 更改代码编辑器插件的 JavaScript
- mongodb - Express-session + Passport + MongoDB - req.isAuthenticated() 在登录后总是返回 false
- javascript - chrome.contextMenus.create 的 onclick 回调中的“info”的类型是什么?
- java - 无法使用 json 对象读取 jsonarray,NPE
- hibernate - 在 ManyToMany 中重命名外键约束
- c - 如何正确处理字符串数组的动态分配?
- vb.net - 如何在 VB.NET 中通过 datgarid 设置单元格颜色并修改其文本
- pyqt5 - 如何编写 Python 代码 pyqt5 在主窗口上附加 2 个小部件