Issue
I have a snippet of code that allows me to connect to my psql DB via ssh in Python. It works perfectly on Ubuntu 18.10 (via VirtualBox) but fails every time on windows with an error that it can't reach the remote host and port.
I'm been developing a user interface that can query data from a remote DB (logs etc.) and visualize it.
All of the development has been done using Spyder3 on Ubuntu 18.10. I never had an issue until I tried to execute the same code on Windows 10.
I tried Telnet to both the localhost:port and remote host:port (via ssh) and it works. Having looked up all the possible answers on stackoverflow and other places, I still haven't been able to fix the issue. The fact that it works on one environment and not on the other, while on the same machine, tells me it's some sort of environment setting but I don't know what it could be.
The code:
import psycopg2
import logging
logging.basicConfig(level=logging.DEBUG)
from sshtunnel import SSHTunnelForwarder
PORT = 5432
REMOTE_HOST = '111.222.111.222'
REMOTE_SSH_PORT = 22
curs = None
conn = None
server = SSHTunnelForwarder((REMOTE_HOST, REMOTE_SSH_PORT),
ssh_username='username',
ssh_password='password',
remote_bind_address=('localhost', PORT),
local_bind_address=('localhost', PORT))
server.start()
conn = psycopg2.connect(database='db_name', user='db_username', password='db_password', host='127.0.0.1', port='5432')
curs = conn.cursor()
Expected: A successful connection to ssh and subsequent successful log-in to the database. This works on Ubuntu 18.10 via VirtualBox on the same machine.
Actual result: 2019-01-02 10:54:51,489 ERROR Problem setting SSH Forwarder up: Couldn't open tunnel localhost:5432 <> localhost:5432 might be in use or destination not reachable
Solution
I realized that my local postgres (psql) service was interfering with the port mapping as it was also using port 5432. Once I disabled the service, it worked like a charm.
Answered By - Alexandros