自宅サーバのHDD残量監視

7月の出張から帰ってみると、自宅サーバのHDD残量が0になって数日分の記録データが消失した模様。出張前にそれなりの容量を空けておいたはずなのですが、予定外に不要なものが記録されていたようで。

毎年このようなことが起きるので残量を監視してメールで報告してくれるプログラムでも探そうかなと思ったのですが、内容が簡単なので作ることに。ついでに仕事でPythonを覚えることになったので、IronPythonLink で作ってみようかと。

  • 残量以外にHDDの健全性チェック機能も付けたので、実行には要管理者権限。
  • 調べたいのはデータドライブだけなので、100GB以上のドライブ限定(STORAGE_MIN_TOTAL_SIZE)。
  • ドライブの使用量が90%を超えた場合にメール (STORAGE_MAX_FREE_RATIO)
  • スクリプト内にメールサーバのパスワードが平文であるのがセキュリティ的に難ありですが、それはおいおい修正ということで(と言って、やらないんだろうな>自分)
MAIL_FROM = "from@example.net"
MAIL_TO = "to@example.net"
SMTP_SERVER = "mail.example.net"
SMTP_PORT = 587
SMTP_USER = "smtpuser"
SMTP_PASSWORD = "smtppassword"
STORAGE_MIN_TOTAL_SIZE = 100e+9
STORAGE_MAX_FREE_RATIO = 0.9

import clr
clr.AddReferenceByPartialName("System.Management")
clr.AddReferenceByPartialName("System.Net")
from System.Management import ManagementScope,ObjectQuery,ManagementObjectSearcher,ManagementObjectCollection
from System.IO import DriveInfo,DriveType
from System import String
from System.Net import NetworkCredential
from System.Net.Mail import SmtpClient,MailMessage

message = ""

# Check HDD health
scope = ManagementScope("¥¥¥¥.¥¥ROOT¥¥WMI")
query = ObjectQuery("SELECT * FROM MSStorageDriver_FailurePredictStatus WHERE PredictFailure=True")
searcher = ManagementObjectSearcher(scope, query)
mgrCollection = searcher.Get()

for aMgr in mgrCollection:
    message = message + aMgr["InstanceName"] + " is predicted to be failure.¥n"


# Check drive free space
drives = DriveInfo.GetDrives()
for aDrive in drives:
    if aDrive.DriveType == DriveType.Fixed and ¥
       aDrive.TotalSize > STORAGE_MIN_TOTAL_SIZE and ¥
       float(aDrive.TotalFreeSpace)/aDrive.TotalSize>STORAGE_MAX_FREE_RATIO:
        message = message + String.Format("{0} has {1:0.0}GB free.¥n", aDrive.Name, aDrive.TotalFreeSpace/1e+9)

try:
    if message <> "":
        mailMsg = MailMessage(MAIL_FROM, MAIL_TO)
        mailMsg.Subject = "Storage alert"
        mailMsg.Body = message
        
        smtpClient = SmtpClient(SMTP_SERVER, SMTP_PORT)
        smtpClient.Credentials = NetworkCredential(SMTP_USER, SMTP_PASSWORD)
        
        smtpClient.Send(mailMsg)

except Exception as ex:
    print ex.clsException
[参照]

— posted by mu at 09:31 pm   commentComment [0]  pingTrackBack [0]

T: Y: ALL: Online:
ThemeSwitch
  • Basic
Created in 0.0088 sec.
prev
2014.8
next
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31