python sftp_尝试使用Python到SFTP文件时定义传输模式

本文介绍如何通过Python脚本在Linux和Windows服务器之间转移文本文件,并确保文件以文本模式传输。由于SFTP协议版本3不支持文本模式,你需要在传输前将文件内容转换为Windows格式。示例代码展示了如何读取Linux格式的文件,替换行结束符,然后写入到远程Windows服务器的文件中。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

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?

解决方案

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.

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值