当前位置: 代码迷 >> 综合 >> Python连接sftp教程
  详细解决方案

Python连接sftp教程

热度:36   发布时间:2023-11-21 06:00:16

(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-8import 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']= remoteconfig['local']=localconfig['host'] = hostconfig['port'] = portconfig['username'] = usernameconfig['password'] = passwordreturn configdef 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 sftpdef exists(sftp,path):try:sftp.stat(path)return Trueexcept IOError,e:if 'No such file' in str(e):return Falseelse: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+"/"+fremote_path = path1local_path = localprint ("正在下载"+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)