首页 > 编程语言 >python监控磁盘使用率

python监控磁盘使用率

时间:2023-07-20 18:13:27浏览次数:41  
标签:get python self system secret import 磁盘 使用率 config

#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# @Time    : 2023/6/27 13:56
# @Author  : zk_linux
# @File    : Disk_monitoring.py.py
# @Software: PyCharm
from temp import ail_the_alarm
import psutil
import os

threshold_value = 75

os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def get_disk_info():
    disk_usage = psutil.disk_usage('/').percent
    return disk_usage


def monitoring():
    res = get_disk_info()
    if res >= threshold_value:
     
       webhook = ail_the_alarm.DingTalkUrl('/server/scripts/config.ini').get_config()
       ding_msg = ail_the_alarm.Send_Dingding('HK-集群环境02', webhook['mobile_number'], web_url=webhook['prod_webhook_url'],secret=webhook['prod_secret'], msg="当前磁盘使用率:{} 已超出预值".format(res))
       ding_msg.send_dingnding()
 
if "__name__ == __main__":
    monitoring()

  

[root@acs-hk-ctos7-prod-02 scripts]# cat config.ini 
[MySQL]
master_host=172
master_port=3306
master_user=root
master_password=Z
slave_host=1


[DingTalk]
#生产
prod_webhook_url = https://oapi.dingtalk.com/robot/send?access_token=94790bbfa97c855d241b9eacf5b1d7ed868afd4d863e14f04b04cd8d06
prod_secret=SEC859f1cefff0cc3c202df524222d05c65ac8ffb4ec7da3ecfbe5257
#测试
dev_webhook_url= https://oapi.dingtalk.com/robot/send?access_token=39095663a52a5975a827a87f84af8d14321919536e71e43f90488
dev_secret= SEC359c7842f082d8b7b90ef46bd7d2e3063a1aad29b55b98e0e8519bd
mobile_number=13

[Redis]
redis_master_host= 172.
redis_master_port= 6379
redis_master_password = 
redis_slave_host= 17

[Code]
mobile_phone_number = 1569
signature_name = 智控网络
template_code = SMS_4606
master_monitor_address= http://172..7:6666/user/getNewPublicKey?loginType=1
slave_monitor_address= http://172.318:6666/user/getNewPublicKey?loginType=1

[sms]
phonenumbers = 15657
signname = 网络
templatecode = SMS_46

  

[root@acs-hk-ctos7-prod-02 scripts]# cat temp/ail_the_alarm.py 
#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# @time    : 2023/7/7 10:48
# @File    : temp.py
# @Author  : zk_linux
# @Software: PyCharm
# @Description:
import datetime
import json
import socket
import os
import requests
import configparser
import base64
import hmac
import urllib
import hashlib
import time


class GetDigest:
    @staticmethod
    def get_digest(secret):
        # secret= "SEC359c7842f08286efb1fc5d8b7b90ef46bd7d2e3063a1aad29b55b98e0e8519bd"
        timestamp = str(round(time.time() * 1000))
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        return f"&timestamp={timestamp}&sign={sign}"


class GetSysyemInfo:
    @staticmethod
    def get_system_info():
        system_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        host_name = socket.gethostname()
        system_load = os.popen("uptime|awk '{print $NF,$NF-1,$NF-2}'")
        load = system_load.read().strip()
        ip = requests.get('http://ifconfig.me').text.strip()
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        local_ip = s.getsockname()[0]
        s.close()

        return system_time, host_name, load, local_ip ,ip


class DingTalkUrl:
    def __init__(self, config_file):
        self.config_file = config_file

    def get_config(self):
        config = configparser.ConfigParser()
        config.read(self.config_file)
        return config['DingTalk']


class Send_Dingding(GetSysyemInfo):
    # system_info = GetSysyemInfo.get_system_info()

    def __init__(self, *args, **kwargs):
        '''

        :param title,mobile_number
        :param web_url,secret,msg
        '''
        self.args = args
        self.kwargs = kwargs



    def send_dingnding(self):
        '''
        :return: requests  web_url,secret data
        '''
        MSG = (
            "**告警主题**:" + "\n" + str(self.args[0]) + "\n\n"
            " >当前时间:" + "\n" + str(GetSysyemInfo.get_system_info()[0]) + "\n\n"
            " >当前主机名:"  + "\n" + str(GetSysyemInfo.get_system_info()[1]) + "\n\n" \
            " >当前系统load:" + "\n" + str(GetSysyemInfo.get_system_info()[2]) + "\n\n" \
            " >当前服务器IP:" + "\n" + str(GetSysyemInfo.get_system_info()[3]) + "\n" + str(GetSysyemInfo.get_system_info()[4]) +"\n\n" \
            " >详细信息:" + "\n" + self.kwargs['msg'] +  "\n")


        data={
          "msgtype": "markdown",
          "markdown": {
            "title": str(self.args[0]),
            "text": MSG,
          },
          "at": {
            "atMobiles": [
              self.args[1]
            ],
            "isAtAll": False
          }
        }

        headers = {
              'Content-Type': 'application/json'
        }
        req = requests.post(self.kwargs['web_url'] + GetDigest.get_digest(self.kwargs['secret']),json=data,headers=headers)

 

