问题
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