In this article, the example for you to share the python to achieve automatic download sftp file specific code for your reference, the specific content is as follows
Realize the function:Automatically connects to sftp using python and downloads all directories and files in the specified directory in sftp.
- System environment: centos7
- python version: python3
- Use the module package: paramiko, which can be installed with pip install paramiko if it is not already installed.
Examples of requirements:The file in sftp is as follows
Download all files in the sftp root directory to the local /data/test directory
Implementation Code:
#!/usr/bin/python # coding=utf-8 import paramiko import os def sftp_download(sftp,localDir,remoteDir): if (".") == -1:# Determine whether the remote directory parameter is a directory, provided that the remote file names all contain extensions, otherwise this method is not available for file in (remoteDir): remoteDirTmp=(remoteDir,file) localDirTmp=(localDir,file) sftp_download(sftp,localDirTmp,remoteDirTmp) else: localPath=("/")[0] if not (localPath): (localPath) print("download file:",remoteDir) try: (remoteDir,localDir) except Exception as e: print('download exception:',e) if __name__ == '__main__': host = '192.168.149.128'#sftp host port = 22 # port username = 'sftp' #sftp username password = '123456' localDir = '/data/test'# Local files or directories remoteDir = '/'# Remote files or directories sf = ((host,port)) (username = username,password = password) sftp = .from_transport(sf) sftp_download(sftp,localDir,remoteDir) ()
This is the whole content of this article.