公网开放一个获取用户当前IP的服务

自用,用于动态客户端获取当前IP,向服务器报告IP地址,并出发DNS解析和内网穿透的后续操作。

将脚本注册成linux服务,脚本启动一个python程序。
脚本权限设置为可执行。
在/usr/lib/systemd/system/下增加服务描述脚本,例如/usr/lib/systemd/system/getip.service
内容如下:

[Unit]
Description=getclientip
After=network.target
[Service]
Type=simple
User=root
ExecStart=/root/fix/getip.sh
Restart=on-failure
PrivateTmp=true
[Install]
WantedBy=multi-user.target

刷新服务,systemctl daemon-reload
注册开机启动,systemctl enable getip
启动服务,systemctl start getip

python代码如下:

# coding:utf-8
from fastapi import FastAPI, Request,WebSocket
from fastapi.responses import PlainTextResponse
from datetime import datetime
import uvicorn

app = FastAPI()

@app.get("/",response_class=PlainTextResponse)
async def get_client_ip(request: Request):
    client_ip = request.client.host
    return client_ip

@app.get("/log/{log_class}/{error_level}/{message}")
async def log_via_http(log_class: str, error_level: str, message: str):
    log_entry = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [{log_class}] [{error_level}] {message}\n"
    with open("log.txt", "a", encoding="utf-8") as log_file:
        log_file.write(log_entry)
    return {"message": "Logged via HTTP"}


@app.websocket("/ws/log")
async def log_via_websocket(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        log_data = eval(
            data
        )  # Using eval for simplicity, consider safer alternatives in production
        log_entry = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [{log_data['log']['class']}] [{log_data['log']['errorlevel']}] {log_data['log']['message']}\n"
        with open("log.txt", "a", encoding="utf-8") as log_file:
            log_file.write(log_entry)
        await websocket.send_text("Logged via WebSocket")


if __name__ == "__main__":
    # 使用uvicorn启动服务器,监听在0.0.0.0的8000端口
    uvicorn.run(app, host="0.0.0.0", port=8000)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注