问题描述
我目前使用 Paramiko 访问 SFTP 服务器并连接到同一服务器上的 PostgreSQL.我发现了很多使用sshtunnel
登录PostgreSQL的例子.但是我不知道如何用纯Paramiko来做.
I currently use Paramiko to access an SFTP server and connect to the PostgreSQL on the same server. I found many examples using sshtunnel
to log on PostgreSQL. But I don't know how to do it with pure Paramiko.
目前我的代码看起来像:
Currently my code looks something like:
# establish SSH tunnel
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(hostname=host, username=user, password=password)
# setup SFTP server
self.sftp = self.ssh.open_sftp()
# connect to datebase
self.engine = create_engine('postgres+psycopg2://{}:{}@{}:{}/{}'.format(user, password, host, port, db))
感谢您的任何建议!
推荐答案
使用 SSH 端口转发.
Use SSH port forwarding.
修改 使用 Python Paramiko 的嵌套 SSH 中的代码进行数据库隧道,您会得到如下代码:
Modifying the code from Nested SSH using Python Paramiko for database tunneling, you get a code like this:
# establish SSH tunnel
self.ssh = paramiko.SSHClient()
# ...
self.ssh.connect(hostname=ssh_host, username=ssh_user, password=ssh_password)
transport = ssh_client.get_transport()
dest_addr = (db_host, db_port)
local_unique_port = 4000 # any unused local port
local_host = 'localhost'
local_addr = (local_host, local_unique_port)
vmchannel = vmtransport.open_channel("direct-tcpip", dest_addr, local_addr)
self.engine = create_engine(
'postgres+psycopg2://{}:{}@{}:{}/{}'.format(
db_user, db_password, local_host, local_unique_port, db))
如果 PostgreSQL 数据库在 SSH 服务器本身上运行,那么它通常只会在环回接口上侦听.在这种情况下,db_host
应该设置为 localhost
.
If the PostgreSQL database runs on the SSH server itself, then it will typically listen on the loopback interface only. In that case db_host
should be set to localhost
.
但请注意,sshtunnel
只是 Paramiko 的包装器.所以一般来说,你可以用它来简化代码,除非你有一些限制阻止你安装额外的包.
Though note that sshtunnel
is just a wrapper around Paramiko. So in general, you can use it to simplify the code, unless you have some restrictions preventing you from installing additional packages.
例如:在 Python 中通过 SSH 隧道连接到 PostgreSQL 数据库
基于关于 MongoDB 的相同问题:
使用 Python 中的私钥通过 SSH 连接和查询 Mongo 数据库.
强制性警告:请勿使用 AutoAddPolicy
- 您将失去针对 MITM 攻击 这样做.如需正确的解决方案,请参阅Paramiko未知服务器".
Obligatory warning: Do not use AutoAddPolicy
- You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".
这篇关于使用 Paramiko 设置 SSH 隧道以访问 PostgreSQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!