如何在Python中删除远程SFTP服务器上目录中的所有文件?

发布于 2024-09-13 01:17:55 字数 576 浏览 7 评论 0原文

我想删除已使用 Paramiko 连接到的远程服务器上给定目录中的所有文件。不过,我无法明确给出文件名,因为这些文件名会根据我之前放在那里的文件版本而有所不同。

这就是我想要做的... #TODO 下面的行是我正在尝试的调用,其中 remoteArtifactPath 类似于 /opt/foo/*

ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, pkey=mykey)
sftp = ssh.open_sftp()

# TODO: Need to somehow delete all files in remoteArtifactPath remotely
sftp.remove(remoteArtifactPath+"*")

# Close to end
sftp.close()
ssh.close()

Any知道我怎样才能实现这个目标吗?

I'd like to delete all the files in a given directory on a remote server that I'm already connected to using Paramiko. I cannot explicitly give the file names, though, because these will vary depending on which version of file I had previously put there.

Here's what I'm trying to do... the line below the #TODO is the call I'm trying where remoteArtifactPath is something like /opt/foo/*

ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, pkey=mykey)
sftp = ssh.open_sftp()

# TODO: Need to somehow delete all files in remoteArtifactPath remotely
sftp.remove(remoteArtifactPath+"*")

# Close to end
sftp.close()
ssh.close()

Any idea how I can achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

悲凉≈ 2024-09-20 01:17:55

我找到了一个解决方案:迭代远程位置中的所有文件,然后对每个文件调用 remove

ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, pkey=mykey)
sftp = ssh.open_sftp()

# Updated code below:
filesInRemoteArtifacts = sftp.listdir(path=remoteArtifactPath)
for file in filesInRemoteArtifacts:
    sftp.remove(remoteArtifactPath+file)

# Close to end
sftp.close()
ssh.close()

I found a solution: Iterate over all the files in the remote location, then call remove on each of them:

ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, pkey=mykey)
sftp = ssh.open_sftp()

# Updated code below:
filesInRemoteArtifacts = sftp.listdir(path=remoteArtifactPath)
for file in filesInRemoteArtifacts:
    sftp.remove(remoteArtifactPath+file)

# Close to end
sftp.close()
ssh.close()
你在看孤独的风景 2024-09-20 01:17:55

您需要一个递归例程,因为您的远程目录可能有子目录。

def rmtree(sftp, remotepath, level=0):
    for f in sftp.listdir_attr(remotepath):
        rpath = posixpath.join(remotepath, f.filename)
        if stat.S_ISDIR(f.st_mode):
            rmtree(sftp, rpath, level=(level + 1))
        else:
            rpath = posixpath.join(remotepath, f.filename)
            print('removing %s%s' % ('    ' * level, rpath))
            sftp.remove(rpath)
    print('removing %s%s' % ('    ' * level, remotepath))
    sftp.rmdir(remotepath)

ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, pkey=mykey)
sftp = ssh.open_sftp()
rmtree(sftp, remoteArtifactPath)

# Close to end
stfp.close()
ssh.close()

You need a recursive routine since your remote directory may have subdirectories.

def rmtree(sftp, remotepath, level=0):
    for f in sftp.listdir_attr(remotepath):
        rpath = posixpath.join(remotepath, f.filename)
        if stat.S_ISDIR(f.st_mode):
            rmtree(sftp, rpath, level=(level + 1))
        else:
            rpath = posixpath.join(remotepath, f.filename)
            print('removing %s%s' % ('    ' * level, rpath))
            sftp.remove(rpath)
    print('removing %s%s' % ('    ' * level, remotepath))
    sftp.rmdir(remotepath)

ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, pkey=mykey)
sftp = ssh.open_sftp()
rmtree(sftp, remoteArtifactPath)

# Close to end
stfp.close()
ssh.close()
可遇━不可求 2024-09-20 01:17:55

Fabric 例程可以像这样简单:

with cd(remoteArtifactPath):
    run("rm *")

Fabric 非常适合在远程服务器上执行 shell 命令。 Fabric 实际上在底层使用了 Paramiko,所以如果需要的话可以同时使用两者。

A Fabric routine could be as simple as this:

with cd(remoteArtifactPath):
    run("rm *")

Fabric is great for executing shell commands on remote servers. Fabric actually uses Paramiko underneath, so you can use both if you need to.

演多会厌 2024-09-20 01:17:55

对于 @markolopa 的答案,您需要 2 次导入才能使其正常工作:

import posixpath
from stat import S_ISDIR

For @markolopa answer, you need 2 imports to get it working:

import posixpath
from stat import S_ISDIR
撩动你心 2024-09-20 01:17:55

我找到了一个解决方案,使用python3.7spur 0.3.20。很可能也适用于其他版本。

import spur

shell = spur.SshShell( hostname="ssh_host", username="ssh_usr", password="ssh_pwd")
ssh_session = shell._connect_ssh()

ssh_session.exec_command('rm -rf  /dir1/dir2/dir3')

ssh_session.close()

I found a solution, using python3.7 e spur 0.3.20. It is very possible that works with others versions as well.

import spur

shell = spur.SshShell( hostname="ssh_host", username="ssh_usr", password="ssh_pwd")
ssh_session = shell._connect_ssh()

ssh_session.exec_command('rm -rf  /dir1/dir2/dir3')

ssh_session.close()
〗斷ホ乔殘χμё〖 2024-09-20 01:17:55

所以我知道这是一篇较旧的帖子,但我仍然想给出一个简短的答案,我发现它比我发现的其他内容更有用。此外,这还使用 paramikos 内置函数,因此它应该适用于所有设备

import paramiko

class remote_operations:
    def __init__(self):
        pass
    
    def connect(self, hostname, username, password):
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname, username=username, password=password)
        return client

def delete_files():
    print("--Deleting files--")
    test = remote_operations()

    # these ips and passwords are just examples
    username = "aabfbkbakjdfb123"
    password = "I_am_not_good_at_making_passwords_123"
    host_ip = "111.111.11.11"

    client = test.connect(host_ip,username,password)
    sftp_client = client.open_sftp()

    folderPath = "/my_secret_files/"
    sftp_client.chdir(folderPath)

    for file in sftp_client.listdir():
        sftp_client.remove(file)

if __name__ == '__main__':
    delete_files()

So I know this is an older post but I would still like to give a short answer that I found to be more usefull than the rest I found. Also this uses paramikos in-built functions so it should work on all devices

import paramiko

class remote_operations:
    def __init__(self):
        pass
    
    def connect(self, hostname, username, password):
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname, username=username, password=password)
        return client

def delete_files():
    print("--Deleting files--")
    test = remote_operations()

    # these ips and passwords are just examples
    username = "aabfbkbakjdfb123"
    password = "I_am_not_good_at_making_passwords_123"
    host_ip = "111.111.11.11"

    client = test.connect(host_ip,username,password)
    sftp_client = client.open_sftp()

    folderPath = "/my_secret_files/"
    sftp_client.chdir(folderPath)

    for file in sftp_client.listdir():
        sftp_client.remove(file)

if __name__ == '__main__':
    delete_files()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文