我需要使用 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客户端。只需将普通(本地)
open
替换为ParamikoSFTPClient.open
:
sftp = ssh.open_sftp()
with sftp.open('dictionary.txt', 'w') as outfile:
json.dump(dicty, outfile, default=myconverter)
强制性警告:
不要这样使用
AutoAddPolicy
。这样做你会失去安全感。