使用 Python 自动执行磁盘资源使用情况监控和服务器运行状况更新
监控服务器磁盘使用情况对于保持最佳性能和防止停机至关重要。在这篇博文中,我们将探讨如何使用 Python 脚本自动监控磁盘资源并通过 API 更新服务器运行状况。我们还将讨论如何设置 cron 作业来定期运行脚本。
先决条件
- Python编程基础知识
- 熟悉Linux命令行操作
- 访问可以运行 Python 脚本并设置 cron 作业的服务器
- 用于更新服务器运行状况的 API 端点(替换为您的实际 API URL 和令牌)
Python 脚本解释
下面是执行磁盘资源监控并通过 API 更新服务器运行状况的 Python 脚本。
本篇博文未涵盖 Health API 创建,如果您也需要,请发表评论,我也会发布该 api 创建步骤。
import subprocess import requests import argparse class Resource: file_system = '' disk_size = 0.0 used = 0.0 avail = 0.0 use_percent = 0.0 mounted_on = 0.0 disk_free_threshold = 1 mount_partition = "/" class ResourcesMonitor(Resource): def __init__(self): self.__file_system = Resource.file_system self.__disk_size = Resource.disk_size self.__used = Resource.used self.__avail = Resource.avail self.__use_percent = Resource.use_percent self.__mounted_on = Resource.mounted_on self.__disk_free_threshold = Resource.disk_free_threshold self.__mount_partition = Resource.mount_partition def show_resource_usage(self): """ Print the resource usage of disk. """ print("file_system", "disk_size", "used", "avail", "use_percent", "mounted_on") print(self.__file_system, self.__disk_size, self.__used, self.__avail, self.__use_percent, self.__mounted_on) def check_resource_usage(self): """ Check the disk usage by running the Unix 'df -h' command. """ response_df = subprocess.Popen(["df", "-h"], stdout=subprocess.PIPE) for line in response_df.stdout: split_line = line.decode().split() if split_line[5] == self.__mount_partition: if int(split_line[4][:-1]) > self.__disk_free_threshold: self.__file_system, self.__disk_size, self.__used = split_line[0], split_line[1], split_line[2] self.__avail, self.__use_percent, self.__mounted_on = split_line[3], split_line[4], split_line[5] self.show_resource_usage() self.update_resource_usage_api(self) def update_resource_usage_api(self, resource): """ Call the update API using all resource details. """ update_resource_url = url.format( resource.__file_system, resource.__disk_size, resource.__used, resource.__avail, resource.__use_percent, resource_id ) print(update_resource_url) payload = {} files = {} headers = { 'token': 'Bearer APITOKEN' } try: response = requests.request("GET", update_resource_url, headers=headers, data=payload, files=files) if response.ok: print(response.json()) except Exception as ex: print("Error while calling update API") print(ex) if __name__ == '__main__': url = "http://yourapi.com/update_server_health_by_server_id?path={}&size={}" \ "&used={}&avail={}&use_percent={}&id={}" parser = argparse.ArgumentParser(description='Disk Resource Monitor') parser.add_argument('-id', metavar='id', help='ID record of server', default=7, type=int) args = parser.parse_args() resource_id = args.id print(resource_id) resource_monitor = ResourcesMonitor() resource_monitor.check_resource_usage()
Resource 和 ResourcesMonitor 类
Resource 类定义了与磁盘使用相关的属性,例如文件系统、磁盘大小、已用空间等。 ResourcesMonitor类继承自Resource并初始化这些属性。
检查磁盘使用情况
check_resource_usage 方法执行 Unix df -h 命令来获取磁盘使用统计信息。它解析输出以查找指定安装分区的磁盘使用情况(默认为/)。如果磁盘使用率超过阈值,则会更新资源详细信息并调用 API 更新方法。
通过 API 更新服务器运行状况
update_resource_usage_api 方法使用资源详细信息构造 API 请求 URL,并发送 GET 请求来更新服务器运行状况。确保将 http://yourapi.com/update_server_health_by_server_id 替换为您的实际 API 端点并提供正确的 API 令牌。
使用脚本
将脚本保存为resource_monitor.py并使用Python 3运行它。
命令行参数
- -id:要更新健康数据的服务器ID(默认为7)。 这将有助于在多个服务器中运行相同的脚本,只需更改 ID。
用法和输出示例
$ python3 resource_monitor.py -id=7 Output: file_system disk_size used avail use_percent mounted_on /dev/root 39G 31G 8.1G 80% / API GET Request: http://yourapi.com/update_server_health_by_server_id?path=/dev/root&size=39G&used=31G&avail=8.1G&use_percent=80%&id=7 Response {'success': 'Servers_health data Updated.', 'data': {'id': 7, 'server_id': 1, 'server_name': 'web-server', 'server_ip': '11.11.11.11', 'size': '39G', 'path': '/dev/root', 'used': '31G', 'avail': '8.1G', 'use_percent': '80%', 'created_at': '2021-08-28T13:45:28.000000Z', 'updated_at': '2024-10-27T08:02:43.000000Z'}}
使用 Cron 实现自动化
要每 30 分钟自动执行一次脚本,请添加一个 cron 作业,如下所示:
*/30 * * * * python3 /home/ubuntu/resource_monitor.py -id=7 &
您可以通过运行 crontab -e 并添加以上行来编辑 cron 作业。这将确保脚本每 30 分钟运行一次,从而使您的服务器运行状况数据保持最新。
结论
通过自动化磁盘资源监控和服务器运行状况更新,您可以主动管理服务器的性能并避免由于磁盘空间短缺而导致的潜在问题。此 Python 脚本可作为起点,并可进行定制以满足您的特定需求。
以上是使用 Python 自动执行磁盘资源使用情况监控和服务器运行状况更新的详细内容。更多信息请关注PHP中文网其他相关文章!

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

本文解释了如何使用美丽的汤库来解析html。 它详细介绍了常见方法,例如find(),find_all(),select()和get_text(),以用于数据提取,处理不同的HTML结构和错误以及替代方案(SEL)

Python的statistics模块提供强大的数据统计分析功能,帮助我们快速理解数据整体特征,例如生物统计学和商业分析等领域。无需逐个查看数据点,只需查看均值或方差等统计量,即可发现原始数据中可能被忽略的趋势和特征,并更轻松、有效地比较大型数据集。 本教程将介绍如何计算平均值和衡量数据集的离散程度。除非另有说明,本模块中的所有函数都支持使用mean()函数计算平均值,而非简单的求和平均。 也可使用浮点数。 import random import statistics from fracti

本文比较了Tensorflow和Pytorch的深度学习。 它详细介绍了所涉及的步骤:数据准备,模型构建,培训,评估和部署。 框架之间的关键差异,特别是关于计算刻度的

本文讨论了诸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和请求等流行的Python库,并详细介绍了它们在科学计算,数据分析,可视化,机器学习,网络开发和H中的用途

本文指导Python开发人员构建命令行界面(CLIS)。 它使用Typer,Click和ArgParse等库详细介绍,强调输入/输出处理,并促进用户友好的设计模式,以提高CLI可用性。

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

文章讨论了虚拟环境在Python中的作用,重点是管理项目依赖性并避免冲突。它详细介绍了他们在改善项目管理和减少依赖问题方面的创建,激活和利益。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境