Python 3.x基礎實戰(zhàn)檢查磁盤可用空間
引言
在 Linux 服務器上,磁盤空間的使用情況是一個非常重要的指標。如果服務器上的磁盤空間不足,可能會導致服務器崩潰,影響網(wǎng)站的正常運行。為了避免這種情況的發(fā)生,我們需要定期檢查服務器上的磁盤空間,并及時清理不必要的文件。本文將介紹如何使用 Python 3腳本檢查 Linux 服務器上的磁盤空間。
使用psutil模塊實現(xiàn)
首先,我們需要安裝psutil
模塊。psutil
是一個跨平臺的庫,用于獲取系統(tǒng)信息,包括磁盤使用情況、CPU使用情況等。我們可以使用以下命令來安裝psutil
:
pip3 install psutil
獲取磁盤使用情況
我們將使用psutil
模塊來獲取磁盤使用情況。以下是獲取磁盤使用情況的示例代碼:
import psutil # 獲取磁盤使用情況 disk_usage = psutil.disk_usage('/') # 打印磁盤使用情況 print(f"Total: {disk_usage.total / (1024*1024*1024):.2f} GB") print(f"Used: {disk_usage.used / (1024*1024*1024):.2f} GB") print(f"Free: {disk_usage.free / (1024*1024*1024):.2f} GB")
在這個示例中,我們使用psutil.disk_usage()
函數(shù)來獲取磁盤使用情況。該函數(shù)需要傳遞一個參數(shù),即要獲取使用情況的磁盤路徑。在這個示例中,我們傳遞了根目錄/
作為參數(shù)。psutil.disk_usage()
函數(shù)返回一個namedtuple
對象,其中包含總?cè)萘?、已用容量和可用容量等信息?/p>
獲取磁盤掛載點
在Linux系統(tǒng)中,磁盤可以掛載到不同的目錄下。如果您的系統(tǒng)中有多個磁盤,您可能需要檢查每個磁盤的可用空間。以下是獲取磁盤掛載點的示例代碼:
import psutil # 獲取磁盤掛載點 disk_partitions = psutil.disk_partitions() # 打印磁盤掛載點 for partition in disk_partitions: print(f"Device: {partition.device}") print(f"Mountpoint: {partition.mountpoint}") print(f"File system type: {partition.fstype}") print()
在這個示例中,我們使用psutil.disk_partitions()
函數(shù)來獲取磁盤掛載點。該函數(shù)返回一個列表,其中包含每個掛載點的信息,包括設備、掛載點和文件系統(tǒng)類型等。
檢查磁盤可用空間
現(xiàn)在我們已經(jīng)了解了如何獲取磁盤使用情況和磁盤掛載點,讓我們編寫一個腳本來檢查磁盤的可用空間。以下是檢查磁盤可用空間的示例代碼:
import psutil import os # 獲取磁盤掛載點 disk_partitions = psutil.disk_partitions() # 遍歷每個掛載點 for partition in disk_partitions: # 獲取磁盤使用情況 disk_usage = psutil.disk_usage(partition.mountpoint) # 計算磁盤可用空間的百分比 free_percent = disk_usage.free / disk_usage.total * 100 # 如果磁盤可用空間小于10%,發(fā)送警告郵件 if free_percent < 10: # 獲取主機名 hostname = os.uname()[1] # 構(gòu)造郵件內(nèi)容 subject = f"Disk space warning on {hostname}" message = f"The disk {partition.device} ({partition.mountpoint}) is running out of space ({free_percent:.2f}% free)." # 發(fā)送郵件 send_email(subject, message)
在這個示例中,我們遍歷了每個磁盤掛載點,并使用psutil.disk_usage()
函數(shù)獲取了每個掛載點的使用情況。然后,我們計算了每個掛載點的可用空間百分比,并檢查了是否小于10%。如果是,我們將發(fā)送一封警告郵件。
使用 du 命令實現(xiàn)
使用 du 命令檢查磁盤空間
du 命令是 Linux 系統(tǒng)中一個非常有用的命令,可以用來查看當前目錄或文件的磁盤使用情況。在 Python 3 中,我們可以使用 subprocess 模塊來執(zhí)行 du 命令,并將其輸出解析為 Python 對象。
以下是一個簡單的 Python 3 腳本,用于檢查服務器上特定目錄的磁盤使用情況:
import subprocess def get_directory_size(path): """Return the total size of the files in the given directory and subdirectories.""" cmd = ["du", "-sh", path] result = subprocess.run(cmd, stdout=subprocess.PIPE) output = result.stdout.decode("utf-8").strip() size = output.split()[0] return size # Example usage: size = get_directory_size("/var/www/html") print("Size of /var/www/html: {}".format(size))
在上面的示例中,我們定義了一個名為 get_directory_size
的函數(shù),該函數(shù)接受一個路徑作為參數(shù),并返回該目錄及其子目錄中文件的總大小。該函數(shù)使用 subprocess.run
函數(shù)來執(zhí)行 du
命令,并將其輸出解析為 Python 對象。然后,我們從輸出中提取出目錄的大小,并將其作為字符串返回。
要使用此函數(shù),只需調(diào)用 get_directory_size
并傳遞要檢查的目錄的路徑即可。在上面的示例中,我們檢查了 /var/www/html
目錄的大小,并將結(jié)果打印到控制臺上。
檢查多個目錄的磁盤空間
如果您需要檢查多個目錄的磁盤使用情況,可以使用一個簡單的循環(huán)來遍歷目錄列表,并調(diào)用 get_directory_size
函數(shù)來獲取每個目錄的大小。以下是一個示例腳本,用于檢查多個目錄的磁盤使用情況:
import subprocess def get_directory_size(path): """Return the total size of the files in the given directory and subdirectories.""" cmd = ["du", "-sh", path] result = subprocess.run(cmd, stdout=subprocess.PIPE) output = result.stdout.decode("utf-8").strip() size = output.split()[0] return size # List of directories to check directories = ["/var/www/html", "/var/log", "/etc"] # Loop through directories and print their sizes for directory in directories: size = get_directory_size(directory) print("Size of {}: {}".format(directory, size))
在上面的示例中,我們定義了一個名為 directories
的列表,其中包含要檢查的目錄的路徑。然后,我們使用一個簡單的循環(huán)遍歷該列表,并調(diào)用 get_directory_size
函數(shù)來獲取每個目錄的大小。
檢查磁盤空間使用率
除了檢查單個目錄或多個目錄的磁盤使用情況之外,我們還可以使用 Python 3 來檢查整個磁盤的使用情況。以下是一個示例腳本,用于檢查磁盤使用率:
import subprocess def get_disk_usage(): """Return the disk usage of the root filesystem in percent.""" cmd = ["df", "-h", "/"] result = subprocess.run(cmd, stdout=subprocess.PIPE) output = result.stdout.decode("utf-8").strip() usage = int(output.split("\n")[1].split()[4].replace("%", "")) return usage # Example usage: usage = get_disk_usage() print("Disk usage: {}%".format(usage))
在上面的示例中,我們定義了一個名為 get_disk_usage
的函數(shù),該函數(shù)返回根文件系統(tǒng)的磁盤使用率。該函數(shù)使用 subprocess.run
函數(shù)來執(zhí)行 df
命令,并將其輸出解析為 Python 對象。然后,我們從輸出中提取出磁盤使用率,并將其作為整數(shù)返回。
要使用此函數(shù),只需調(diào)用 get_disk_usage
并將其結(jié)果打印到控制臺上即可。
發(fā)送郵件
在上面的示例中,我們調(diào)用了一個名為send_email()
的函數(shù)來發(fā)送郵件。這個函數(shù)需要進行自定義實現(xiàn)。以下是一個簡單的send_email()
函數(shù)的示例代碼:
import smtplib from email.mime.text import MIMEText from email.header import Header def send_email(subject, message): # 郵件發(fā)送者和接收者 sender = 'sender@example.com' receiver = 'receiver@example.com' # 郵件主題和內(nèi)容 msg = MIMEText(message, 'plain', 'utf-8') msg['Subject'] = Header(subject, 'utf-8') # 發(fā)送郵件 smtp = smtplib.SMTP('smtp.example.com') smtp.login(sender, 'password') smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
在這個示例中,我們使用smtplib
模塊來發(fā)送郵件。首先,我們指定了郵件發(fā)送者和接收者的地址。然后,我們使用MIMEText
類創(chuàng)建了一個郵件對象,并指定了郵件的主題和內(nèi)容。最后,我們使用SMTP
類連接到郵件服務器,并使用login()
方法進行身份驗證。然后,我們使用sendmail()
方法發(fā)送郵件,并使用quit()
方法關閉連接。
結(jié)論
在這篇教程中,我們使用Python 3編寫了一個腳本來檢查Linux服務器的磁盤可用空間。我們使用了psutil
和os
模塊來獲取磁盤信息,并編寫了一個簡單的函數(shù)來發(fā)送警告郵件。這個腳本可以幫助您在磁盤空間不足時及時采取措施,避免系統(tǒng)崩潰。
以上就是Python 3.x基礎實戰(zhàn)檢查磁盤可用空間的詳細內(nèi)容,更多關于Python檢查磁盤可用空間的資料請關注腳本之家其它相關文章!
相關文章
Python簡單實現(xiàn)查找一個字符串中最長不重復子串的方法
這篇文章主要介紹了Python簡單實現(xiàn)查找一個字符串中最長不重復子串的方法,涉及Python針對字符串的簡單遍歷、運算等相關操作技巧,需要的朋友可以參考下2018-03-03python使用aiohttp通過設置代理爬取基金數(shù)據(jù)簡單示例
這篇文章主要為大家介紹了python使用aiohttp通過設置代理爬取基金數(shù)據(jù)簡單示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06