TRANSLATE with x English
Arabic Hebrew Polish
Bulgarian Hindi Portuguese
Catalan Hmong Daw Romanian
Chinese Simplified Hungarian Russian
Chinese Traditional Indonesian Slovak
Czech Italian Slovenian
Danish Japanese Spanish
Dutch Klingon Swedish
English Korean Thai
Estonian Latvian Turkish
Finnish Lithuanian Ukrainian
French Malay Urdu
German Maltese Vietnamese
Greek Norwegian Welsh
Haitian Creole Persian  
  TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back

标签:get,python,self,system,secret,import,磁盘,使用率,config
From: https://www.cnblogs.com/sseban/p/17569214.html

相关文章

  • python_500个长尾词
    pythonpython怎么读python编程python能做什么python下载python代码大全python语言属于什么语言python123python线下培训班python什么东西python官网python培训python入门python学习网站python安装python游戏代码python入门代码python游戏开发python爬虫python手机版python编译器py......
  • 请问为什么cmd中输入python显示no python at (python所在地址)?
    可能是由于您的Python安装路径不在系统的PATH环境变量中导致的。您可以尝试将Python的安装路径添加到PATH环境变量中,然后再次尝试在cmd中输入python。如果您已经将Python的安装路径添加到了PATH环境变量中,但仍然无法在cmd中输入python,那么可能是因为您的系统中存在多个版本的Pyt......
  • exclude在python中
    Python中的exclude用法作为一名经验丰富的开发者,我将教会你如何在Python中使用"exclude"函数。首先,让我们了解一下整个过程的流程,并在下面的表格中列出每个步骤。步骤描述1导入所需的库2定义一个包含要排除元素的列表3使用列表推导式或filter()函数来排除元素......
  • ile "D:\Development\Python\Python39\Scripts\pip3.exe\__main__.py", line 4,
    Python中的pip命令及其用法在Python中,pip是一个非常重要的工具,它是PythonPackageIndex(简称PyPI)上的软件包管理系统。通过使用pip,我们可以方便地安装、升级和卸载Python的第三方库。安装pip在大多数情况下,新版本的Python已经预装了pip。然而,如果你的Python没有安装pip,你可以通......
  • python安装问题
    --使用pipinstall命令安装插件时出现如下提示:(命令python-mpipinstall-ihttps://pypi.tuna.tsinghua.edu.cn/simplegitlab==1.0.2)(环境:Windows10)UnicodeDecodeError:'gbk'codeccan'tdecodebyte0xa2inposition202:illegalmultibytesequence[e......
  • 08python离线安装requests需要安装的依赖库
    requests安装有依赖的包版本,如下:certifi[required:>=2017.4.17]#CA认证模块urllib3[required:!=1.25.0,!=1.25.1,<1.26,>=1.21.1’]#线程安全HTTP库idna[required:<2.9,>=2.5]#国际化域名解析模块chardet[required:❤️.1.0,>=3.0.2]#通用字符编码检测器模块......
  • python模块缺少报错
     [root@localhostpythonProject1]#python-mpipinstall--upgradepip/usr/bin/python:Nomodulenamedpip[root@localhostpythonProject1]#python3-mpipinstall--upgradepippython3-mpipinstallnumpy ......
  • mod python
    mod_python简介及使用示例mod_python是一款用于在ApacheWeb服务器上扩展Python的模块。它为开发人员提供了一种在Web服务器上使用Python编写动态内容的方法,使得开发和维护Web应用程序更加方便快捷。本文将介绍mod_python的基本概念、安装过程以及使用示例。安装m......
  • Python简单HTTP Server
    Python简单HTTPServerfromhttp.serverimportBaseHTTPRequestHandler,HTTPServerclassMyHttpRequestHandler(BaseHTTPRequestHandler):defdo_POST(self):print("path:"+self.path)print("method:"+self.command)print(s......
  • 用Python脚本自动采集金融网站当天发布的免费报告
    大家好,我是皮皮。一、前言前几天在Python群【林生】问了一个Python数据采集的问题,需求如下:想写一个脚本能自动采集下载当天发布的这个页面的这几个免费报告,能保存成这个标题的pdf文件,网站是手机号注册就能下载这些文件的,就是在我注册登录状态下,能采集下载。二、实现过程一开......