我正在尝试通过 SSH 从我的本地 Windows 机器连接到 MySQL 服务器。SSH 连接工作正常,但运行以下 Python 脚本时无法连接到 MySQL 服务器:
import mysql.connector
import sys
import time
import paramiko
host = 'remote-ssh-host'
i = 1
while True:
print("Trying to connect to %s (%i/30)" % (host, i))
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port=22, username='sshuser', password='sshpwd')
print("Connected to %s" % host)
break
except paramiko.AuthenticationException:
print("Authentication failed when connecting to %s" % host)
sys.exit(1)
except:
print("Could not SSH to %s, waiting for it to start" % host)
i += 1
time.sleep(2)
# If we could not connect within time limit
if i == 30:
print("Could not connect to %s. Giving up" % host)
sys.exit(1)
cnx = mysql.connector.connect(user="mysqluser", password="mysqlpwd",
host="mysqlhost",
port=3307)
这是输出:
Trying to connect to remote-ssh-host (1/30)
Connected to remote-ssh-host
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\mysql\connector\network.py", line 469, in open_connection
self.sock.connect(sockaddr)
TimeoutError: [WinError 10060]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\path\to\script\ssh_mysql_test.py", line 50, in <module>
port="3307"
...
File "C:\Python34\lib\site-packages\mysql\connector\network.py", line 472, in open_connection
errno=2003, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'mysqlhost:3307' (10060)
类似的问题已经在这里和这里被问过,但我认为这个问题与 mysql-connector-python 处理端口号的连接字符串的方式有关,因为当使用 Putty 终端时,我可以让它工作:
login as: sshuser
sshuser@remote-ssh-host's password:
sshuser@remote-ssh-host:~$ mysql -h mysqlhost -P 3307 -u mysqluser -p
Enter password:
...
mysql>
但是,当以与 mysql-connector-python 相同的方式指定端口号时:
login as: sshuser
sshuser@remote-ssh-host's password:
sshuser@remote-ssh-host:~$ mysql -h mysqlhost:3307 -u mysqluser -p
Enter password:
ERROR 2005 (HY000): Unknown MySQL server host 'mysqlhost:3307' (0)
我意识到错误编号是不同的(2003 年与 2005 年),但我认为它们是相关的。所以问题实际上是:如何格式化端口号以使连接执行为-h hostname -P port
而不是-h hostname:port
?