使用 Python 自动监控磁盘资源使用情况和服务器运行状况更新
来源:dev.to
时间:2024-10-27 21:57:57 337浏览 收藏
知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个文章开发实战,手把手教大家学习《使用 Python 自动监控磁盘资源使用情况和服务器运行状况更新》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

使用 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 自动监控磁盘资源使用情况和服务器运行状况更新》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
111 收藏
-
175 收藏
-
494 收藏
-
129 收藏
-
356 收藏
-
342 收藏
-
276 收藏
-
278 收藏
-
430 收藏
-
122 收藏
-
242 收藏
-
232 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习