简体   繁体   English

用于Python MySQLdb连接的SSH隧道

[英]SSH Tunnel for Python MySQLdb connection

I tried creating a SSH tunnel using 我尝试使用创建SSH隧道

ssh -L 3306:localhost:22 <hostip>

Then running my python script to connect via localhost 然后运行我的python脚本通过localhost连接

conn = MySQLdb.connect(host'localhost', port=3306, user='bob', passwd='na', db='test')

However, I receive the following error 但是,我收到以下错误

(2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")

How can I make sure I'm hitting the correct host and not just some problem with the bind? 我怎样才能确保我找到正确的主机而不仅仅是绑定的一些问题?

Try changing "localhost" to "127.0.0.1" , it should work as you expect. 尝试将"localhost"更改为"127.0.0.1" ,它应该按预期工作。 This behavior is detailed in the manual : 手册中详细介绍了此行为:

UNIX sockets and named pipes don't work over a network, so if you specify a host other than localhost, TCP will be used, and you can specify an odd port if you need to (the default port is 3306): UNIX套接字和命名管道不能在网络上运行,因此如果指定localhost以外的主机,则将使用TCP,如果需要,可以指定奇数端口(默认端口为3306):

db=_mysql.connect(host="outhouse", port=3307, passwd="moonpie", db="thangs")

If you really had to, you could connect to the local host with TCP by specifying the full host name, or 127.0.0.1 . 如果您真的需要,可以通过指定完整主机名或127.0.0.1连接到具有TCP的本地主机。

Does mysqld run on port 22 on the remote? mysqld是否在远程端口22上运行? Call me ignorant but I think what you're trying to do is 叫我无知,但我认为你要做的是

ssh -n -N -f -L 3306:localhost:3306 remotehost

Then making MySQL connections on local machine will transparently get tunneled over to the target host. 然后在本地计算机上建立MySQL连接将透明地通过隧道传输到目标主机。

You can't specify localhost as the hostname, as this suggests that MySQLdb should try to use a UNIX socket. 您不能将localhost指定为主机名,因为这表明MySQLdb应该尝试使用UNIX套接字。 Use 127.0.0.1 for the host instead. 请改用主机127.0.0.1

If you want to make sure the connection works, you can use the standard mysql client. 如果要确保连接正常,可以使用标准的mysql客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM