SoFunction
Updated on 2024-11-12

Python use sftp to realize the upload and download function (example code)

In Python you can use sftp from the paramiko module to log in to a remote host for upload and download functions.

1.Function realization

Determine whether it is a file or a directory based on the input parameters for uploading and downloading

The local parameter local needs to be of the same type as the remote parameter remote, with files ending in filename and directories ending in \.

The local and remote directories for uploads and downloads need to exist

exception capture

2.Code realization

#!/usr/bin/python
# coding=utf-8
import paramiko
import os
def sftp_upload(host,port,username,password,local,remote):
  sf = ((host,port))
  (username = username,password = password)
  sftp = .from_transport(sf)
  try:
    if (local):# Determine if a local parameter is a directory or a file
      for f in (local):# Traversing the local directory
        ((local+f),(remote+f))# Uploading files in a directory
    else:
      (local,remote)#Upload a file
  except Exception,e:
    print('upload exception:',e)
  ()
def sftp_download(host,port,username,password,local,remote):
  sf = ((host,port))
  (username = username,password = password)
  sftp = .from_transport(sf)
  try:
    if (local):# Determine if a local parameter is a directory or a file
      for f in (remote):# Traversing remote directories
         ((remote+f),(local+f))#Downloading files from the directory
    else:
      (remote,local)#Download file
  except Exception,e:
    print('download exception:',e)
  ()
if __name__ == '__main__':
  host = '192.168.1.2'#Host
  port = 22 # port
  username = 'root' #Username
  password = '123456' #password
  local = 'F:\\sftptest\\'# Local file or directory, consistent with the remote, the current windows directory format, windows directory needs to use double slash in the middle
  remote = '/opt/tianpy5/python/test/'# Remote file or directory, consistent with local, current linux directory format
  sftp_upload(host,port,username,password,local,remote)#Upload
  #sftp_download(host,port,username,password,local,remote)#downloading

3. Summary

The above code implements the uploading and downloading of files and directories, you can upload and download files individually, or batch upload and download files in a directory, which basically realizes the desired functionality, but for the case where the directory doesn't exist, as well as for the case where the uploads and downloads are made to multiple hosts, it still needs to be perfected.