In Python, you can use the SFTP in the Paramiko module to login to the remote host for upload and download functions.
1. Function implementation According to the input parameters to determine whether the file or directory, upload and download local parameters locally need to be the same as remote parameter remoted type, file end with filename, directory with \ End upload and download local and remote directories need to have exception capture
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): #判断本地参数是目录还是文件 to F in Os.listdir (Loca L): #遍历本地目录 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): #判断本地参数是目录还是文件 to F in Sftp.listdir (re
Mote): #遍历远程目录 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 = #端口 username = ' root ' #用户名 password = ' 123456 ' #密码 loca L = ' f:\\sftptest\\ ' #本地文件或目录, consistent with remote, currently Windows directory format, window directory needs to use double slash remote = '/opt/tianpy5/python/test/' #远程文件或目录, In line with the local, currently the Linux directory format sftp_upload (host,port,username,password,local,remote) #上传 #sftp_download (Host,port,username, Password,local,remote) #下载
3. Summary
The above code implements the upload and download of files and directories, can upload and download files alone, can also 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 multiple hosts on the situation, still need to improve.