ngrok实现内网穿透(以Python FastAPI为例)

文章目录

简介

内网穿透:让外网设备能够访问你家或公司局域网内部的设备

ngrok:把本地电脑上的服务,如 API 接口安全地暴露到公网的工具。在没有公网 IP、无法配置路由器的情况下,也能让外网访问到本地服务

ngrok 工作原理:由内网主动建立一个到公网服务器的加密隧道,所有外部流量都通过这个隧道转发到本地服务

还可以使用 Cloudflare Tunnel

安装

解压到某目录下,添加环境变量 Path

shell 复制代码
ngrok config add-authtoken xxx

初试

main.py

python 复制代码
import uvicorn
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def index():
    return {"Hello": "World"}


if __name__ == "__main__":
    uvicorn.run("main:app")

暴露 8000 端口

shell 复制代码
ngrok http 8000

访问 Forwarding 的链接

Visit Site

查看请求日志

http://127.0.0.1:4040

设置静态域

免费版只能 1 个静态随机域名

前后端分离

frontend.html

html 复制代码
<!doctype html>
<html>
<head><meta charset="utf-8"><title>demo</title></head>
<body>
  <button id="btn">调后端</button>
  <pre id="out"></pre>

  <script>
    const API = "https://thing-prance-spindle.ngrok-free.dev";

    document.getElementById("btn").onclick = async () => {
      const r = await fetch(API + "/hello", {
        headers: { "ngrok-skip-browser-warning": "1" }
      });
      const data = await r.json();
      document.getElementById("out").textContent = JSON.stringify(data, null, 2);
    };
  </script>
</body>
</html>

backend.py

python 复制代码
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
    allow_credentials=True,
)


@app.get("/hello")
def hello():
    return {"msg": "hello"}


app.mount("/", StaticFiles(directory=".", html=True), name="static")


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

启动

shell 复制代码
python backend.py

映射

shell 复制代码
ngrok http 8000

访问 https://thing-prance-spindle.ngrok-free.dev/frontend.html

TODO:多隧道

免费版并发隧道可以 3 条

backend.py

python 复制代码

启动

shell 复制代码
python backend.py

frontend.html

html 复制代码

启动

shell 复制代码
python -m http.server 3000

修改 %USERPROFILE%\AppData\Local\ngrok\ngrok.yml

yaml 复制代码
version: "3"
agent:
    authtoken: 你的token
    
tunnels:
  backend:
    proto: http
    addr: 8000
    domain: 你的domain(如thing-prance-spindle.ngrok-free.dev)
    
  frontend:
    proto: http
    addr: 3000

启动

shell 复制代码
ngrok start backend frontend

ngrok start --all

参考文献

  1. ngrok
相关推荐
Canmag 兴隆磁性4 分钟前
C 系列充磁机
c语言·开发语言·学习·永磁材料·充磁·退磁
zmzb010313 分钟前
Python课后习题训练记录Day194
python·opencv·计算机视觉
benchmark_cc26 分钟前
批量获取量化数据时,如何设置合理的超时和重试机制?——QuantDash 高性能实战指南
开发语言·人工智能·python·pandas·量化·quantdash
2601_9669496527 分钟前
使用 Pandas 读取批量数据时如何避免内存溢出?QuantDash 量化数据工程师避坑指南
开发语言·python·pandas·tushare·akshare·quantdash
65岁退休Coder35 分钟前
LangChain v1.3.4 笔记 - 08 MCP & 相关概念
后端·python·langchain
郑州光合科技余经理36 分钟前
海外版多语言团购系统架构:主数据互通与核销边界
java·开发语言·前端·后端·系统架构·php·ai编程
ttwuai1 小时前
Go 后台图片上传到对象存储后,预览 403/404 怎么排查?
开发语言·golang
wdloumiga1 小时前
使用 Construct 3零基础做一些2D小游戏
python·游戏·游戏2d
绿浪19841 小时前
c# 结构体 能不能直接封送检测
开发语言·c#
用户8356290780511 小时前
使用 Python 查找和替换 Word 文档中的文本
后端·python