- 需要使用 魔法(tizi) 将 cloudflared.exe 这个文件下载到本地
- 关闭 魔法(tizi)启动服务器就可以了
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
一键运行:本地 Markdown 笔记服务 + Cloudflare 免费公网隧道
运行: python 笔记.py
说明: 无访问认证,链接即权限,请勿放隐私内容。
"""
import os
import re
import sys
import stat
import time
import html
import shutil
import tarfile
import platform
import mimetypes
import subprocess
import threading
import urllib.request
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import unquote, quote
try:
import markdown
from markdown.extensions.toc import TocExtension
except ImportError:
print("❌ 缺少依赖,请先运行:pip install markdown pygments")
sys.exit(1)
# ================== 配置区 ==================
NOTES_DIR = os.environ.get("NOTES_DIR", "./notes")
LOCAL_PORT = int(os.environ.get("NOTES_PORT", "8000"))
ALLOWED_EXT = {".md", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp"}
# ===========================================
NOTES_DIR = os.path.abspath(NOTES_DIR)
HERE = os.path.dirname(os.path.abspath(__file__))
# ============================================================
# 页面模板
# ============================================================
PAGE_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
<style>
* {{ box-sizing: border-box; }}
html, body {{ height: 100%; }}
body {{
margin: 0; display: flex;
font-family: -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
background: #f6f8fa; color: #24292f;
height: 100vh; overflow: hidden; font-size: 16px; line-height: 1.6;
}}
#sidebar {{
width: 300px; height: 100vh; overflow-y: auto; background: #fff;
border-right: 1px solid #e1e4e8; padding: 16px 12px; font-size: 14px; flex-shrink: 0;
}}
#sidebar h2 {{ font-size: 15px; margin: 0 0 12px; padding-left: 4px; }}
.note-group {{ margin-bottom: 6px; }}
.note-title {{
display: block; padding: 6px 8px; border-radius: 6px; color: #24292f;
text-decoration: none; font-weight: 600; cursor: pointer; word-break: break-all;
}}
.note-title:hover {{ background: #f0f3f6; }}
.note-title.active {{ background: #0969da; color: #fff; }}
.toc-wrap ul {{ list-style: none; padding: 0; margin: 2px 0 6px 0; }}
.toc-wrap ul ul {{ margin: 0; padding-left: 12px; }}
.toc-wrap li {{ margin: 0; }}
.toc-wrap a {{
display: block; padding: 3px 8px; border-radius: 4px; color: #57606a;
text-decoration: none; font-size: 13px; word-break: break-all;
border-left: 2px solid transparent; white-space: normal;
}}
.toc-wrap a:hover {{ background: #f0f3f6; color: #0969da; }}
.toc-wrap a.active {{ color: #0969da; border-left-color: #0969da; background: #f0f6ff; }}
#content {{
flex: 1; padding: 32px 48px; min-width: 0; height: 100vh;
overflow-y: auto; overflow-x: hidden;
}}
#content-inner {{ max-width: 900px; margin: 0 auto; }}
.markdown-body h1, .markdown-body h2, .markdown-body h3,
.markdown-body h4, .markdown-body h5, .markdown-body h6 {{
margin: 24px 0 16px; font-weight: 600; line-height: 1.25; scroll-margin-top: 16px;
}}
.markdown-body h1 {{ font-size: 2em; padding-bottom: .3em; border-bottom: 1px solid #eaecef; }}
.markdown-body h2 {{ font-size: 1.5em; padding-bottom: .3em; border-bottom: 1px solid #eaecef; }}
.markdown-body h3 {{ font-size: 1.25em; }}
.markdown-body h4 {{ font-size: 1em; }}
.markdown-body h5 {{ font-size: .875em; }}
.markdown-body h6 {{ font-size: .85em; color: #6a737d; }}
.markdown-body p {{ margin: 0 0 16px; }}
.markdown-body a {{ color: #0969da; text-decoration: none; }}
.markdown-body a:hover {{ text-decoration: underline; }}
.markdown-body ul, .markdown-body ol {{ padding-left: 2em; margin: 0 0 16px; }}
.markdown-body li {{ margin: 4px 0; }}
.markdown-body blockquote {{
margin: 0 0 16px; padding: 0 1em; color: #6a737d; border-left: .25em solid #dfe2e5;
}}
.markdown-body hr {{
height: .25em; padding: 0; margin: 24px 0;
background-color: #e1e4e8; border: 0;
}}
.markdown-body table {{ border-collapse: collapse; margin: 0 0 16px; display: block; overflow-x: auto; }}
.markdown-body table th, .markdown-body table td {{ padding: 6px 13px; border: 1px solid #dfe2e5; }}
.markdown-body table tr:nth-child(2n) {{ background: #f6f8fa; }}
.markdown-body img {{
max-width: 100%; height: auto; border: 1px solid #e1e4e8;
border-radius: 6px; margin: 8px 0;
}}
.markdown-body .codehilite {{
background: #f6f8fa; border: 1px solid #d0d7de; border-left: 4px solid #0969da;
border-radius: 8px; padding: 12px 16px 12px 18px; overflow-x: auto; margin: 14px 0;
}}
.markdown-body .codehilite pre {{
background: transparent; border: 0; padding: 0; margin: 0; overflow-x: visible;
}}
.markdown-body .codehilite code {{
background: transparent; padding: 0;
font-family: "SFMono-Regular", Consolas, "Courier New", monospace;
font-size: 85%; line-height: 1.55;
}}
.markdown-body pre:not(.codehilite pre) {{
background: #f6f8fa; border: 1px solid #d0d7de; border-left: 4px solid #0969da;
border-radius: 8px; padding: 12px 16px 12px 18px; overflow-x: auto; margin: 14px 0;
font-family: "SFMono-Regular", Consolas, "Courier New", monospace; font-size: 85%;
}}
.markdown-body :not(pre) > code {{
background: rgba(175, 184, 193, 0.25); border: 1px solid rgba(175, 184, 193, 0.4);
padding: 0.15em 0.4em; border-radius: 5px;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 85%; color: #cf222e;
}}
.codehilite .hll {{ background-color: #fff8c5; }}
.codehilite .c, .codehilite .ch, .codehilite .cm, .codehilite .cp,
.codehilite .cpf, .codehilite .c1, .codehilite .cs {{ color: #6a737d; font-style: italic; }}
.codehilite .k, .codehilite .kc, .codehilite .kd, .codehilite .kn,
.codehilite .kp, .codehilite .kr, .codehilite .kt {{ color: #cf222e; font-weight: 600; }}
.codehilite .o, .codehilite .ow {{ color: #cf222e; }}
.codehilite .m, .codehilite .mb, .codehilite .mf, .codehilite .mh,
.codehilite .mi, .codehilite .mo {{ color: #0550ae; }}
.codehilite .s, .codehilite .sa, .codehilite .sb, .codehilite .sc, .codehilite .dl,
.codehilite .sd, .codehilite .s2, .codehilite .se, .codehilite .sh, .codehilite .si,
.codehilite .sx, .codehilite .sr, .codehilite .s1, .codehilite .ss {{ color: #0a3069; }}
.codehilite .nf, .codehilite .fm {{ color: #8250df; }}
.codehilite .nc, .codehilite .nn {{ color: #953800; }}
.codehilite .nb, .codehilite .bp {{ color: #0550ae; }}
.codehilite .nd {{ color: #8250df; }}
.codehilite .ne {{ color: #cf222e; }}
.codehilite .n, .codehilite .na, .codehilite .ni, .codehilite .nl, .codehilite .nt,
.codehilite .nv, .codehilite .vc, .codehilite .vg, .codehilite .vi,
.codehilite .vm {{ color: #24292f; }}
.codehilite .err {{ color: #82071e; background: #ffebe9; }}
.codehilite .p {{ color: #24292f; }}
.codehilite .w {{ color: transparent; }}
.empty {{ color: #888; text-align: center; margin-top: 80px; }}
@media (max-width: 768px) {{
body {{ flex-direction: column; height: auto; overflow: auto; }}
#sidebar {{ width: 100%; height: auto; max-height: 45vh; position: relative; }}
#content {{ height: auto; overflow: visible; padding: 16px; }}
}}
</style>
</head>
<body>
<nav id="sidebar">
<h2>📚 我的笔记</h2>
{nav}
</nav>
<main id="content">
<div id="content-inner">
<article class="markdown-body">{content}</article>
</div>
</main>
<script>
function scrollToHeading(id) {{
var el = document.getElementById(id);
if (!el) return false;
var container = document.getElementById('content');
var isScrollable = container &&
container.scrollHeight > container.clientHeight &&
getComputedStyle(container).overflowY !== 'visible';
if (isScrollable) {{
var offset = el.getBoundingClientRect().top
- container.getBoundingClientRect().top
+ container.scrollTop;
container.scrollTo({{ top: Math.max(0, offset - 16), behavior: 'smooth' }});
}} else {{
el.scrollIntoView({{ behavior: 'smooth', block: 'start' }});
}}
return true;
}}
document.querySelectorAll('.toc-wrap a').forEach(function (a) {{
a.addEventListener('click', function (e) {{
var href = a.getAttribute('href') || '';
if (href.charAt(0) !== '#') return;
var id = decodeURIComponent(href.slice(1));
if (scrollToHeading(id)) {{
e.preventDefault();
history.replaceState(null, '', href);
document.querySelectorAll('.toc-wrap a').forEach(function (x) {{
x.classList.remove('active');
}});
a.classList.add('active');
}}
}});
}});
(function () {{
if (location.hash) {{
var id = decodeURIComponent(location.hash.slice(1));
setTimeout(function () {{ scrollToHeading(id); }}, 50);
}}
}})();
</script>
</body>
</html>
"""
# ============================================================
# 笔记服务
# ============================================================
def list_notes():
notes = []
for root, dirs, files in os.walk(NOTES_DIR):
dirs[:] = [d for d in dirs if not d.startswith(".")]
for f in files:
if f.startswith("."):
continue
if f.lower().endswith(".md"):
full = os.path.join(root, f)
rel = os.path.relpath(full, NOTES_DIR).replace(os.sep, "/")
notes.append(rel)
notes.sort()
return notes
def get_note_title(rel_path, md_text=None):
return os.path.basename(rel_path)[:-3]
def _slugify(value, separator):
value = re.sub(r"[^\w\u4e00-\u9fff\- ]+", "", value, flags=re.U).strip().lower()
value = re.sub(r"[{0}\s]+".format(re.escape(separator)), separator, value)
return value or "section"
def render_md_with_toc(text):
md = markdown.Markdown(
extensions=[
"extra",
"fenced_code",
"nl2br",
"codehilite",
TocExtension(
toc_depth="1-6",
anchorlink=False,
permalink=False,
slugify=lambda value, separator: _slugify(value, separator),
),
],
extension_configs={
"codehilite": {
"guess_lang": True,
"css_class": "codehilite",
"linenums": False,
"use_pygments": True,
}
},
)
body = md.convert(text)
toc = md.toc or ""
return body, toc
def read_file(path):
with open(path, "r", encoding="utf-8") as f:
return f.read()
def render_nav(notes, current_file, current_toc=""):
groups = []
for n in notes:
note_title = get_note_title(n)
is_current = (n == current_file)
active_cls = " active" if is_current else ""
href = "/?file=" + quote(n)
parts = [
'<div class="note-group">',
f'<a class="note-title{active_cls}" '
f'href="{html.escape(href, quote=True)}">{html.escape(note_title)}</a>',
]
if is_current and current_toc:
parts.append('<div class="toc-wrap">')
parts.append(current_toc)
parts.append('</div>')
parts.append('</div>')
groups.append("\n".join(parts))
return "\n".join(groups)
def safe_join(base, rel):
target = os.path.abspath(os.path.join(base, rel))
if target == base or target.startswith(base + os.sep):
return target
return None
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
raw_path = self.path.split("?", 1)[0]
raw_path = unquote(raw_path).lstrip("/")
if raw_path:
target = safe_join(NOTES_DIR, raw_path)
if target and os.path.isfile(target):
ext = os.path.splitext(target)[1].lower()
if ext not in ALLOWED_EXT:
self.send_error(403, "Forbidden")
return
self.serve_file(target)
return
self.serve_page()
def serve_file(self, path):
ctype, _ = mimetypes.guess_type(path)
if ctype is None:
ctype = "application/octet-stream"
try:
with open(path, "rb") as f:
data = f.read()
except Exception:
self.send_error(404, "File not found")
return
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-cache, must-revalidate")
self.end_headers()
self.wfile.write(data)
def serve_page(self):
query = ""
if "?" in self.path:
query = self.path.split("?", 1)[1]
params = {}
for part in query.split("&"):
if "=" in part:
k, v = part.split("=", 1)
params[k] = unquote(v)
notes = list_notes()
file_param = params.get("file", "")
if not file_param and notes:
file_param = notes[0]
content_html = ""
current_toc = ""
title = "我的笔记"
if file_param:
target = safe_join(NOTES_DIR, file_param)
if not target or not os.path.isfile(target):
content_html = '<p class="empty">❌ 笔记不存在</p>'
else:
try:
raw = read_file(target)
content_html, current_toc = render_md_with_toc(raw)
title = get_note_title(file_param)
except Exception as e:
content_html = f'<p class="empty">读取失败:{html.escape(str(e))}</p>'
else:
content_html = '<p class="empty">📭 还没有笔记,把 .md 文件放进 notes 目录吧</p>'
nav = render_nav(notes, file_param, current_toc)
page = PAGE_TEMPLATE.format(
title=html.escape(title),
nav=nav,
content=content_html,
)
data = page.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
self.send_header("Pragma", "no-cache")
self.send_header("Expires", "0")
self.end_headers()
self.wfile.write(data)
def log_message(self, fmt, *args):
# 本地请求日志保留,方便确认访问是否到达
print(f"[本地] {self.address_string()} {fmt % args}")
# ============================================================
# cloudflared 智能获取
# ============================================================
def _is_valid_binary(path):
if not os.path.isfile(path):
return False
size = os.path.getsize(path)
system = platform.system()
if system == "Windows":
if size < 20 * 1024 * 1024:
return False
try:
with open(path, "rb") as f:
head = f.read(2)
return head == b"MZ"
except Exception:
return False
elif system == "Darwin":
if size < 10 * 1024 * 1024:
return False
try:
with open(path, "rb") as f:
head = f.read(4)
return head[:1] != b"<"
except Exception:
return False
else:
if size < 10 * 1024 * 1024:
return False
try:
with open(path, "rb") as f:
head = f.read(4)
return head == b"\x7fELF"
except Exception:
return False
def _candidate_urls():
system = platform.system().lower()
machine = platform.machine().lower()
mirrors = [
"",
"https://ghproxy.net/",
"https://gh-proxy.com/",
"https://mirror.ghproxy.com/",
"https://ghfast.top/",
]
if system == "windows":
name = "cloudflared.exe"
if "64" in machine or "amd" in machine:
path = "cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe"
else:
path = "cloudflare/cloudflared/releases/latest/download/cloudflared-windows-386.exe"
elif system == "darwin":
name = "cloudflared.tgz"
path = "cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-amd64.tgz"
else:
arch = "amd64" if "64" in machine else ("arm64" if "arm" in machine else "386")
name = "cloudflared"
path = f"cloudflare/cloudflared/releases/latest/download/cloudflared-linux-{arch}"
urls = []
for m in mirrors:
urls.append(m + "https://github.com/" + path)
return name, urls
def _download_one(url, dst):
print(f"⬇️ 尝试下载: {url}")
try:
req = urllib.request.Request(url, headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
})
with urllib.request.urlopen(req, timeout=90) as r, open(dst, "wb") as f:
total = int(r.headers.get("Content-Length") or 0)
got = 0
last_pct = -1
while True:
chunk = r.read(1024 * 256)
if not chunk:
break
f.write(chunk)
got += len(chunk)
if total:
pct = got * 100 // total
if pct != last_pct and pct % 5 == 0:
print(f" {pct}% ({got // 1024} KB)", flush=True)
last_pct = pct
print(f" 下载完成: {os.path.getsize(dst) // 1024} KB")
return True
except Exception as e:
print(f" ⚠️ 失败: {e}")
try:
if os.path.exists(dst):
os.remove(dst)
except Exception:
pass
return False
def _extract_tgz_if_needed(path, name):
if name.endswith(".tgz"):
try:
with tarfile.open(path) as t:
t.extractall(os.path.dirname(path))
os.remove(path)
p = os.path.join(os.path.dirname(path), "cloudflared")
st = os.stat(p)
os.chmod(p, st.st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
return p
except Exception as e:
print(f"⚠️ 解压失败: {e}")
return None
if not name.endswith(".exe"):
st = os.stat(path)
os.chmod(path, st.st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
return path
def ensure_cloudflared():
name, urls = _candidate_urls()
dst = os.path.join(HERE, name)
if _is_valid_binary(dst):
print(f"✅ 已找到有效的 cloudflared: {dst}")
return dst
if os.path.exists(dst):
size = os.path.getsize(dst)
print(f"⚠️ 发现已有 cloudflared,但校验失败({size} 字节),将删除重下")
try:
os.remove(dst)
except Exception as e:
print(f"❌ 无法删除旧文件:{e}")
print(f" 请手动删除:{dst}")
sys.exit(1)
p = shutil.which("cloudflared")
if p and _is_valid_binary(p):
print(f"✅ 在 PATH 中找到 cloudflared: {p}")
return p
for url in urls:
if _download_one(url, dst):
if _is_valid_binary(dst):
print("✅ 下载完成且校验通过")
result = _extract_tgz_if_needed(dst, name)
if result:
return result
else:
print("❌ 下载到的文件校验失败(可能是 HTML 错误页)")
try:
os.remove(dst)
except Exception:
pass
print("\n" + "=" * 60)
print("❌ 所有下载源都失败。请手动处理:")
print("=" * 60)
print("1. 用浏览器打开下面任一直达链接下载:")
print(" https://ghproxy.net/https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe")
print(" https://gh-proxy.com/https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe")
print(" https://mirror.ghproxy.com/https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe")
print()
print("2. 下载后确认大小约 30-40 MB,改名为 cloudflared.exe")
print(f"3. 放到这个目录:{HERE}")
print("4. 重新运行本脚本")
print("=" * 60)
sys.exit(1)
# ============================================================
# 隧道
# ============================================================
URL_RE = re.compile(r"https://[a-z0-9\-]+\.trycloudflare\.com")
ADDR_FILE = os.path.join(HERE, "当前地址.txt")
def _kill_leftover_cloudflared():
"""启动前清理残留的 cloudflared 进程(仅 Windows)"""
if platform.system() != "Windows":
return
try:
subprocess.run(
["taskkill", "/IM", "cloudflared.exe", "/F"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=5,
)
print("🧹 已清理可能残留的 cloudflared 进程")
except Exception:
pass
def start_tunnel(cloudflared_path):
print("🚇 正在建立 Cloudflare 隧道...")
cmd = [
cloudflared_path, "tunnel",
"--no-autoupdate",
"--url", f"http://127.0.0.1:{LOCAL_PORT}",
]
try:
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
encoding="utf-8",
errors="ignore",
)
except OSError as e:
print(f"❌ 启动 cloudflared 失败: {e}")
print(f" 路径: {cloudflared_path}")
sys.exit(1)
found = {"url": None}
def reader():
for line in proc.stdout:
line = line.rstrip()
# 只打印错误行,其余 INFO 全部忽略
if " ERR " in line or line.startswith("ERR"):
print(f"[cf错误] {line}")
m = URL_RE.search(line)
if m and not found["url"]:
found["url"] = m.group(0)
try:
with open(ADDR_FILE, "w", encoding="utf-8") as f:
f.write(found["url"] + "\n")
except Exception:
pass
print("\n" + "=" * 60)
print(f"🌍 公网地址: {found['url']}")
print(f" 已保存到: {ADDR_FILE}")
print("=" * 60)
print("把这个链接发到手机/任何设备就能打开笔记。")
print("按 Ctrl+C 停止服务。\n")
threading.Thread(target=reader, daemon=True).start()
for _ in range(60):
if found["url"]:
break
time.sleep(0.5)
if not found["url"]:
print("⚠️ 30 秒内未获取到公网地址,可能网络受限。")
return proc
# ============================================================
# 主流程
# ============================================================
def get_local_ip():
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
except Exception:
ip = "127.0.0.1"
finally:
s.close()
return ip
def main():
_kill_leftover_cloudflared()
try:
import pygments # noqa
except ImportError:
print("❌ 缺少依赖,请先运行:pip install markdown pygments")
sys.exit(1)
if not os.path.isdir(NOTES_DIR):
os.makedirs(NOTES_DIR)
print(f"已创建笔记目录:{NOTES_DIR}")
ip = get_local_ip()
print("=" * 60)
print("📖 Markdown 笔记服务(一键公网版)")
print("=" * 60)
print(f" 本机访问: http://127.0.0.1:{LOCAL_PORT}")
print(f" 内网访问: http://{ip}:{LOCAL_PORT}")
print("=" * 60)
# 1. 本地服务
server = HTTPServer(("127.0.0.1", LOCAL_PORT), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
print(f"✅ 笔记服务已启动: http://127.0.0.1:{LOCAL_PORT}")
# 2. cloudflared
cloudflared = ensure_cloudflared()
# 3. 隧道
proc = start_tunnel(cloudflared)
# 4. 挂着
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\n正在停止...")
try:
proc.terminate()
except Exception:
pass
try:
server.shutdown()
except Exception:
pass
print("已停止。")
if __name__ == "__main__":
main()