Home > Backend Development > Python Tutorial > Using Python to implement sftp upload and download function code sharing

Using Python to implement sftp upload and download function code sharing

高洛峰
Release: 2017-03-16 09:19:32
Original
1643 people have browsed it

Python中可以使用paramiko模块中的sftp登陆远程主机,实现上传和下载功能。接下来通过本文给大家介绍Python使用sftp实现上传和下载功能,需要的朋友参考下

1.功能实现

根据输入参数判断是文件还是目录,进行上传和下载

本地参数local需要与远程参数remote类型一致,文件以文件名结尾,目录以\结尾

上传和下载的本地和远程目录需要存在

异常捕获

2.代码实现


#!/usr/bin/python
# coding=utf-8
import paramiko
import os
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 = '192.168.1.2'#主机
  port = 22 #端口
  username = 'root' #用户名
  password = '123456' #密码
  local = 'F:\\sftptest\\'#本地文件或目录,与远程一致,当前为windows目录格式,window目录中间需要使用双斜线
  remote = '/opt/tianpy5/python/test/'#远程文件或目录,与本地一致,当前为linux目录格式
  sftp_upload(host,port,username,password,local,remote)#上传
  #sftp_download(host,port,username,password,local,remote)#下载
Copy after login

3.总结

以上代码实现了文件和目录的上传和下载,可以单独上传和下载文件,也可以批量上传和下载目录中的文件,基本实现了所要的功能,但是针对目录不存在的情况,以及上传和下载到多台主机上的情况,还有待完善。

The above is the detailed content of Using Python to implement sftp upload and download function code sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template