gpt4 book ai didi

python - 使用 SFTP 缓慢上传许多小文件

转载 作者:行者123 更新时间:2023-12-05 01:09:35 25 4
gpt4 key购买 nike

当使用SFTP上传100个100字节的文件时,这里需要17秒(连接建立后,我什至没有计算初始连接时间)。这意味着仅传输 10 KB 需要 17 秒,即 0.59 KB/秒!

我知道向 openwriteclose 等发送 SSH 命令可能会产生很大的开销,但是,在使用 SFTP 发送许多小文件时,有没有办法加快处理速度?

paramiko/pysftp 中的特殊模式将所有要执行的写入操作保存在内存缓冲区中(假设最后 2 秒的所有操作),以及然后在一个分组的 SSH/SFTP channel 中做所有事情?这样可以避免在每个操作之间等待 ping 时间。

注意:

  • 我的连接上传速度约为 100 KB/s(测试上传速度为 0.8 Mbit),到服务器的 40 毫秒 ping 时间
  • 当然,如果不是发送 100 个 100 字节的文件,而是发送 1 个 10 KB 字节的文件,则需要 <1 秒
  • 我不想远程运行二进制程序,只接受 SFTP 命令
import pysftp, time, os
with pysftp.Connection('1.2.3.4', username='root', password='') as sftp:
with sftp.cd('/tmp/'):
t0 = time.time()
for i in range(100):
print(i)
with sftp.open('test%i.txt' % i, 'wb') as f: # even worse in a+ append mode: it takes 25 seconds
f.write(os.urandom(100))
print(time.time() - t0)

最佳答案

使用以下方法(100 个异步任务),大约 0.5 秒即可完成,这是一个巨大的改进。

import asyncio, asyncssh  # pip install asyncssh
async def main():
async with asyncssh.connect('1.2.3.4', username='root', password='') as conn:
async with conn.start_sftp_client() as sftp:
print('connected')
await asyncio.wait([sftp.put('files/test%i.txt' % i) for i in range(100)])
asyncio.run(main())

我将探索源代码,但我仍然不知道它是否将许多操作分组在几个 SSH 事务中,或者它是否只是并行运行命令。

关于python - 使用 SFTP 缓慢上传许多小文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65106405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com