问题
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))
Thanks for any suggestions!
回答1:
Use SSH port forwarding.
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))
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
.
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.
For example: Connecting to PostgreSQL database through SSH tunneling in Python
Based on the same question about MongoDB:
Connect and query Mongo database over SSH with private key in Python.
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".
来源:https://stackoverflow.com/questions/64291009/setup-ssh-tunnel-with-paramiko-to-access-postgresql