Using net/ssh/gateway to establish ssh tunnel to m

2019-08-01 10:40发布

I'm attempting to establish a tunnel to a remote server via ssh, and then use the forwarded port to access MySQL.

I'm using it currently like this

$gateway = Net::SSH::Gateway.new('target.server', 'user')

def with_gateway
  $gateway.open("target.server", 3306) do |port|
    yield port
  end
end

Which in my mind would be similar to this...

`ssh -L #{port}:localhost:3306 -N user@target.server`

Then when I try to use it and do something like this.

with_gateway do |port|
  puts `mysql -u user -ppass -h 127.0.0.1 -P #{port} -e SHOW\ DATABASES\;`
end

It gives me this error message..

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0

What am I missing?

1条回答
beautiful°
2楼-- · 2019-08-01 11:43

$gateway.open("target.server", 3306) do |port|

is more equivalent to, in this case,

ssh -L #{port}:target.server:3306 -N user@target.server

which may very well fail if your mysql server only listens on 127.0.0.1 (or on an internal IP address, or firewalled to only allow connections via internal networks, all of which are reasonable and normal configurations).

Probably you want:

$gateway.open("127.0.0.1", 3306) do |port|

instead in this case.

查看更多
登录 后发表回答