【问题标题】:List files on SFTP server matching wildcard in Python using Paramiko使用 Paramiko 在 Python 中列出与通配符匹配的 SFTP 服务器上的文件
【发布时间】:2018-08-29 03:08:13
【问题描述】:
import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('hostname', username='test1234', password='test')
path = ['/home/test/*.txt', '/home/test1/*.file', '/home/check/*.xml']
for i in path:

    for j in glob.glob(i):

        print j

client.close()

我正在尝试使用glob.glob 列出远程服务器上的通配符文件。但是glob.glob() 不起作用。

使用 Python 2.6。

远程服务器包含这些文件:/home/test1/check.file/home/test1/validate.file/home/test1/vali.file

谁能帮忙解决这个问题。

【问题讨论】:

    标签: python ssh sftp glob paramiko


    【解决方案1】:

    glob 不会神奇地开始使用远程服务器,只是因为您之前已经实例化了SSHClient

    您必须使用 Paramiko API 来列出文件,例如 SFTPClient.listdir:

    import fnmatch
    
    sftp = client.open_sftp()
    
    for filename in sftp.listdir('/home/test'):
        if fnmatch.fnmatch(filename, "*.txt"):
            print filename
    

    如果更适合您的需要,您也可以使用正则表达式进行匹配。见Using wildcard in remote path using Paramiko's SFTPClient


    旁注:不要使用AutoAddPolicy。你 这样做会失去安全感。见Paramiko "Unknown Server"

    【讨论】:

      【解决方案2】:

      或者使用 paramiko 包装器 pysftp 并编写如下内容:

      import pysftp
      
      
      def store_files_name(fname):
          pass
      
      
      def store_dir_name(dir_name):
          pass
      
      
      def store_other_file_type(other_file):
          pass
      
      with pysftp.Connection('server', username='user', password='pass') as sftp:
          sftp.walktree('.', store_files_name, store_dir_name, store_other_file_type)
      

      【讨论】:

        猜你喜欢
        • 2022-06-18
        • 1970-01-01
        • 2017-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-18
        • 2015-04-17
        • 2011-03-19
        相关资源
        最近更新 更多