sftp upload file

文章来源:http://www.cppcns.com/jiaoben/python/182058.html

#!/usr/bin/python
# coding=utf-8

import paramiko
import os
import ctypes

def sftp_upload(host,port,username,password,local,remote):
    sf = paramiko.Transport((host, port))
    sf.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(sf)
    try:
        if os.path.isdir(local):# 判断本地参数是目录还是文件
            for f in os.listdir(local):# 遍历本地目录
                sftp.put(os.path.join(local+f),os.path.join(remote+f))# 上传目录中的文件
        else:
            sftp.put(local, remote)# 上传文件
    except Exception, e:
        print('upload exception:', e)
    sf.close()


def sftp_download(host, port, username, password, local, remote):
    sf = paramiko.Transport((host, port))
    sf.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(sf)
    try:
        if os.path.isdir(local):#判断本地参数是目录还是文件
            for f in sftp.listdir(remote):#遍历远程目录
                 sftp.get(os.path.join(remote+f),os.path.join(local+f))#下载目录中文件
        else:
            sftp.get(remote, local)#下载文件
    except Exception,e:
        print('download exception:',e)
    sf.close()


if __name__ == '__main__':
    host = ''#主机
    port =  # 端口
    username = '' #用户名
    password = '' #密码
    local = '/app/scraper/req.txt'
    remote = ''
    sftp_upload(host,port,username,password,local,remote)#上传
    #sftp_download(host,port,username,password,local,remote)#下载
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容