Python USES sftp to upload and download of instance code
- 2020-05-26 09:37:51
- OfStack
In Python, you can use sftp in paramiko module to log in the remote host and realize upload and download functions.
1. Function realization
According to the input parameters to determine whether the file or directory, upload and download
The local parameter local needs to be sent to the remote parameter remote of type 1, with the file ending in filename and the directory ending in \
Local and remote directories for uploading and downloading need to exist
Exception handling
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):# Determines whether the local parameter is a directory or a file
for f in os.listdir(local):# Search 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):# Determines whether the local parameter is a directory or a file
for f in sftp.listdir(remote):# Traverse the remote directory
sftp.get(os.path.join(remote+f),os.path.join(local+f))# Download the files in the directory
else:
sftp.get(remote,local)# The download file
except Exception,e:
print('download exception:',e)
sf.close()
if __name__ == '__main__':
host = '192.168.1.2'# The host
port = 22 # port
username = 'root' # The user name
password = '123456' # password
local = 'F:\\sftptest\\'# Local file or directory, with remote 1 To, currently is windows Directory format, window You need to use a double slash in the middle of the directory
remote = '/opt/tianpy5/python/test/'# Remote file or directory, with 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 to achieve the file and directory upload and download, can upload and download files alone, can also be bulk upload and download files in the directory, basically achieve the desired function, but for the directory does not exist, as well as upload and download to a number of host on the case, still need to be improved.