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

使用Python脚本从Linux服务器向Windows服务器传输文本文件时,发现SFTP库(如pysftp/Paramiko)不支持文本模式。由于SFTP协议版本3中不存在文本模式,你需要在传输前预先进行文件格式转换。文中提供了一个简单的实现,通过读取Linux格式的文件,替换换行符为Windows格式,然后写入远程文件。
摘要由CSDN通过智能技术生成

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)

要在 Python使用 SFTP(Secure File Transfer Protocol传输文件,你可以使用 `paramiko` 库。`paramiko` 是一个为 SSH 2 协议提供客户端和服务器功能的库,它也包含了 SFTP 功能。 首先,你需要安装 `paramiko` 库。你可以使用以下命令在终端中安装: ``` pip install paramiko ``` 下面是一个示例代码,展示了如何使用 `paramiko` 进行 SFTP 文件传输: ```python import paramiko # 创建 SSH 客户端 ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接到远程服务器 hostname = 'sftp.server.com' port = 22 username = 'username' password = 'password' ssh.connect(hostname, port, username, password) # 创建 SFTP 客户端 sftp = ssh.open_sftp() # 下载文件 remote_path = '/path/to/remote/file.txt' local_path = '/path/to/local/file.txt' sftp.get(remote_path, local_path) # 上传文件 remote_path = '/path/to/remote/file.txt' local_path = '/path/to/local/file.txt' sftp.put(local_path, remote_path) # 关闭连接 sftp.close() ssh.close() ``` 在这个示例中,我们首先创建一个 `SSHClient` 对象,并设置了自动添加主机密钥的策略。然后,使用 `connect` 方法连接到远程服务器,提供主机名、端口、用户名和密码。 接下来,我们使用 `open_sftp` 方法创建一个 `SFTPClient` 对象。然后,可以使用 `get` 方法下载远程文件到本地,或使用 `put` 方法上传本地文件到远程服务器。 最后,我们使用 `close` 方法关闭 SFTP 连接和 SSH 连接。 请注意,为了安全起见,建议将用户名和密码存储在安全的地方,并避免在代码中明文显示。你可以使用其他安全措施,例如使用密钥进行身份验证。 希望这个示例能够帮助到你!如果还有其他问题,请随提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值