SSH跳板机访问内网服务
1. 连接Shell
ssh
的 ProxyJump
选项用于通过一台中间服务器(跳板机)连接到最终目标服务器。这在需要通过一个中间服务器来访问目标服务器时特别有用,例如在内网环境中。ProxyJump
的使用方式非常简单,下面是一些具体的例子和说明。
1.1 基本用法
假设你有以下服务器:
- 跳板机(Jump Host):
jumphost.example.com
- 目标服务器(Target Host):
targethost.example.com
使用 ProxyJump
连接目标服务器的命令如下:
ssh -J jumphost.example.com targethost.example.com
1.2 配置文件方式
为了简化命令,你可以将配置写入 ~/.ssh/config
文件。如下是一个示例配置:
Host targethost
HostName targethost.example.com
User targetuser
ProxyJump jumphost.example.com
然后你可以通过以下命令连接目标服务器:
ssh targethost
1.3 多跳代理
如果需要通过多个跳板机连接到最终目标服务器,可以这样配置:
ssh -J jumphost1.example.com,jumphost2.example.com targethost.example.com
或者在 ~/.ssh/config
文件中进行多跳配置:
Host targethost
HostName targethost.example.com
User targetuser
ProxyJump jumphost1.example.com,jumphost2.example.com
1.4 其他选项
你还可以在配置文件中设置更多的选项,例如用户、端口、私钥路径等:
Host jumphost
HostName jumphost.example.com
User jumpuser
IdentityFile ~/.ssh/jumpkey
Host targethost
HostName targethost.example.com
User targetuser
IdentityFile ~/.ssh/targetkey
ProxyJump jumphost
1.5 实例解析
假设有以下场景:
- 跳板机的地址是
jump.example.com
,登录用户名是jumpuser
。 - 目标服务器的地址是
target.example.com
,登录用户名是targetuser
。
可以使用以下命令连接:
ssh -J jumpuser@jump.example.com targetuser@target.example.com
或者将其配置到 ~/.ssh/config
文件中:
Host jump
HostName jump.example.com
User jumpuser
Host target
HostName target.example.com
User targetuser
ProxyJump jump
然后通过以下命令连接:
ssh target
这样配置和使用 ProxyJump
可以大大简化通过多级跳板机连接的过程,并提升你的工作效率。
2. 访问内网服务
要通过跳板机访问内网服务器上的Web服务,可以使用SSH隧道(SSH tunneling)。下面是详细步骤,包括直接命令行操作和配置文件设置。
2.1 方法一:使用命令行
假设有以下服务器:
- 跳板机(Jump Host):
jumphost.example.com
- 内网Web服务器(Target Host):
targethost.internal
- Web服务端口:
80
你可以使用SSH隧道通过跳板机访问内网Web服务器上的Web服务。具体命令如下:
ssh -N -L 8080:targethost.internal:80 jumphost.example.com
这条命令将本地机器的8080端口映射到内网Web服务器的80端口,通过跳板机进行连接。
之后,在本地浏览器中访问 http://localhost:8080
,即可访问内网Web服务器上的Web服务。
2.2 方法二:使用配置文件
你也可以将配置写入 ~/.ssh/config
文件中以简化命令:
Host targethost
HostName jumphost.example.com
User jumpuser
LocalForward 8080 targethost.internal:80
# 可选项:指定 SSH 密钥路径
# IdentityFile ~/.ssh/id_rsa
这个配置文件中设置了跳板机和内网Web服务器的连接信息,并配置了端口转发。
之后,你只需运行以下命令即可:
ssh -N targethost
同样,在本地浏览器中访问 http://localhost:8080
,即可访问内网Web服务器上的Web服务。
2.3 具体示例
假设:
- 跳板机地址是
jumphost.example.com
,用户是jumpuser
。 - 内网Web服务器地址是
targethost.internal
,用户是targetuser
,Web服务运行在80端口。
2.3.1 命令行方式:
ssh -N -L 8080:targethost.internal:80 jumpuser@jumphost.example.com
然后在浏览器中访问 http://localhost:8080
。
2.3.2 配置文件方式:
在 ~/.ssh/config
中添加:
Host targethost
HostName jumphost.example.com
User jumpuser
LocalForward 8080 targethost.internal:80
然后运行:
ssh -N targethost
在浏览器中访问 http://localhost:8080
。
通过这两种方法,你可以通过跳板机访问内网服务器上的Web服务。配置文件方式在需要频繁连接时更为方便。