创建从跳转主机到数据库的SSH隧道,并在跳转主机端口上访问数据库

问题描述 投票:1回答:1

我正在尝试在运行服务器端口的数据库和另一台服务器之间创建SSH隧道,如下所示。

MySQL:3306 <=====> Server-A:3306

而且我想使用Server-A:3306作为数据库URI来连接数据库。

我正在ServerA上运行以下内容

ssh -f -N -i ~/keys/test.pem [email protected] -L5001:127.0.0.1:2001

我可以看到隧道已启动并正在运行。但是,当我使用Server-A的公共IP并尝试连接到数据库时,它不起作用。

如果我在Server-A和运行MySQL客户端之间创建另一个隧道。然后就可以了。但我不想这样做。

可能是此问题的原因。我对脚本还很陌生

ssh database-connection portforwarding ssh-tunnel autossh
1个回答
0
投票

默认情况下,本地端(ssh客户端)在使用像这样的命令时在回送接口上创建监听端口,地址为127.0.0.1

ssh me@server -L3306:localhost:3306

如果您在主机上看到检查netstat,您将看到类似这样的内容

sudo netstat -ntlp | grep 3306
tcp  0 0 127.0.0.1:3306  0.0.0.0:*   LISTEN 12354/ssh

因此,本地节点上的应用程序可以连接到此类映射的服务,因为环回接口对于主机本身是可见的,但外部节点无法访问此虚拟接口,因此无法与正在侦听此服务的任何服务(端口)建立任何连接单一界面。

要指示本地ssh客户端将映射的端口共享给世界,您需要指示它绑定到所有接口(包括回送)或仅绑定到特定接口

# here you explicitly tell ssh client to accept connection to your tunnel
# from any client(i.e. bind listenning port to all interfaces)
ssh me@server -L0.0.0.0:3306:localhost:3306 

#here you do the same thing by using -g option
ssh me@server -g -L3306:localhost:3306
sudo netstat -ntlp | grep 3306 
tcp  0 0 0.0.0.0:3306   0.0.0.0:*   LISTEN 12354/ssh

#and here is an example of how to bind to specific interfaces only
# 10.0.0.12 is an IP of one of interfaces on your node
# 10.1.0.156 is also IP address of one interfaces of your node
ssh me@server -L10.0.0.12:3306:localhost:3306 -L10.1.0.156:3306:localhost:3306

sudo netstat -ntlp | grep 3306
tcp  0 0 10.0.0.12:3306   0.0.0.0:*   LISTEN 12354/ssh
tcp  0 0 10.1.0.156:3306  0.0.0.0:*   LISTEN 12354/ssh

© www.soinside.com 2019 - 2024. All rights reserved.