温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Linux下Python脚本管理服务器资源

发布时间:2024-09-11 21:22:39 来源:亿速云 阅读:78 作者:小樊 栏目:编程语言

在 Linux 下,你可以使用 Python 脚本来管理服务器资源,例如监控 CPU、内存、磁盘和网络使用情况

  1. 首先,确保你的系统已经安装了 Python。你可以通过在终端中输入 python --versionpython3 --version 来检查 Python 是否已经安装。

  2. 创建一个名为 server_resource_monitor.py 的新 Python 脚本文件。在文件中,我们将编写代码来获取服务器资源的使用情况。

import os
import time
import psutil

def get_cpu_usage():
    return psutil.cpu_percent()

def get_memory_usage():
    mem = psutil.virtual_memory()
    return mem.percent

def get_disk_usage(path='/'):
    disk = psutil.disk_usage(path)
    return disk.percent

def get_network_io():
    net_io = psutil.net_io_counters()
    return net_io.bytes_sent, net_io.bytes_recv

def main():
    while True:
        cpu_usage = get_cpu_usage()
        memory_usage = get_memory_usage()
        disk_usage = get_disk_usage()
        bytes_sent, bytes_recv = get_network_io()

        print(f"CPU Usage: {cpu_usage}%")
        print(f"Memory Usage: {memory_usage}%")
        print(f"Disk Usage: {disk_usage}%")
        print(f"Bytes Sent: {bytes_sent}")
        print(f"Bytes Received: {bytes_recv}")

        time.sleep(5)  # 每隔5秒钟更新一次数据

if __name__ == "__main__":
    main()
  1. 保存文件并在终端中运行脚本:
python server_resource_monitor.py

这个脚本将每隔5秒钟打印服务器的 CPU、内存、磁盘和网络使用情况。你可以根据需要调整时间间隔或添加其他功能,例如将数据写入日志文件或发送到监控系统。

注意:在运行脚本之前,请确保已经安装了 psutil 库。你可以使用以下命令安装:

pip install psutil
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI