码迷,mamicode.com
首页 > 编程语言 > 详细

python 监控windows磁盘空间和备份大小

时间:2017-09-28 17:20:05      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:roo   subject   dict   blog   com   dev   print   pat   文件   

#!/usr/bin/env python
# Version = 3.5.2
# __auth__ = ‘无名小妖‘
import os
import time
import sendmail
import psutil
import collections

disk_used = collections.OrderedDict()
cur_time = time.time()
# current_day = cur_time - cur_time % 86400
root_dir = ["D:\\backup", "G:\db_backup"]
log_name = ‘result.log‘


def get_disk_info():
    """
    查看磁盘属性信息
    :return: 磁盘使用率和剩余空间
    """
    for id in psutil.disk_partitions():
        if ‘cdrom‘ in id.opts or id.fstype == ‘‘:
            continue
        disk_name = id.device.split(‘:‘)
        s = disk_name[0]
        disk_info = psutil.disk_usage(id.device)
        disk_used[s + ‘盘使用率:‘] = ‘{}%‘.format(disk_info.percent)
        disk_used[s + ‘剩余空间:‘] = ‘{}GB‘.format(disk_info.free // 1024 // 1024 // 1024)
    return disk_used


if __name__ == ‘__main__‘:
    with open(log_name, ‘w‘) as f:
        ret = get_disk_info()
        for k, v in ret.items():
            f.write(‘{}{}。\n‘.format(k, v))

        for item in root_dir:
            print(item)
            all_size = 0
            for parent, dir_names, file_names in os.walk(item):  # 遍历文件夹
                for filename in file_names:
                    path = os.path.join(parent, filename)  # 获取文件路径
                    stat_info = os.stat(path)  # 读取文件属性
                    upload_time = time.ctime(stat_info.st_mtime)

                    if stat_info.st_mtime > cur_time - 86400:
                        all_size += stat_info.st_size
                        if stat_info.st_size // 1024 <= 5:
                            f.write(‘\n{}\n\t大小:{}KB,  上传时间:{}。‘.format(path, stat_info.st_size // 1024, upload_time))

            f.write(‘\n\n {}本日备份大小:{}GB.\n‘.format(item, all_size // 1024 // 1024 // 1024))

    with open(log_name, ‘rb‘) as logfile:
        sendmail.sendmail(‘204-备份监控‘, str(logfile.read(), encoding=‘GBK‘))

  

sendmail.py

#!/usr/bin/env python
# Version = 3.5.2
# __auth__ = ‘无名小妖‘
import smtplib
import email.mime.multipart
import email.mime.text


def sendmail(sub, con):
    msg = email.mime.multipart.MIMEMultipart()
    msg[‘from‘] = "wumingxiaoyao@life.org.com"
    msg[‘to‘] = "hello@python.good.com"
    msg[‘subject‘] = sub
    content = con
    txt = email.mime.text.MIMEText(content)
    msg.attach(txt)
    smtp = smtplib.SMTP()
    smtp.connect(‘smtp.mail.haoyisheng.com‘, ‘25‘)
    smtp.login(‘lijianwei@mail.haoyisheng.com‘, ‘xxxxxx‘)
    smtp.sendmail(‘lijianwei@mail.haoyisheng.com‘, ‘lijianwei@mail.haoyisheng.com‘,str(msg))
    smtp.quit()

  

python 监控windows磁盘空间和备份大小

标签:roo   subject   dict   blog   com   dev   print   pat   文件   

原文地址:http://www.cnblogs.com/wumingxiaoyao/p/7607538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!