Define transfer mode when trying to SFTP files using Python

孤者浪人 提交于 2019-12-08 04:37:28

问题


We are trying to transfer text files from a Linux server to a Windows server using a python script (which resides on the SFTP server).

It is necessary for us to ensure the files are transferred using text mode. I don't see this possibility in pysftp. Is there any other Python library that supports this?


回答1:


pysftp/Paramiko uses an SFTP protocol version 3.

In the SFTP protocol version 3, there are no transfer modes. Or in other words, there is only the binary transfer mode.

Even if pysftp/Paramiko supported a newer version of SFTP, which do support the text/ascii mode, it is unlikely to help you. Most SFTP servers are OpenSSH. And OpenSSH uses SFTP 3 too.

See also How to transfer binary file in SFTP?


If you need to convert the file to Windows format, you need to do it upfront, before a file transfer.

A naive implementation would be like:

WINDOWS_LINE_ENDING = b'\r\n'
UNIX_LINE_ENDING = b'\n'

with open("/local/path/file.txt", "rb") as local_file:
    contents = local_file.read()
    contents = contents.replace(UNIX_LINE_ENDING, WINDOWS_LINE_ENDING)
    with sftp.open("/remote/path/file.txt", "wb") as remote_file:
        remote_file.write(contents)

(conversion based on How to convert CRLF to LF on a Windows machine in Python)



来源:https://stackoverflow.com/questions/58099119/define-transfer-mode-when-trying-to-sftp-files-using-python

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