An SSH local forward listens on the machine where the SSH client runs. If port 9997 was opened by an SSH client on your workstation, a Python program in a remote shell cannot reach it through its own 127.0.0.1:9997. Run Python on the workstation beside the tunnel, or create a separate tunnel in the environment where Python runs.
Last updated: November 22, 2026.
import os
import mysql.connector
connection = mysql.connector.connect(
host="127.0.0.1",
port=9997,
user="app_reader",
password=os.environ["MYSQL_PASSWORD"],
database="appdb",
connection_timeout=10,
)
cursor = connection.cursor()
try:
cursor.execute("SELECT DATABASE(), CURRENT_USER()")
print(cursor.fetchone())
finally:
cursor.close()
connection.close()Run this program on the same workstation that owns the local forwarding socket. Keep the password outside the source file, use a restricted database account, and do not expose MySQL port 3306 publicly to make the connection easier.
Place the tunnel and program on the same host
A typical command is ssh -N -L 127.0.0.1:9997:db.internal:3306 user@bastion. OpenSSH documents local forwarding with -L as a listener allocated on the local side. Traffic entering that listener crosses the SSH connection, then the remote side connects to db.internal:3306.
Every machine has its own loopback interface. In a workstation terminal, 127.0.0.1 means the workstation; inside an SSH session, it means the remote host. A command-line MySQL client can work locally while a Python process launched remotely receives “connection refused” because those processes are contacting different loopback sockets.
Verify each side without changing network exposure
First keep the SSH session that owns the forward open and confirm the workstation is listening on port 9997. Then run the MySQL command-line client and Python from that same workstation with host 127.0.0.1 and port 9997. Oracle’s Connector/Python connection arguments define host, integer port and connection_timeout for this connection.
If Python must run on another server, establish an approved local forward there or use an existing private network path. Do not bind the workstation listener to every interface unless remote access is explicitly required and protected. A tunnel that connects but fails authentication is a different problem: check the MySQL account, allowed host and privileges instead of changing the SSH direction.