步骤

  • SSH登录到VPS

  • 运行 sudo -i 获取权限

  • 更新和升级系统

apt update && apt upgrade -y
  • 如果没有安装过 Python3 的话要安装

    • 安装 Python3 和 pip 包管理器

      • 运行以下命令安装 Python3 和 pip 包管理器。
sudo apt install python3 python3-pip
* 安装依赖包
pip3 install psutil
    * 在后面运行 py 程序的时候,如果遇到缺少的依赖包,会有相应的提示:ModuleNotFoundError: No module named xxxx  这时候通过上面的 pip3 install xxxx 进行相应的依赖包安装即可解决。
  • 编写运行程序

    • vim /root/servertraffic.py
#!/usr/bin/env python3
# Sestea
 
import http.server
import socketserver
import json
import time
import psutil
 
# The port number of the local HTTP server, which can be modified
port = 7122
 
class RequestHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
 
        # Limit the HTTP server to one request per second
        time.sleep(1)
 
        # Obtain CPU/MEM usage and network traffic info
        cpu_usage = psutil.cpu_percent()
        mem_usage = psutil.virtual_memory().percent
        bytes_sent = psutil.net_io_counters().bytes_sent
        bytes_recv = psutil.net_io_counters().bytes_recv
        bytes_total = bytes_sent + bytes_recv
 
        # Get UTC timestamp and uptime
        utc_timestamp = int(time.time())
        uptime = int(time.time() - psutil.boot_time())
 
        # Get the last statistics time
        last_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
 
        # Construct JSON dictionary
        response_dict = {
            "utc_timestamp": utc_timestamp,
            "uptime": uptime,
            "cpu_usage": cpu_usage,
            "mem_usage": mem_usage,
            "bytes_sent": str(bytes_sent),
            "bytes_recv": str(bytes_recv),
            "bytes_total": str(bytes_total),
            "last_time": last_time
        }
 
        # Convert JSON dictionary to JSON string
        response_json = json.dumps(response_dict).encode('utf-8')
        self.wfile.write(response_json)
 
with socketserver.ThreadingTCPServer(("", port), RequestHandler) as httpd:
    try:
        print(f"Serving at port {port}")
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("KeyboardInterrupt is captured, program exited")
    * **说明:此代码是通过VPS的7122端口进行监控,请确保该端口的开放,如果你熟悉代码,也可以根据自己需要进行修改。**

* 编写服务

    * `vim /etc/systemd/system/servertraffic.service`
[Unit]
Description=Server Traffic Monitor

[Service]
Type=simple
WorkingDirectory=/root/
User=root
ExecStart=/usr/bin/python3 /root/servertraffic.py
Restart=always

[Install]
WantedBy=multi-user.target
  • 运行

    • 启动并激活这个服务:

      • sudo systemctl start servertraffic.service

      • sudo systemctl enable servertraffic.service

    • 查看服务状态以确保它已经运行:

      • sudo systemctl status servertraffic.service
    • 这样就可以在后台运行 /root/servertraffic.py 了。请按照自己实际情况修改服务单元文件中的相关配置,比如 User 和 WorkingDirectory。

Surge模块安装

将下面内容复制到本地模块中:

#!name=CatVPS
#!desc=监控VPS流量信息和处理器、内存占用情况
#!author= 面板和脚本部分@Sestea @clydetime  VPS端部分 @Sestea 由 @整点猫咪 进行整理
#!howto=将模块内容复制到本地后根据自己VPS IP地址及端口修改 http://127.0.0.1:7122

[Panel]
Serverinfo = script-name= Serverinfo,update-interval=3600

[Script]
Serverinfo = type=generic,script-path=https://raw.githubusercontent.com/getsomecat/GetSomeCats/Surge/script/serverinfo.js, argument = url=http://127.0.0.1:7122&name=Server Info&icon=party.popper

将其中的 http://127.0.0.1:7122部分根据自己上面教程部分改为自己的VPS IP和端口即可使用。

Reference