是否可以使用 pysftp 模块删除包含某些内容的目录?

Is it possible to Remove Directory with some contents using pysftp module?

I am creating a backup script using pysftp module. I am able to upload and download files. When i am trying to Delete a directory with some contents i got an exception.

This is what i tried

con = pysftp.Connection('192.168.0.40',username='root',password='clado123')
con.chdir('/root/backup')
con.pwd
con.listdir()
['data', 'test']
data - directory is not empty.
test - directory is empty.
con.rmdir('test')
con.listdir()
['data']
con.rmdir('data')

操作系统错误:失败

Can any one suggest me a way to solve this problem?

rmdir(remotepath) 在文档中找到 http://pysftp.readthedocs.io/en/release_0.2.8/pysftp.html#pysftp.Connection.rmdir

我找到方法了。 pysftp 连接对象中有一个名为 'execute' 的方法。我们可以使用此方法在远程服务器上执行命令。

con.execute('rm -rf /root/backup/data')
con.listdir()
[]

remove 目录中的所有文件,然后使用 rmdir 删除空目录。适合我。

def clean_dir(sftp, dir, files):
    assert sftp.isdir(str(dir)), "Outbox does not exist!"
    assert files.is_dir(), "Source directory does not exist!"
    for capsule in list(files.iterdir()):
        target = dir / capsule.name
        assert sftp.exists(str(target)), "Target files does not exist!"
        sftp.remove(str(target))
        assert not sftp.exists(str(target)), "Removed file still exists!"