learn-spider/app.py

96 lines
3.0 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from fastmcp import FastMCP
from spider.mail_qq import start as a1
import asyncio
import logging
import json
mcp = FastMCP("spider-server")
logging.basicConfig(level=logging.INFO)
# 日志会输出到 stderr不会污染 stdout
logging.info("服务器启动")
# @mcp.tool()
def mail_qq_spider(account: str) -> str:
"""qq邮箱爬虫,第一个参数是用户名"""
return a1(account)
@mcp.tool()
async def start_vnc_server(index: int) -> str:
"""启动VNC服务
Args:
index: VNC 显示编号
"""
try:
# 调用外部 start_vnc_server.sh 脚本,传入 index 作为参数
process = await asyncio.create_subprocess_exec(
"/home/dgs/vnc-server/start_vnc_server.sh",
str(index),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode == 0:
return f"✅ VNC服务启动成功\n输出:\n{stdout.decode()}"
else:
return f"❌ VNC服务启动失败\n错误:\n{stderr.decode()}"
except Exception as e:
return f"❌ 执行出错: {str(e)}"
@mcp.tool()
async def start_spider(spider_code: str) -> str:
"""启动爬虫
Args:
spider_code: 爬虫代码
"""
try:
# 调用外部 start_spider.sh 脚本,传入 spider_code 作为参数
process = await asyncio.create_subprocess_exec(
"/home/dgs/vnc-server/start_spider.sh",
spider_code,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode == 0:
return f"✅ 爬虫启动成功\n输出:\n{stdout.decode()}"
else:
return f"❌ 爬虫启动失败\n错误:\n{stderr.decode()}"
except Exception as e:
return f"❌ 执行出错: {str(e)}"
@mcp.tool()
async def close_vnc_server(index: int) -> str:
"""关闭 VNC 服务
Args:
index: VNC 显示编号
"""
try:
# 调用外部 stop_vnc_server.sh 脚本,传入 index 作为参数
process = await asyncio.create_subprocess_exec(
"/home/dgs/vnc-server/stop_vnc_server.sh",
str(index),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode == 0:
return f"✅ VNC服务关闭成功\n输出:\n{stdout.decode()}"
else:
return f"❌ VNC服务关闭失败\n错误:\n{stderr.decode()}"
except Exception as e:
return f"❌ 执行出错: {str(e)}"
@mcp.resource("data://spider_code")
def get_spider_code_list() -> str:
spider_list = [
{"code": "01","name": "阳光采购爬虫"},
{"code": "02","name": "QQ邮箱爬虫"},
]
return json.dumps(spider_list, ensure_ascii=False)
# 运行服务器
if __name__ == "__main__":
mcp.run(transport="sse")
# mcp.run(transport="stdio")