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

笑着哭i 提交于 2021-02-19 09:25:50

问题


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.

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()

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.


回答1:


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)

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



来源:https://stackoverflow.com/questions/55951860/dump-json-files-directly-into-a-remote-ssh-connection-without-storing-them-in-lo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!