(1)创建配置文件 config.ini

[sftp]
#远程路径 例如 in,子文件夹名称要有key
REMOTE =in
#本地路径
LOCAL = out
#主机
HOST= 127.0.0.1
#端口
PORT=22
#用户名
USERNAME =root
#密码
PASSWORD =root

(2)创建py

# coding: utf-8

import paramiko
import ConfigParser
import sys,os
import codecs
import stat
config = {}

def importConfig():
    conf = ConfigParser.ConfigParser()
    conf.readfp(codecs.open('config.ini',"r","utf-8-sig"))
    remote = conf.get('sftp','REMOTE').encode('utf-8')
    local =  conf.get('sftp','LOCAL').encode('utf-8')
    host =  conf.get('sftp','HOST').encode('utf-8')
    port = conf.get('sftp','PORT').encode('utf-8')
    username = conf.get('sftp','USERNAME').encode('utf-8')
    password = conf.get('sftp','PASSWORD').encode('utf-8')
    config['remote']= remote
    config['local']=local
    config['host'] = host
    config['port'] = port
    config['username'] = username
    config['password'] = password
    return config

def connect_sftp(config):
    trans = paramiko.Transport((config['host'], int(config['port']))) 
    trans.connect(username=config['username'],password=config['password'])
    sftp = paramiko.SFTPClient.from_transport(trans)  
    return sftp

def exists(sftp,path):
	try:
		sftp.stat(path)
		return True
	except IOError,e:
		if 'No such file' in str(e):
			return False
		else:
			return True
def download_sftp(sftp,local,remote):
    for f in sftp.listdir(remote):
        if str(f).find("key")!= -1:
            if not os.path.exists(local):
				os.makedirs(local)
            path1 = remote+"/"+f
            remote_path = path1
            local_path = local
            print ("正在下载"+path1 ).decode('utf-8').encode('gbk')
            sftp.get(remote_path,local_path)
            print (path1 +"下载完成").decode('utf-8').encode('gbk')
            print "\n"

if __name__ == '__main__':
    sftp = connect_sftp(importConfig())
    print "\n"
    print "开始准备下载...".decode('utf-8').encode('gbk')
    print "\n"
    remo = config['remote']
    remotes = remo.split("|")
    for remote in remotes:
		download_sftp(sftp,config['local'],remote)


更多推荐

Python连接sftp教程