Ngrok是什么

​ ngrok是一个内网穿透的解决方案:它使得你本地的服务器可以被局域网外的公网访问到,ngork有服务端和客户端,服务端运行在公网服务器,客户端运行在本地服务器

Ngrok服务器搭建

必备条件

  1. 具有公网IP的服务器
  2. 可进行解析配置的域名

搭建步骤

本文基于CentOS7的环境进行搭建,Ubuntu环境类似,本文不再赘述
1. 安装git和go以及其它依赖
1
yum install gcc mercurial git bzr subversion golang golang-pkg-windows-amd64 golang-pkg-windows-386 -y
2. 下载源码
1
git clone https://github.com/inconshreveable/ngrok.git
3. 生成证书
1
2
3
4
5
6
7
8
cd ngrok
#将xxxx.xxxx修改为你自己的域名
export NGROK_DOMAIN="xxxx.xxxx"
openssl genrsa -out rootCA.key 2048
openssl req -x509 -new -nodes -key rootCA.key -subj "/CN=$NGROK_DOMAIN" -days 5000 -out rootCA.pem
openssl genrsa -out device.key 2048
openssl req -new -key device.key -subj "/CN=$NGROK_DOMAIN" -out device.csr
openssl x509 -req -in device.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out device.crt -days 5000
4.替换证书
1
2
3
4
#在ngrok目录下执行
cp rootCA.pem assets/client/tls/ngrokroot.crt
cp device.crt assets/server/tls/snakeoil.crt
cp device.key assets/server/tls/snakeoil.key
5.生成服务端&客户端
1
2
3
4
5
6
#linux amd64 服务端
GOOS=linux GOARCH=amd64 make release-server
#windows amd64 客户端
GOOS=windows GOARCH=amd64 make release-client
#linux amd64 客户端
GOOS=linux GOARCH=amd64 make release-client
6.运行服务端
1
2
3
4
5
mkdir -p /usr/local/ngrok
#ngrok目录下
cp bin/ngrokd /usr/local/ngrok/

cd /usr/local/ngrok
start.sh
1
2
#!/bin/bash
/usr/local/ngrok/ngrokd -domain="xxxx.xxxx" -httpAddr=":80" -httpsAddr=":4443" -tunnelAddr=":8083" >> ./ngrok.log 2>&1 &
ngrok_monitor.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/bin/bash
# ===========================================================================
# 程序名称: ngrok_monitor.sh
# 功能描述: ngrok监控
# 创建人: zhhades
# 创建日期: 2020-04-21
# 版本说明: v1.0
# ===========================================================================
DATE_DIR=`date +%F`
STIME=`date`
PROC="/usr/local/ngrok"

MAINPID=`ps -ef|grep ngrokd|grep -v grep `

echo $STIME
#check main programme status
if [ ! "$MAINPID" ];then
cd $PROC
echo "ngrokd is not running..."
sh start.sh
echo "start ngrokd success..."
else
echo "ngrokd is running..."
fi
配置cron定时任务
1
*/10 * * * * /bin/sh /usr/local/ngrok/ngrok_monitor.sh >> $HOME/crontab_log/crontab.log 2>&1

以上即搭建好ngrok服务端程序

客户端配置

windows客户端

将bin目录下打包生成的windows客户端程序copy到windows服务器,新增ngrok.bat、ngrok.cfg等文件,ngrok.exe与以上两个文件在同一目录

ngrok.bat
1
ngrok.exe -config=ngrok.cfg start-all
ngrok.cfg
1
2
3
4
5
6
7
server_addr: "XXXX.XXXX:8083"
trust_host_root_certs: false
tunnels:
mstsc:
remote_port: 23389
proto:
tcp: "127.0.0.1:3389"

双击ngrok.bat即可运行客户端,如下图所示

image-20210410203108209

将ngrok.bat安装为windows服务

使用nssm-2.24-101将ngrok.bat安装为windows服务,开机自启动。进入nssm-2.24-101\win64目录cmd,nssm.exe install弹出如下界面,点击path后的按钮,选择ngrok.bat,填上Service name,点击Install service,此时安装成功。进入服务列表,点击启动服务,大功告成。

image-20210410203707085

总结

  1. 生成证书与替换证书比较重要,一定不能搞错了
  2. 相应域名要解析到ngrok服务端所在服务器