如何解决如果任何目录没有读取权限,pysftp.Connection.walktree() 将失败
我正在使用 pysftp 连接,使用 walktree()
方法列出所有文件,如下所示
with pysftp.Connection(domain,username=USER,password=PWD,port=port,cnopts=cnopts) as sftp:
# call back method to list the files for the directory found in walktree
def dir_found_list_files(path):
if path:
files = sftp.listdir_attr(path)
for file in files:
if 'r' in file.longname[:4]:
filelist.append(path+'/'+file.filename)
# call back method when file found in walktree
def file_found(path):
pass
# call back method when unknown found in walktree
def unknown_file(path):
pass
# sftp walk tree to list files
sftp.walktree("/",file_found,dir_found_list_files,unknown_file,recurse=True)
这部分工作正常。但是当任何文件夹没有读取权限时,walktree
方法会引发权限异常。
如何忽略访问被拒绝文件夹并继续使用 walktree
获取可访问文件夹?
解决方法
你不能。 Connection.walktree
不允许此类自定义。
但是方法很简单,检查its source code。只需复制代码并根据需要进行自定义。像这样的东西(未经测试):
def robust_walktree(sftp,remotepath,fcallback,dcallback,ucallback,recurse=True)
try:
entries = sftp.listdir(remotepath)
except IOError as e:
if e.errno != errno.EACCES:
raise
else
entries = []
for entry in entries:
pathname = posixpath.join(remotepath,entry)
mode = sftp.stat(pathname).st_mode
if S_ISDIR(mode):
# It's a directory,call the dcallback function
dcallback(pathname)
if recurse:
# now,recurse into it
robust_walktree(sftp,pathname,ucallback)
elif S_ISREG(mode):
# It's a file,call the fcallback function
fcallback(pathname)
else:
# Unknown file type
ucallback(pathname)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。