Python连接sftp教程

编程知识 行业动态 更新时间:2024-06-13 00:20:51

(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教程

本文发布于:2023-03-30 16:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/2afef1bc8d60a4c8e59c869d8b1020a5.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:教程   Python   sftp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!