以下是一个获取服务器的CPU、内存、磁盘和网络速率,并将数据写入MySQL数据库的Python脚本示例:

import psutil
import speedtest
import mysql.connector
from datetime import datetime
import time

# 连接MySQL数据库
cnx = mysql.connector.connect(
    host="localhost",
    user="your_username",
    password="your_password",
    database="your_database"
)
cursor = cnx.cursor()

# 创建数据表
create_table_query = """
CREATE TABLE IF NOT EXISTS server_stats (
    id INT AUTO_INCREMENT PRIMARY KEY,
    cpu_percent FLOAT,
    memory_percent FLOAT,
    disk_percent FLOAT,
    download_speed FLOAT,
    upload_speed FLOAT,
    timestamp DATETIME
)
"""
cursor.execute(create_table_query)

while True:
    # 获取CPU信息
    cpu_percent = psutil.cpu_percent()

    # 获取内存信息
    memory = psutil.virtual_memory()
    memory_percent = memory.percent

    # 获取磁盘信息
    disk = psutil.disk_usage('/')
    disk_percent = disk.percent

    # 获取网络速率信息
    speed_test = speedtest.Speedtest()
    download_speed = speed_test.download() / 1024 / 1024
    upload_speed = speed_test.upload() / 1024 / 1024

    # 获取当前时间
    timestamp = datetime.now()

    # 将数据插入数据库
    insert_query = """
    INSERT INTO server_stats (cpu_percent, memory_percent, disk_percent, download_speed, upload_speed, timestamp)
    VALUES (%s, %s, %s, %s, %s, %s)
    """
    insert_values = (cpu_percent, memory_percent, disk_percent, download_speed, upload_speed, timestamp)
    cursor.execute(insert_query, insert_values)
    cnx.commit()

    time.sleep(60)  # 暂停60秒,每分钟获取一次数据

# 关闭数据库连接
cursor.close()
cnx.close()

上述代码使用了mysql.connector库来连接和操作MySQL数据库。在使用之前,请确保你已经安装了该库:

pip install mysql-connector-python

在运行脚本之前,请将your_username、your_password和your_database替换为实际的MySQL数据库的用户名、密码和数据库名称。

脚本将每分钟获取一次服务器的CPU、内存、磁盘和网络速率数据,并将这些数据插入到名为server_stats的数据表中。数据表包含了ID、CPU使用率、内存使用率、磁盘使用率、下载速率、上传速率和时间戳等列。

接下来,你可以使用Flask或Django等Web框架创建一个API接口来从数据库中检索和显示这些数据。

希望这个示例对你有所帮助!如果你有更多问题,请随时提问。

-