将 JSON 个文件直接转储到远程 SSH 连接中,而不先将它们存储在本地计算机中

Dump JSON files directly into a remote SSH connection without storing them in local machine first

我需要使用 SSH 连接将数据以 JSON 文件的形式转储到远程服务器,但我需要将数据直接转储到远程服务器,而不是先转储到我的本地机器。我正在使用 Paramiko 进行 SSH 连接,但我对其他解决方案持开放态度。

我正在从数据库中提取数据并将这些数据转换为字典数据结构。现在我想以 JSON 文件的形式转储这些词典,但我无法将数据保存在我的本地机器中。我需要将它直接转储到我通过 Python 与 Paramiko 连接的服务器中。我需要同时做所有事情,从数据库中提取数据,转换成字典,然后将其作为 JSON 个文件转储到远程服务器。

在这里,我添加了一些虚拟代码来满足我的需求。

import paramiko

dicty = {'a': 1, 'b':2, 'c': 3}

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('141.42.48.20', username='user', password='psw')

with open('dictionary.txt', 'w') as outfile:
    json.dump(dicty, outfile, default=myconverter)

ssh.close()

我需要的是,与其将数据转储到 outfile,不如将其转储到 ssh 客户端。
我对另一个解决方案或框架持开放态度。我只需要一本字典作为 JSON 直接转到服务器。

只需将普通(本地)open 替换为 Paramiko SFTPClient.open:

sftp = ssh.open_sftp()

with sftp.open('dictionary.txt', 'w') as outfile:
    json.dump(dicty, outfile, default=myconverter)

强制警告:
不要像这样使用 AutoAddPolicy。这样做会失去安全感。
参见 Paramiko "Unknown Server"