使用Python Paramiko/pysftp检查SFTP服务器上的文件是否为符号链接,并删除该符号链接



我在基于linux的服务器上有一个目录,其中包含子目录,其中一个子目录包含指向服务器上其他目录的符号链接。

我想使用python脚本,从网络上的Windows计算机远程删除目录及其所有内容。在执行此操作时,我希望删除符号链接,但而不是删除符号链接指向的目录或其任何内容。

这是我的代码(部分取自另一个stackoverflow答案https://stackoverflow.com/a/22074280/3794244):

def rm_tree(remote_path, connection):
"""Recursively remove a remote directory and all its contents
The remote server must have a POSIX-standard file system
Parameters
----------
remote_path : str
Directory on the remote server to remove
connection : pysftp.Connection
Connection to the remote server on which to find the directory
Returns
-------
None
"""
# https://stackoverflow.com/questions/3406734
try:
files = connection.listdir(remote_path)
except FileNotFoundError:
files = []
for filename in files:
rpath = posixpath.join(remote_path, filename)
if connection.isdir(rpath):
rm_tree(rpath, connection)
else:
connection.unlink(rpath)
with contextlib.suppress(FileNotFoundError):
connection.rmdir(remote_path)

当我运行这个时,我从paramiko得到一个信息很少的错误,这是一个IOError,消息是";O错误:失败";。当它试图删除包含符号链接的目录时,它在函数connection.rmdir(remote_path)的最后一行给出了错误。函数已经删除了目录的其余内容,但符号链接仍然存在。

我想我需要添加到我的功能中的内容如下:

if is_symlink(rpath):
remove_symlink(rpath)

在检查它是否是目录之前,但我在pysftp或paramiko文档中找不到任何与is_symlinkremove_symlink函数等效的内容。

如何确定远程文件是否为符号链接,以及如何远程删除符号链接?

不要使用Connection.listdirConnection.isdir。这是低效的。使用Connection.listdir_attr检索包含所有属性的列表注意,Connection.listdir在内部调用Connection.listdir_attr并丢弃属性

具有这些属性后,可以使用stat.S_ISLNK来确定条目是否为符号链接。

import stat
for f in connection.listdir_attr(remote_path):
rpath = posixpath.join(remote_path, f.filename)
if stat.S_ISLNK(f.st_mode)):
connection.unlink(rpath)
elif stat.S_ISDIR(f.st_mode):
rm_tree(rpath, connection)
else:
connection.unlink(rpath)

最新更新