How to check if Paramiko successfully uploaded a file to an SFTP server?

对着背影说爱祢 提交于 2019-11-27 07:26:47

问题


I use Paramiko to put a file to an SFTP server:

import paramiko

transport = paramiko.Transport((host, port))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(local_path, remote_path)

Now, I would like to check if it worked. The idea is that I compare the checksum of the local file and the remote one (that is located on the SFTP server).

Does Paramiko functionality allows to do that? If it is the case, how exactly it works?


回答1:


With the SFTP, running over an encrypted SSH session, there's no chance the file contents could get corrupted while transferring. So unless it gets corrupted when reading the local file or writing the remote file, you can be pretty sure that the file was uploaded correctly, if the .put does not throw any error.


If you want to test explicitly anyway:

While there's the check-file extension to the SFTP protocol to calculate a remote file checksum, it's not widely supported. Particularly it's not supported by the most widespread SFTP server implementation, the OpenSSH. See What SFTP server implementations support check-file extension.

If you are lucky to connect to another SFTP server that supports the extension, you can use the Paramiko's SFTPFile.check method.

If not, your only option is to download the file back and compare locally.


If you have a shell access to the server, you can of course try to run some shell checksum command (sha256sum) over a separate shell/SSH connection (or channel) and parse the results. But that's not an SFTP solution anymore.




回答2:


if the file doesn't upload then the method will throw an error, so u can check for error

import paramiko

transport = paramiko.Transport((host, port))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
try:
    sftp.put(local_path, remote_path)
except IOError:
    #'Failure'
except OSError:
    #'Failure'


来源:https://stackoverflow.com/questions/28967969/how-to-check-if-paramiko-successfully-uploaded-a-file-to-an-sftp-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!