使用 Python 自动监控磁盘资源使用情况和服务器运行状况更新(磁盘.运行状况.监控.情况.服务器...)
监控服务器磁盘使用情况对于保持最佳性能和防止停机至关重要。在这篇博文中,我们将探讨如何使用 python 脚本自动监控磁盘资源并通过 api 更新服务器运行状况。我们还将讨论如何设置 cron 作业来定期运行脚本。
先决条件- python编程基础知识
- 熟悉linux命令行操作
- 访问可以运行 python 脚本并设置 cron 作业的服务器
- 用于更新服务器运行状况的 api 端点(替换为您的实际 api url 和令牌)
下面是执行磁盘资源监控并通过 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 自动监控磁盘资源使用情况和服务器运行状况更新的详细内容,更多请关注知识资源分享宝库其它相关文章!