ssh - 创建从 Jump 主机到数据库的 SSH 隧道并通过 Jump 主机端口访问数据库

标签 ssh database-connection portforwarding ssh-tunnel autossh

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

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

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

我正在 ServerA 上运行以下命令

ssh -f -N -i ~/keys/test.pem <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0c6cfcfe0c6cfcf8ed3d4cfd2c5d3c1cec4c2cfd88ec3cfcd" rel="noreferrer noopener nofollow">[email protected]</a> -L5001:127.0.0.1:2001

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

如果我在服务器 A 和运行 MySQL 客户端的位置之间创建另一个隧道。然后就可以了。但我不想那样做。

此问题的原因可能是什么。我对脚本编写相当陌生

最佳答案

默认情况下,当您使用这样的命令时,本地端(ssh 客户端)会在地址为 127.0.0.1 的环回接口(interface)处创建监听端口

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

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

要指示本地 ssh 客户端向全世界共享此类映射端口,您需要指示它绑定(bind)到所有接口(interface)(包括环回)或仅绑定(bind)到特定接口(interface)

# 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 
sudo netstat -ntlp | grep 3306 
tcp  0 0 0.0.0.0:3306   0.0.0.0:*   LISTEN 12354/ssh

#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

关于ssh - 创建从 Jump 主机到数据库的 SSH 隧道并通过 Jump 主机端口访问数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61309319/

相关文章:

git - maven-release-plugin 不使用作业配置或/和 .ssh/config 中提供的 ssh key

php - fatal error : Call to a member function query() on null

mysql - 无法使用外部IP地址连接到MySQL数据库

Python YahooFinancials 结合 mysql 连接器导致 SSL 错误

docker - docker-compose 中的端口转发

macos - 从其他物理机访问Docker容器IP

localhost - 从互联网访问本地主机

c++ - 如何用c++建立一个简单的ssh连接

linux - 通过 ssh 杀死远程进程

使用 GIT_SSH 时 git ls-remote 挂起