0%

Ngrok 配置方法

利用Ngrok进行内网穿透的基本配置(截止2018/0319)

2022年注:Ngrok不推荐使用,建议使用frp替代,简单易用。

准备工作:域名,并做好解析(domain.org及***.**domain.org)
服务器端开放端口(如果有防火墙的话)

  1. 安装go,下载编译好的包即可。设置GOROOT.GOPATH.PATH环境变量

  2. 下载ngrok源码

1
git clone https://github.com/inconshreveable/ngrok.git
  1. 生成私有证书,并拷贝近assets文件夹

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    cd ngrok
    export NGROK_DOMAIN="domain.org"
    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
    cp rootCA.pem assets/client/tls/ngrokroot.crt
    cp device.crt assets/server/tls/snakeoil.crt
    cp device.key assets/server/tls/snakeoil.key
  2. 编译

1
2
GOOS=linux GOARCH=amd64
make release-server release-client
  1. 打开ngrokd服务器端命令
1
./bin/ngrokd -domain="domain.org"  -httpAddr=":80" -httpsAddr=":443" -tunnelAddr=":4443"
  1. 拷贝bin/ngrok至客户机

  2. 填写配置文件模板:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server_addr: "domain.org:8082"
trust_host_root_certs: false
tunnels:
http:
subdomain: "www"
proto:
http: "80"
https:
subdomain: "www"
proto:
https: "80"
ssh:
remote_port: 100 #映射为服务器端口,需开放
proto:
tcp: "22" #待映射的客户机端口
  1. 开机启动,设置service文件,/etc/systemd/system/ngrok.service
    开机自动启动 systemctl enable ngrok
    启动 systemctl start ngrok
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[Unit]
Description=Ngrok Service
Wants=network-online.target
After=network.target

[Service]
Type=simple
ExecStart=/usr/sbin/ngrok-work -config=/home/shitw/ngrok/LAAS.cfg -log-level=WARNING -log=/var/log/ngrok.log start ssh
StandardOutput=syslog
StandardError=null
Restart=always
RestartSec=30

[Install]
WantedBy=multi-user.target
  1. 更换ngrok端口与nginx80端口共用

既然「nginx」占用了80端口,那么就在「nginx」上做文章。只要绑定ngrok.zmkj6.top 并将所有请求转发到8002端口即可。在服务器中新建/etc/nginx/conf.d/ngrock.conf文件,添加以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
upstream ngrok {
server 127.0.0.1:8002;
#此处端口要跟 启动服务端ngrok时指定的端口一致
keepalive 64;
}
server {
listen 80;
server_name *.ngrok.zmkj6.top;
#charset koi8-r;
access_log logs/ngrok.log;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For
$proxy_add_x_forwarded_for;
proxy_set_header Host $http_host:8002;
# 此处端口要跟 启动服务端ngrok 时指定的端口一致
proxy_set_header X-Nginx-Proxy true;
proxy_set_header Connection "";
proxy_pass http://ngrok;
}
}

重新加载「nginx」

1
nginx -s reload

此外,「ngrok」+ 「nginx」+「Docker」也可以完美实现,由于对Docker」不了解没有去折腾