要通过ssh从远程文件夹下载所有文件,可以使用ftp.listdir()列出每个文件的ftp.get()文件:
#!/usr/bin/env python
import os
import sys
from contextlib import closing
from paramiko import SSHConfig, SSHClient
# specify hostname to connect to and the remote/local paths
hostname, remote_dirname, destdir = sys.argv[1:]
# load parameters to setup ssh connection
config = SSHConfig()
with open(os.path.expanduser('~/.ssh/config')) as config_file:
config.parse(config_file)
d = config.lookup(hostname)
# connect
with closing(SSHClient()) as ssh:
ssh.load_system_host_keys() #NOTE: no AutoAddPolicy()
ssh.connect(d['hostname'], username=d.get('user'))
with closing(ssh.open_sftp()) as sftp:
# cd into remote directory
sftp.chdir(remote_dirname)
# cd to local destination directory
os.chdir(destdir)
# download all files in it to destdir directory
for filename in sftp.listdir():
sftp.get(filename, filename)