19

I tried creating a SSH tunnel using

ssh -L 3306:localhost:22 <hostip>

Then running my python script to connect via 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?

John Giotta
  • 16,432
  • 7
  • 52
  • 82

3 Answers3

18

Try changing "localhost" to "127.0.0.1", it should work as you expect. 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):

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.

Tarantula
  • 19,031
  • 12
  • 54
  • 71
13

Does mysqld run on port 22 on the remote? 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.

Novikov
  • 4,399
  • 3
  • 28
  • 36
  • Yes, and you can test it if you have a telnet client available on the local host: `telnet localhost 3306` should establish a connection and display a recognizable MySQL version number. – Ned Deily Aug 26 '10 at 17:22
  • I think this answer is better than the chosen one, because the proposed way makes it possible to stay on your local machine instead of being remote. – Johann Hagerer Jul 14 '15 at 09:26
3

You can't specify localhost as the hostname, as this suggests that MySQLdb should try to use a UNIX socket. Use 127.0.0.1 for the host instead.

If you want to make sure the connection works, you can use the standard mysql client.

Michael Mior
  • 28,107
  • 9
  • 89
  • 113