Python uses sftp to upload and download

  • 2021-11-01 03:44:53
  • OfStack

In Python, you can use sftp in paramiko module to log in to the remote host to realize uploading and downloading functions.

1. Function realization

1. Judge whether it is a file or a directory according to the input parameters, and upload and download
2. The local parameter local needs to be the same as the remote parameter remote type 1. The file ends with the file name and the directory ends with\
3. Local and remote directories for upload and download need to exist
4. Exception catching

2. Code implementation


#!/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):# Determine whether the local parameter is a directory or a file 
            for f in os.listdir(local):# Traverse the local directory 
                sftp.put(os.path.join(local+f),os.path.join(remote+f))# Upload files in the directory 
        else:
            sftp.put(local,remote)# Upload a file 
    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):# Determine whether the local parameter is a directory or a file 
            for f in sftp.listdir(remote):# Traversing remote directories 
                 sftp.get(os.path.join(remote+f),os.path.join(local+f))# Download files in the directory 
        else:
            sftp.get(remote,local)# Download a file 
    except Exception,e:
        print('download exception:',e)
    sf.close()

if __name__ == '__main__':
    host = '192.168.1.2'# Host 
    port = 22 # Port 
    username = 'root' # User name 
    password = '123456' # Password 
    local = 'F:\\sftptest\\'# Local file or directory, and remote 1 To, currently is windows Directory format, window Double slashes are required in the middle of the directory 
    remote = '/opt/tianpy5/python/test/'# Remote files or directories, and local 1 To, currently is linux Directory format 
    sftp_upload(host,port,username,password,local,remote)# Upload 
    #sftp_download(host,port,username,password,local,remote)# Download 

3. Summary

The above code realizes the uploading and downloading of files and directories, which can be uploaded and downloaded separately, and can also upload and download files in directories in batches, basically realizing the required functions, but for the situation that directories do not exist, and uploading and downloading to multiple hosts, it needs to be improved.


Related articles: