使用SSH转发连接远程localhost 端口
前言
目前博客使用的是Hexo 的框架进行部署的,所以在每次发布博客前,我都可以通过hexo server —-debug
来对新的页面进行检验,保证页面的整体格式、内容、图片都是得当的。使用hexo server
会在服务器端的环回地址(localhost or 127.0.0.1)开启一个4000 端口的侦听进程,给管理员提供访问。
我们可以通过iptalbes 等防火墙技术来配置SNAT 达到远程访问服务器环回地址的作用,但这样做有几个不妥之处:1. 我们需要将一个debug 的进程暴露给公网,且该进程是没有提供用户身份认证服务的; 2. hexo server 提供的是HTTP 的页面访问,并没有使用HTTPS 对相关流量进行加密。
后来通过搜索文档,我找到了一个使用SSH 来将本地端口和远程服务器端口绑定的一种方法,在此分享给大家。
SSH 的配置
搜索SSH 的man page,可以看到对-L
的注释如下:
Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side. This works by allocating a socket to listen to either a TCP port on the local side, ptionally bound to the specified bind_address, or to a Unix socket. Whenever a connection is made to the local port or socket, the connection is forwarded over the secure channel, and a connection is made to either host port hostport, or the Unix socket remote_socket, from the remote machine.
指定要将与本地(客户端)主机上给定TCP端口或Unix套接字的连接转发到远程端的给定主机和端口或Unix套接字。这是通过分配套接字来侦听本地端的TCP端口(临时绑定到指定的BIND_ADDRESS或Unix套接字)来实现的。每当连接到本地端口或套接字时,都会通过安全通道转发连接,并从远程计算机建立到主机端口hostport或Unix套接字remote_socket的连接。
# 用法 |
指定本地端口转发到服务器端4000 端口
所以如果我希望在本地浏览hexo
服务器的localhost:4000
端口,我可以在terminal 使用如下命令:
# 将发送到本地的4000 端口的流量转发到远程服务器149.28.131.106 的127.0.0.1:4000 |
效果展示
- 打开hexo 博客的server 模式
hexo server --debug
:# 得到提示
04:49:51.611 INFO Hexo is running at http://localhost:4000 . Press Ctrl+C to stop.
04:49:51.626 DEBUG Database saved - 在本地terminal (终端)中,输入
ssh -L 4000:127.0.0.1:4000 [email protected]
- 使用浏览器打开
localhost:4000
页面,如果成功打开博客主页且服务器端debug 进程有连接请求,则配置成功