10
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. But glob.glob() is not working.

Using Python 2.6.

Remote server contains these files: /home/test1/check.file, /home/test1/validate.file, /home/test1/vali.file

Can anyone please help on this issue.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Vijay
  • 133
  • 1
  • 1
  • 10

2 Answers2

16

The glob will not magically start working with a remote server, just because you have instantiated SSHClient before.

You have to use Paramiko API to list the files, like 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.


Side note: Do not use AutoAddPolicy. You lose security by doing so. See Paramiko "Unknown Server".

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
4

Or use pysftp which is paramiko wrapper and write something like this:

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)
watbywbarif
  • 6,487
  • 8
  • 50
  • 64