Python MySQLdb连接的SSH隧道

2024-04-26 10:03:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用

ssh -L 3306:localhost:22 <hostip>

然后运行python脚本通过localhost连接

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

但是,我收到以下错误

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

我怎样才能确保我击中了正确的主机,而不仅仅是绑定的问题?


Tags: 脚本localhosthostdbportconnectmysqlconn
3条回答

尝试将"localhost"更改为"127.0.0.1",它应该可以按预期工作。此行为在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):

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.

mysqld在远程端口22上运行吗?叫我无知,但我认为你想做的是

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

然后,在本地计算机上建立MySQL连接将透明地被传送到目标主机。

不能指定localhost作为主机名,因为这表明MySQLdb应该尝试使用UNIX套接字。用127.0.0.1代替主机。

如果您想确保连接正常工作,可以使用标准的mysql客户机。

相关问题 更多 >