|
| 1 | +"""SSH 运维接口:主机/片段管理、终端会话(POST 轮询)、批量执行、日志跟踪。""" |
| 2 | + |
| 3 | +import base64 |
| 4 | +from datetime import UTC, datetime |
| 5 | +from typing import Annotated |
| 6 | + |
| 7 | +from fastapi import APIRouter, Body, Depends, Path, Query, Security, status |
| 8 | +from fastapi.responses import JSONResponse |
| 9 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 10 | + |
| 11 | +from app.common.response import ResponseSchema, SuccessResponse |
| 12 | +from app.core.base_schema import AuthSchema |
| 13 | +from app.core.dependencies import AuthPermission, db_getter |
| 14 | +from app.core.router_class import OperationLogRoute |
| 15 | + |
| 16 | +from .schema import ( |
| 17 | + BatchExecResultSchema, |
| 18 | + BatchExecSchema, |
| 19 | + SshHostCreateSchema, |
| 20 | + SshHostOutSchema, |
| 21 | + SshHostTestSchema, |
| 22 | + SshHostUpdateSchema, |
| 23 | + SshSnippetCreateSchema, |
| 24 | + SshSnippetOutSchema, |
| 25 | + SshSnippetUpdateSchema, |
| 26 | + TerminalInputSchema, |
| 27 | + TerminalLogOpenSchema, |
| 28 | + TerminalOpenSchema, |
| 29 | + TerminalPollSchema, |
| 30 | + TerminalResizeSchema, |
| 31 | + TerminalSessionSchema, |
| 32 | +) |
| 33 | +from .service import SshHostService, SshSnippetService |
| 34 | +from .terminal import TerminalManager |
| 35 | + |
| 36 | +SshRouter = APIRouter(route_class=OperationLogRoute, prefix="/ssh", tags=["SSH运维"]) |
| 37 | + |
| 38 | +_QUERY = "module_ops:ssh:query" |
| 39 | +_TERMINAL = "module_ops:ssh:terminal" |
| 40 | +_EXEC = "module_ops:ssh:exec" |
| 41 | + |
| 42 | + |
| 43 | +def _session_schema(session) -> TerminalSessionSchema: |
| 44 | + return TerminalSessionSchema( |
| 45 | + session_id=session.session_id, |
| 46 | + host_id=session.host_id, |
| 47 | + host_name=session.host_name, |
| 48 | + cols=session.cols, |
| 49 | + rows=session.rows, |
| 50 | + created_at=datetime.fromtimestamp(session.created_at, tz=UTC).isoformat(timespec="seconds"), |
| 51 | + ) |
| 52 | + |
| 53 | + |
| 54 | +# ── 主机管理 ────────────────────────────────────────────────────────── |
| 55 | + |
| 56 | + |
| 57 | +@SshRouter.get("/host/list", summary="查询 SSH 主机列表", response_model=ResponseSchema[list[SshHostOutSchema]]) |
| 58 | +async def list_ssh_host_controller( |
| 59 | + auth: Annotated[AuthSchema, Security(AuthPermission([_QUERY]))], |
| 60 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 61 | +) -> JSONResponse: |
| 62 | + result = await SshHostService(auth, db).get_list() |
| 63 | + return SuccessResponse(data=result, msg="查询主机列表成功") |
| 64 | + |
| 65 | + |
| 66 | +@SshRouter.get("/host/detail/{id}", summary="查询 SSH 主机详情", response_model=ResponseSchema[SshHostOutSchema]) |
| 67 | +async def detail_ssh_host_controller( |
| 68 | + auth: Annotated[AuthSchema, Security(AuthPermission([_QUERY]))], |
| 69 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 70 | + id: Annotated[int, Path(description="主机ID", ge=1)], |
| 71 | +) -> JSONResponse: |
| 72 | + result = await SshHostService(auth, db).detail(id=id) |
| 73 | + return SuccessResponse(data=result, msg="查询主机详情成功") |
| 74 | + |
| 75 | + |
| 76 | +@SshRouter.post("/host/create", status_code=status.HTTP_201_CREATED, summary="新增 SSH 主机", response_model=ResponseSchema[SshHostOutSchema]) |
| 77 | +async def create_ssh_host_controller( |
| 78 | + auth: Annotated[AuthSchema, Security(AuthPermission(["module_ops:ssh:create"]))], |
| 79 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 80 | + data: Annotated[SshHostCreateSchema, Body(description="主机配置(密码/私钥加密存储)")], |
| 81 | +) -> JSONResponse: |
| 82 | + result = await SshHostService(auth, db).create(data=data) |
| 83 | + return SuccessResponse(data=result, msg="新增主机成功") |
| 84 | + |
| 85 | + |
| 86 | +@SshRouter.put("/host/update/{id}", summary="修改 SSH 主机", response_model=ResponseSchema[SshHostOutSchema]) |
| 87 | +async def update_ssh_host_controller( |
| 88 | + auth: Annotated[AuthSchema, Security(AuthPermission(["module_ops:ssh:update"]))], |
| 89 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 90 | + id: Annotated[int, Path(description="主机ID", ge=1)], |
| 91 | + data: Annotated[SshHostUpdateSchema, Body(description="主机配置(凭据不传表示不修改)")], |
| 92 | +) -> JSONResponse: |
| 93 | + result = await SshHostService(auth, db).update(id=id, data=data) |
| 94 | + return SuccessResponse(data=result, msg="修改主机成功") |
| 95 | + |
| 96 | + |
| 97 | +@SshRouter.delete("/host/delete", summary="删除 SSH 主机", response_model=ResponseSchema[None]) |
| 98 | +async def delete_ssh_host_controller( |
| 99 | + auth: Annotated[AuthSchema, Security(AuthPermission(["module_ops:ssh:delete"]))], |
| 100 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 101 | + ids: Annotated[list[int], Body(description="主机ID列表")], |
| 102 | +) -> JSONResponse: |
| 103 | + await SshHostService(auth, db).delete(ids=ids) |
| 104 | + return SuccessResponse(msg="删除主机成功") |
| 105 | + |
| 106 | + |
| 107 | +@SshRouter.post("/host/test", summary="按填写中的凭据测试 SSH 连接(不落库)", response_model=ResponseSchema[bool]) |
| 108 | +async def test_ssh_host_config_controller( |
| 109 | + auth: Annotated[AuthSchema, Security(AuthPermission(["module_ops:ssh:update"]))], |
| 110 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 111 | + data: Annotated[SshHostTestSchema, Body(description="连接配置")], |
| 112 | +) -> JSONResponse: |
| 113 | + result = await SshHostService(auth, db).test_connection(data) |
| 114 | + return SuccessResponse(data=result, msg="连接成功") |
| 115 | + |
| 116 | + |
| 117 | +@SshRouter.post("/host/test/{id}", summary="测试已保存的 SSH 主机", response_model=ResponseSchema[bool]) |
| 118 | +async def test_ssh_host_controller( |
| 119 | + auth: Annotated[AuthSchema, Security(AuthPermission([_QUERY]))], |
| 120 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 121 | + id: Annotated[int, Path(description="主机ID", ge=1)], |
| 122 | +) -> JSONResponse: |
| 123 | + result = await SshHostService(auth, db).test_by_id(id=id) |
| 124 | + return SuccessResponse(data=result, msg="连接成功") |
| 125 | + |
| 126 | + |
| 127 | +# ── 命令片段 ────────────────────────────────────────────────────────── |
| 128 | + |
| 129 | + |
| 130 | +@SshRouter.get("/snippet/list", summary="查询命令片段列表", response_model=ResponseSchema[list[SshSnippetOutSchema]]) |
| 131 | +async def list_ssh_snippet_controller( |
| 132 | + auth: Annotated[AuthSchema, Security(AuthPermission(["module_ops:snippet:query"]))], |
| 133 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 134 | +) -> JSONResponse: |
| 135 | + result = await SshSnippetService(auth, db).get_list() |
| 136 | + return SuccessResponse(data=result, msg="查询片段列表成功") |
| 137 | + |
| 138 | + |
| 139 | +@SshRouter.post("/snippet/create", status_code=status.HTTP_201_CREATED, summary="新增命令片段", response_model=ResponseSchema[SshSnippetOutSchema]) |
| 140 | +async def create_ssh_snippet_controller( |
| 141 | + auth: Annotated[AuthSchema, Security(AuthPermission(["module_ops:snippet:create"]))], |
| 142 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 143 | + data: Annotated[SshSnippetCreateSchema, Body(description="片段内容")], |
| 144 | +) -> JSONResponse: |
| 145 | + result = await SshSnippetService(auth, db).create(data=data) |
| 146 | + return SuccessResponse(data=result, msg="新增片段成功") |
| 147 | + |
| 148 | + |
| 149 | +@SshRouter.put("/snippet/update/{id}", summary="修改命令片段", response_model=ResponseSchema[SshSnippetOutSchema]) |
| 150 | +async def update_ssh_snippet_controller( |
| 151 | + auth: Annotated[AuthSchema, Security(AuthPermission(["module_ops:snippet:update"]))], |
| 152 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 153 | + id: Annotated[int, Path(description="片段ID", ge=1)], |
| 154 | + data: Annotated[SshSnippetUpdateSchema, Body(description="片段内容")], |
| 155 | +) -> JSONResponse: |
| 156 | + result = await SshSnippetService(auth, db).update(id=id, data=data) |
| 157 | + return SuccessResponse(data=result, msg="修改片段成功") |
| 158 | + |
| 159 | + |
| 160 | +@SshRouter.delete("/snippet/delete", summary="删除命令片段", response_model=ResponseSchema[None]) |
| 161 | +async def delete_ssh_snippet_controller( |
| 162 | + auth: Annotated[AuthSchema, Security(AuthPermission(["module_ops:snippet:delete"]))], |
| 163 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 164 | + ids: Annotated[list[int], Body(description="片段ID列表")], |
| 165 | +) -> JSONResponse: |
| 166 | + await SshSnippetService(auth, db).delete(ids=ids) |
| 167 | + return SuccessResponse(msg="删除片段成功") |
| 168 | + |
| 169 | + |
| 170 | +# ── 终端会话(POST 轮询)───────────────────────────────────────────── |
| 171 | + |
| 172 | + |
| 173 | +@SshRouter.post("/terminal/open", summary="打开终端会话", response_model=ResponseSchema[TerminalSessionSchema]) |
| 174 | +async def open_terminal_controller( |
| 175 | + auth: Annotated[AuthSchema, Security(AuthPermission([_TERMINAL]))], |
| 176 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 177 | + data: Annotated[TerminalOpenSchema, Body(description="主机与终端尺寸")], |
| 178 | +) -> JSONResponse: |
| 179 | + session = await SshHostService(auth, db).open_terminal(host_id=data.host_id, cols=data.cols, rows=data.rows) |
| 180 | + return SuccessResponse(data=_session_schema(session), msg="终端会话已打开") |
| 181 | + |
| 182 | + |
| 183 | +@SshRouter.post("/log/open", summary="打开日志跟踪会话(tail -F)", response_model=ResponseSchema[TerminalSessionSchema]) |
| 184 | +async def open_log_controller( |
| 185 | + auth: Annotated[AuthSchema, Security(AuthPermission([_TERMINAL]))], |
| 186 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 187 | + data: Annotated[TerminalLogOpenSchema, Body(description="主机与日志路径")], |
| 188 | +) -> JSONResponse: |
| 189 | + session = await SshHostService(auth, db).open_log_tail(host_id=data.host_id, path=data.path, lines=data.lines) |
| 190 | + return SuccessResponse(data=_session_schema(session), msg="日志跟踪会话已打开") |
| 191 | + |
| 192 | + |
| 193 | +@SshRouter.get("/terminal/{session_id}/poll", summary="轮询终端输出(长轮询)", response_model=ResponseSchema[TerminalPollSchema]) |
| 194 | +async def poll_terminal_controller( |
| 195 | + auth: Annotated[AuthSchema, Security(AuthPermission([_TERMINAL]))], |
| 196 | + session_id: Annotated[str, Path(min_length=8, max_length=64, description="会话ID")], |
| 197 | + timeout: Annotated[float, Query(ge=0, le=5, description="长轮询等待秒数")] = 2.0, |
| 198 | +) -> JSONResponse: |
| 199 | + data, closed, exit_status = TerminalManager.poll(session_id, auth.user.id or 0, timeout) |
| 200 | + return SuccessResponse( |
| 201 | + data=TerminalPollSchema( |
| 202 | + data=base64.b64encode(data).decode() if data else "", |
| 203 | + closed=closed, |
| 204 | + exit_status=exit_status, |
| 205 | + ), |
| 206 | + msg="轮询成功", |
| 207 | + ) |
| 208 | + |
| 209 | + |
| 210 | +@SshRouter.post("/terminal/{session_id}/input", summary="终端输入(base64)", response_model=ResponseSchema[None]) |
| 211 | +async def input_terminal_controller( |
| 212 | + auth: Annotated[AuthSchema, Security(AuthPermission([_TERMINAL]))], |
| 213 | + session_id: Annotated[str, Path(min_length=8, max_length=64)], |
| 214 | + data: Annotated[TerminalInputSchema, Body(description="base64 输入")], |
| 215 | +) -> JSONResponse: |
| 216 | + try: |
| 217 | + raw = base64.b64decode(data.data, validate=True) |
| 218 | + except ValueError as exc: # binascii.Error 是 ValueError 子类:base64 非法 |
| 219 | + from app.core.exceptions import CustomException |
| 220 | + |
| 221 | + raise CustomException(msg="输入内容不是合法的 base64") from exc |
| 222 | + TerminalManager.write(session_id, auth.user.id or 0, raw) |
| 223 | + return SuccessResponse(msg="输入成功") |
| 224 | + |
| 225 | + |
| 226 | +@SshRouter.post("/terminal/{session_id}/resync", summary="重同步会话(清空积压输出)", response_model=ResponseSchema[None]) |
| 227 | +async def resync_terminal_controller( |
| 228 | + auth: Annotated[AuthSchema, Security(AuthPermission([_TERMINAL]))], |
| 229 | + session_id: Annotated[str, Path(min_length=8, max_length=64)], |
| 230 | +) -> JSONResponse: |
| 231 | + TerminalManager.poll(session_id, auth.user.id or 0, 0) |
| 232 | + return SuccessResponse(msg="已重同步") |
| 233 | + |
| 234 | + |
| 235 | +@SshRouter.post("/terminal/{session_id}/resize", summary="同步终端尺寸", response_model=ResponseSchema[None]) |
| 236 | +async def resize_terminal_controller( |
| 237 | + auth: Annotated[AuthSchema, Security(AuthPermission([_TERMINAL]))], |
| 238 | + session_id: Annotated[str, Path(min_length=8, max_length=64)], |
| 239 | + data: Annotated[TerminalResizeSchema, Body(description="列/行")], |
| 240 | +) -> JSONResponse: |
| 241 | + TerminalManager.resize(session_id, auth.user.id or 0, data.cols, data.rows) |
| 242 | + return SuccessResponse(msg="尺寸已同步") |
| 243 | + |
| 244 | + |
| 245 | +@SshRouter.delete("/terminal/{session_id}", summary="关闭终端会话", response_model=ResponseSchema[None]) |
| 246 | +async def close_terminal_controller( |
| 247 | + auth: Annotated[AuthSchema, Security(AuthPermission([_TERMINAL]))], |
| 248 | + session_id: Annotated[str, Path(min_length=8, max_length=64)], |
| 249 | +) -> JSONResponse: |
| 250 | + TerminalManager.close(session_id, auth.user.id or 0) |
| 251 | + return SuccessResponse(msg="终端会话已关闭") |
| 252 | + |
| 253 | + |
| 254 | +# ── 批量执行 ────────────────────────────────────────────────────────── |
| 255 | + |
| 256 | + |
| 257 | +@SshRouter.post("/batch-exec", summary="多主机批量执行命令", response_model=ResponseSchema[list[BatchExecResultSchema]]) |
| 258 | +async def batch_exec_controller( |
| 259 | + auth: Annotated[AuthSchema, Security(AuthPermission([_EXEC]))], |
| 260 | + db: Annotated[AsyncSession, Depends(db_getter)], |
| 261 | + data: Annotated[BatchExecSchema, Body(description="主机列表与命令")], |
| 262 | +) -> JSONResponse: |
| 263 | + results = await SshHostService(auth, db).batch_execute( |
| 264 | + host_ids=data.host_ids, command=data.command, timeout=data.timeout |
| 265 | + ) |
| 266 | + return SuccessResponse(data=results, msg="批量执行完成") |
0 commit comments