我正试图通过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)here和here也提出了类似的问题,但我认为这个问题与mysql-连接器-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连接器-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。
发布于 2016-07-13 08:53:58
问题是ssh和MySQL连接是完全分开的。为了让您的MySQL连接通过ssh工作,您需要通过ssh连接隧道-- MySQL连接。
first SO topic you linked实际上提供了这个问题的答案:使用ssh隧道组件创建隧道,MySQL连接通过隧道定向。
server = SSHTunnelForwarder(
('host', 22),
ssh_password="password",
ssh_username="username",
remote_bind_address=('127.0.0.1', 3306))上面的代码将ssh连接绑定到本地主机的端口3306。因此,任何连接到127.0.0.1:3306的连接都将通过ssh连接到远程服务器进行隧道化。
engine = create_engine('mysql+mysqldb://user:pass@127.0.0.1:%s/db' % server.local_bind_port)在上面的代码中,MySQL连接被设置为127.0.0.1:3306,因此它将通过ssh连接进行隧道化。您需要遵循相同的模式:创建绑定到本地端口的ssh隧道,并在MySQL连接字符串中指定此本地端口而不是远程端口。
https://stackoverflow.com/questions/38346392
复制相似问题