简体   繁体   English

使用Paramiko在Python中列出与通配符匹配的SFTP服务器上的文件

[英]List files on SFTP server matching wildcard in Python using Paramiko

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()

I am trying to list the wildcard files on remote server by using glob.glob .我正在尝试使用glob.glob列出远程服务器上的通配符文件。 But glob.glob() is not working.但是glob.glob()不起作用。

Using Python 2.6.使用 Python 2.6。

Remote server contains these files: /home/test1/check.file , /home/test1/validate.file , /home/test1/vali.file远程服务器包含这些文件: /home/test1/check.file/home/test1/validate.file/home/test1/vali.file

Can anyone please help on this issue.任何人都可以请帮助解决这个问题。

The glob will not magically start working with a remote server, just because you have instantiated SSHClient before. glob不会神奇地开始与远程服务器一起工作,仅仅因为您之前已经实例化了SSHClient

You have to use Paramiko API to list the files, like SFTPClient.listdir :您必须使用 Paramiko API 来列出文件,例如SFTPClient.listdir

import fnmatch
sftp = client.open_sftp()

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

You can also use a regular expression for the matching, if it suits your needs better.如果更适合您的需要,您还可以使用正则表达式进行匹配。 See Using wildcard in remote path using Paramiko's SFTPClient .请参阅使用 Paramiko 的 SFTPClient 在远程路径中使用通配符


Side note: Do not use AutoAddPolicy .旁注:不要使用AutoAddPolicy You lose security by doing so.这样做你会失去安全感。 See Paramiko "Unknown Server" .请参阅Paramiko“未知服务器”

Or use pysftp which is paramiko wrapper and write something like this:或者使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM