【问题标题】:Using wildcard in remote path using Paramiko's SFTPClient使用 Paramiko 的 SFTPClient 在远程路径中使用通配符
【发布时间】:2019-01-22 18:32:31
【问题描述】:

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

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",但未评估此通配符。 谁能帮我解决这个问题。

我找到了one solution for SCPClient,但无法解决SFTPClient 的问题。

【问题讨论】:

    标签: python sftp paramiko


    【解决方案1】:

    Paramiko SFTPClient 不支持通配符。

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

    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 模块。见List files on SFTP server matching wildcard in Python using Paramiko

    【讨论】:

      【解决方案2】:

      检索文件列表后,fnmatch 通常比正则表达式更适合这项工作:

      import fnmatch
      for name in sftp.listdir(remote_path):
          if fnmatch.fnmatch(name, "user_*.csv"):
              print(name)
      

      【讨论】:

      • 我尝试了您的解决方案,但仍然失败,文件名类似于 Opt_adv048-2020.12.23.14.05.51.csv.pgp 。我尝试了Opt_adv048-*.csv.pgp的模式
      【解决方案3】:

      如果您将 SFTPServer 部署在类似 *nix 的系统上,这只是一个简单的解决方案,请使用如下execute 方法:

      conn.execute("ls dir/*.csv")
      

      【讨论】:

      • 这假设您对服务器具有 shell 访问权限,并且它是 Linux 服务器。虽然这个问题是关于 SFTP 的。
      • @MartinPrikryl SFTP 是 SSH File Transfer Protocol 的缩写,所以基本上如果你有 SFTP 你有一个 Linux 服务器,也许你的意思是 FTPS!
      • 绝对不是。所有系统都有 SFTP 服务器,不仅适用于 Linux。即使在 Linux 上,您也可以在没有 shell 访问的情况下进行 SFTP 访问。
      • 是的,但在实际问题中,很明显他正在使用 linux,而 linux 并不重要!使用 shell 和 bash 很重要
      • 但我们不知道 OP 是否有 shell 访问权限。我并不是说你的答案没有用。但问题是关于sftp。您的答案不使用 SFTP,而是使用 shell。所以应该这么说,所以很明显不是每个人都能使用你的解决方案
      猜你喜欢
      • 2010-10-25
      • 2012-04-07
      • 1970-01-01
      • 2014-03-02
      • 2014-06-25
      • 2012-11-21
      • 2012-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多