搜尋
首頁後端開發Python教學使用 Python 自動執行磁碟資源使用監控和伺服器運行狀況更新

Automating Disk Resource Usage Monitoring and Server Health Updates with 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 自動執行磁碟資源使用監控和伺服器運行狀況更新的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:編譯器還是解釋器?Python:編譯器還是解釋器?May 13, 2025 am 12:10 AM

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

python用於循環與循環時:何時使用哪個?python用於循環與循環時:何時使用哪個?May 13, 2025 am 12:07 AM

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

Python循環:最常見的錯誤Python循環:最常見的錯誤May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

對於循環和python中的循環時:每個循環的優點是什麼?對於循環和python中的循環時:每個循環的優點是什麼?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具