|
- import os, sys
- from stat import *
- def walktree(top, callback):
- for f in os.listdir(top):
- pathname = os.path.join(top. f)
- mode = os.lstat(pathname).st_mode
- if S_ISDIR(mode):
- walktree(pathname, callback)
- elif S_ISREG(mode):
- # is a file, call the callback function
- callback(pathname)
- else:
- # Unknown file type, print a message
- print('Skipping %s' % pathname)
- def visitfile(file):
- print('visiting', file)
- if __name__ == '__main__':
- walktree(sys.argv[1], visitfile)
复制代码
其二:
- import os
- import pwd
- import grp
- from stat import *
- # input: full path of an Entry, for user and group and access privilige to get
- # output: (user,group,listofprivilige) of that Entry
- def get_user_attr(path):
- stat = os.stat(path)
- mode = os.stat(path).st_mode
- uid = stat.st_uid
- gid = stat.st_gid
- is_readable_u = 'r' if (mode & S_IRUSR > 0) else '-'
- is_readable_g = 'r' if (mode & S_IRGRP > 0) else '-'
- is_readable_o = 'r' if (mode & S_IROTH > 0) else '-'
- is_writable_u = 'w' if (mode & S_IWUSR > 0) else '-'
- is_writable_g = 'w' if (mode & S_IWGRP > 0) else '-'
- is_writable_o = 'w' if (mode & S_IWOTH > 0) else '-'
- is_execable_u = 'x' if (mode & S_IXUSR > 0) else '-'
- is_execable_g = 'x' if (mode & S_IXGRP > 0) else '-'
- is_execable_o = 'x' if (mode & S_IXOTH > 0) else '-'
- user_info_ = pwd.getpwuid(uid)
- user = user_info_.pw_name
- group_info_ = grp.getgrgid(gid)
- group = group_info_.gr_name
- ls_access = []
- ls_access.append(is_readable_u)
- ls_access.append(is_writable_u)
- ls_access.append(is_execable_u)
- ls_access.append(is_readable_g)
- ls_access.append(is_writable_g)
- ls_access.append(is_execable_g)
- ls_access.append(is_readable_o)
- ls_access.append(is_writable_o)
- ls_access.append(is_execable_o)
- return (user, group, ls_access)
- # input: full path of an Entry, may represents a file, a dir ,a link, and a ?
- # output: line of the path Entry's attribute, with '\n', for write to output file.
- def get_file_attr(path):
- retStr = "null"
- mode = os.stat(path).st_mode
- if S_ISDIR(mode):
- retStr = '_dir ' + path + '\n'
- elif S_ISREG(mode):
- retStr = '_file ' + path + '\n'
- elif S_ISLNK(mode):
- retStr = '_lnk ' + path + '\n'
- else:
- retStr = '?___ ' + path + '\n'
- return retStr
复制代码
以上两法可以获取linux的文件权限、所有者、对象属性。
另附一文:Python速查手册,编程必用。
PythonQuickReference.pdf
(1008.27 KB, 下载次数: 1)
|
|