本文介绍了将 JSON 文件直接转储到远程 SSH 连接中,而无需先将它们存储在本地机器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to dump data in form a JSON file into a remote server using SSH connection, but I need to dump the data directly into the remote server without dumping it in my local machine first. I am using Paramiko for the SSH connection but I am open to other solutions.

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

I am extracting data from a database and converting this data into dictionaries data structures. Now I would like to dump these dictionaries in the form of a JSON file but I can not save the data in my local machine. I need to dump it directly into a server, which I connect via Python with Paramiko. I need to do everything at the same moment, extract the data from the database, convert into dictionaries, and dump it into the remote server as JSON files.

在这里,我添加了一些包含我需要的基础知识的虚拟代码.

Here I add some dummy code with the basics of my needs.

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 直接发送到服务器.

What I need is, instead of dumping the data into outfile, I would like to dump it into the ssh client.
I am open to another solution or framework. I just need a dictionary as a JSON going to the server directly.

推荐答案

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

Just replace the plain (local) open with Paramiko SFTPClient.open:

sftp = ssh.open_sftp()

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

强制性警告:
不要像这样使用 AutoAddPolicy.这样做会失去安全性.
请参阅Paramiko未知服务器".


Obligatory warning:
Do not use AutoAddPolicy like this. You lose security by doing so.
See Paramiko "Unknown Server".

这篇关于将 JSON 文件直接转储到远程 SSH 连接中,而无需先将它们存储在本地机器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 19:57