部署监控公司电脑桌面并截图保存至阿里云OSS(定时功能)

import socket
import uuid
import schedule
import datetime
import pyautogui
import logging
import oss2
import ctypes
import os
import time
import shutil

# 阿里云OSS配置信息
access_key_id = 'your_id'
access_key_secret = 'your_secret'
bucket_name = 'bucket_name'
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'

# 创建OSS认证
auth = oss2.Auth(access_key_id, access_key_secret)
# 创建OSS Bucket实例
bucket = oss2.Bucket(auth, endpoint, bucket_name)

# 日志和截图文件的存储目录在D盘
screenshots_folder = r"C:\MonitorService\Screenshots"
log_file_path = r"C:\MonitorService\monitor_service.log"

# 确保截图文件夹存在
if not os.path.exists(screenshots_folder):
    os.makedirs(screenshots_folder)

# 确保执行文件目录存在

if not os.path.exists('C:\Screenshots'):
    os.makedirs('C:\Screenshots')

# 设置文件夹隐藏属性
FILE_ATTRIBUTE_HIDDEN = 0x02
screenshots_folder = r"C:\MonitorService\Screenshots"
log_file_path = r"C:\MonitorService\monitor_service.log"
ctypes.windll.kernel32.SetFileAttributesW(screenshots_folder, FILE_ATTRIBUTE_HIDDEN)
ctypes.windll.kernel32.SetFileAttributesW(os.path.dirname(log_file_path), FILE_ATTRIBUTE_HIDDEN)

# 设置日志记录
logging.basicConfig(filename=log_file_path, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def should_take_screenshot():
    """检查是否应该执行截图。"""
    now = datetime.datetime.now()
    # 周六和周日全天运行
    if now.weekday() >= 5:
        return True
    # 周一至周五晚上9点后运行
    # if now.weekday() < 5 and now.hour >= 21:
    if now.weekday() <= 5 or now.hour >= 20:
        return True
    return False


def get_mac_address():
    """获取本机的MAC地址。"""
    mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
    return "_".join([mac[e:e + 2] for e in range(0, 12, 2)])


def take_screenshot():
    """执行屏幕截图操作并确保文件已写入磁盘再进行上传。"""
    try:
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        hostname = socket.gethostname()
        mac_address = get_mac_address()
        file_name = f'{hostname}_{mac_address}_{timestamp}.png'
        file_path = os.path.join(screenshots_folder, file_name)

        # 使用pyautogui进行截图
        screenshot = pyautogui.screenshot()
        screenshot.save(file_path)
        time.sleep(2)
        # 确保文件已存在且大小不为0
        if os.path.exists(file_path) and os.path.getsize(file_path) > 0:
            logging.info(f'保存截图: {file_path}')
            print(f'保存截图: {file_path}')
        else:
            raise Exception("截图文件未成功保存或文件大小为0")

        # 上传到OSS
        with open(file_path, 'rb') as fileobj:
            bucket.put_object(f'Screenshots/{file_name}', fileobj)
        logging.info(f'上传到OSS的截图: {file_name}')
        print(f'上传到OSS的截图: {file_name}')
    except Exception as e:
        logging.error(f'截图错误: {e}')
        print(f'截图错误: {e}')


def job():
    """定时执行的任务,截图并保存。"""
    if should_take_screenshot():
        logging.info('截图中...')
        print('截图中...')
        take_screenshot()
    else:
        logging.info('无法截图,因为现在不是截图时间。')
        print('无法截图,因为现在不是截图时间。')


# 定期清理日志
def clean_old_logs():
    now = time.time()
    log_folder = os.path.dirname(log_file_path)
    for filename in os.listdir(log_folder):
        file_path = os.path.join(log_folder, filename)
        if os.stat(file_path).st_mtime < now - 7 * 86400:  # 7 days
            if os.path.isfile(file_path):
                os.remove(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)


# 定期清理日志
schedule.every().day.at("09:30").do(clean_old_logs)

# 设置调度任务
schedule.every(5).minutes.do(job)

# 主循环
while True:
    schedule.run_pending()
    time.sleep(1)

"""
 
项目逻辑:周一至周五晚上九点以后,周六、周日 对桌面进行截图。
如果有问题的分析处理逻辑:

测试及排错的流程 
1、如果提示文件无法保存则查看相应的文件夹的写入权限。
2、如果要测试,请把  if now.weekday() < 5 and now.hour >= 21  更为:if now.weekday() < 5

部署步骤:
1、pyinstaller --onefile --noconsole system-5-m.py   # 把文件打包成可执行文件
2、启动项的打开方式为:win+R  shell:common startup
"""

后记:由于业务需求才有了上面的代码。遂记之,以备以后查询!

posted @ 2024-06-18 17:23  *感悟人生*  阅读(42)  评论(0编辑  收藏  举报