使用 Paramiko 的 SFTPClient 在远程路径中使用通配符 [英] Using wildcard in remote path using Paramiko's SFTPClient

查看:91
本文介绍了使用 Paramiko 的 SFTPClient 在远程路径中使用通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文件从远程服务器复制到本地.

I want to copy the file from remote server to local.

import paramiko
paramiko.util.log_to_file('/tmp/paramiko.log')

# open transport
username = "user"
host="example.com"
port = 22
transport = paramiko.Transport((host, port))
transport.start_client()
private_key_file = "/home/user/.ssh/id_rsa"
agent = paramiko.Agent()
key = paramiko.RSAKey.from_private_key_file(private_key_file)
transport.auth_publickey(username, key)

# get sftp client
sftp = paramiko.SFTPClient.from_transport(transport)
source = "/home/user/user_1.csv"
target = "/home/local/local_sftp.txt"
sftp.get(x[0], x[1])

以上代码运行良好,但我想使用 source = "/home/user/user_*.csv" 但未评估此通配符.有人可以帮我解决这个问题.

Above code is working fine but I want to use source = "/home/user/user_*.csv" but this wildcard is not evaluated. Can someone please help me fix this problem.

我找到了 一种 SCPClient 的解决方案 但无法解决 SFTPClient 的问题.

推荐答案

Paramiko SFTPClient 不支持通配符.

Paramiko SFTPClient does not support wildcards.

因此您必须自己列出远程文件夹中的文件,并将它们过滤为您要下载的文件:

So you have to list files in a remote folder yourself and filter them to those you want to download:

import re

remote_path = "/home/user"
local_path = "/home/local"

files = sftp.listdir(remote_path)

for filename in files:
    if re.match("^user_.*\\.csv$", filename):
        print(filename)
        sftp.get(remote_path + "/" + filename, local_path + "/" + filename)

或者使用 fnmatch 模块.请参阅使用 Paramiko 在 Python 中匹配通配符的 SFTP 服务器上的文件列表.

Or use the fnmatch module. See List files on SFTP server matching wildcard in Python using Paramiko.

这篇关于使用 Paramiko 的 SFTPClient 在远程路径中使用通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