前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >监控计算机的系统状态(Smilinghan-SPCWC)

监控计算机的系统状态(Smilinghan-SPCWC)

原创
作者头像
TanHaX
发布2023-07-25 16:33:01
2140
发布2023-07-25 16:33:01
举报
文章被收录于专栏:Smilinghan

刚考完试闲得发慌写的。

Smilinghan-SPCWC 是一个 Python 程序,允许用户监控计算机的系统状态并发送电子邮件通知。该程序使用 tkinter 库创建图形用户界面 (GUI),使用 smtplib 库发送电子邮件。还使用了其他库,如 socket、requests、datetime、pyautogui、threading、os、sys、time 和 ctypes。

代码语言:python
代码运行次数:0
复制
import tkinter as tk

from tkinter import ttk

import smtplib

import socket

import requests

import datetime

import pyautogui

import threading

import os

import sys

import time

import ctypes

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

from email.mime.image import MIMEImage

from email.header import Header



USER32 = ctypes.windll.user32

SW\_SHOW = 5

SW\_HIDE = 0



class EmailChecker:

    def \_\_init\_\_(self):

        self.sent\_email = False

        self.stop\_event = threading.Event()

        self.thread = None

        self.root = tk.Tk()

        self.root.title("Smilinghan-SPCWC")

        self.create\_widgets()



    def create\_widgets(self):

        mainframe = ttk.Frame(self.root, padding="20 10 20 10")

        mainframe.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.E, tk.S))

        mainframe.columnconfigure(0, weight=1)

        mainframe.rowconfigure(0, weight=1)



        email\_entry = ttk.Entry(mainframe, width=30)

        email\_entry.grid(column=1, row=0, sticky=(tk.W, tk.E))



        email\_label = ttk.Label(mainframe, text="Email:")

        email\_label.grid(column=0, row=0, sticky=tk.E)



        submit\_button = ttk.Button(mainframe, text="确定", command=lambda: self.submit\_email(email\_entry))

        submit\_button.grid(column=2, row=0, sticky=tk.W)



        start\_button = ttk.Button(mainframe, text="开始检测", command=self.start\_thread)

        start\_button.grid(column=0, row=2, sticky=tk.W)



        stop\_button = ttk.Button(mainframe, text="停止检测", command=self.stop\_thread)

        stop\_button.grid(column=2, row=2, sticky=tk.E)



        output\_text = tk.Text(mainframe, height=10, width=50)

        output\_text.grid(column=0, row=3, columnspan=3, sticky=(tk.W, tk.E))



        for child in mainframe.winfo\_children():

            child.grid\_configure(padx=5, pady=5)



        email\_entry.focus()

        self.root.bind('<Return>', lambda event: self.submit\_email(email\_entry))



        self.output\_text = output\_text



    def submit\_email(self, email\_entry):

        email = email\_entry.get()

        self.output\_text.insert(tk.END, "接收的电子邮件: " + email + "\n")



        with open("emails.txt", "w") as f:

            f.write(email + "\n")



        email\_entry.delete(0, tk.END)

        email\_entry.insert(0, "")



    def send\_email(self, subject, content, receiver):

        sender = 'smilinghan@qq.com'

        password = 'password'



        with open("emails.txt", "r") as f:

            receivers = [f.read().strip()]



        message = MIMEMultipart()



        message['Subject'] = Header(subject, 'utf-8')

        message['From'] = Header(sender)

        message['To'] = Header(receiver)



        text = MIMEText(content, 'html', 'utf-8')

        message.attach(text)



        screenshot = pyautogui.screenshot()

        if screenshot is not None:

            screenshot.save('screenshot.png')

            with open('screenshot.png', 'rb') as f:

                img = MIMEImage(f.read())

                img.add\_header('Content-ID', '<screenshot>')

                message.attach(img)



        try:

            smtpObj = smtplib.SMTP\_SSL('smtp.qq.com', 465)

            smtpObj.login(sender, password)

            smtpObj.sendmail(sender, receivers, message.as\_string())

            self.output\_text.insert(tk.END, "邮件发送成功\n")

            self.sent\_email = True

        except Exception as e:

            self.output\_text.insert(tk.END, "邮件发送失败\n")

            self.output\_text.insert(tk.END, str(e) + "\n")

            self.sent\_email = False



    def check\_system(self, receiver):

        try:

            while not self.stop\_event.is\_set():

                if USER32.GetForegroundWindow() != 0:

                    hostname = socket.gethostname()

                    ip\_address = socket.gethostbyname(hostname)

                    response\_ip = requests.get("https://www.90th.cn/api/ip")

                    if response\_ip.status\_code == 200:

                        public\_ip = response\_ip.json()["ip"]

                        address = response\_ip.json()["address"]

                    else:

                        public\_ip = "获取失败"

                        address = "获取失败"

                    login\_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")



                    subject = '系统状况报告'

                    content = f"""

                    <html>

                    <body>

                    <h3>系统状况报告</h3>

                    <p>主机名: {hostname}</p>

                    <p>外网IP: {public\_ip}</p>

                    <p>内网IP: {ip\_address}</p>

                    <p>归属地: {address}</p>

                    <p>发送时间: {login\_time}</p>

                    <p>登录状态: 成功</p>

                    <p><img src="cid:screenshot"></p>

                    </body>

                    </html>

                    """

                    if not self.sent\_email:

                        self.send\_email(subject, content, receiver)

                    self.sent\_email = True

                    time.sleep(5)

                else:

                    time.sleep(1)

                    self.sent\_email = False

                    self.output\_text.insert(tk.END, "电脑未唤醒\n")

        except Exception as e:

            self.output\_text.insert(tk.END, "Error: 无法检测电脑唤醒状态\n")

            self.output\_text.insert(tk.END, str(e) + "\n")

            self.sent\_email = False



    def start\_thread(self):

        if self.thread is None or not self.thread.is\_alive():

            with open("emails.txt", "r") as f:

                receiver = f.read().strip()

            self.thread = threading.Thread(target=self.check\_system, args=(receiver,), daemon=True)

            self.thread.start()

            self.output\_text.insert(tk.END, "开始检测\n")



    def stop\_thread(self):

        if self.thread is not None and self.thread.is\_alive():

            self.stop\_event.set()

            self.thread.join(timeout=3)

            self.output\_text.insert(tk.END, "停止检测\n")



    def run(self):

        if getattr(sys, 'frozen', False):

            os.chdir(sys.\_MEIPASS)

        self.root.protocol("WM\_DELETE\_WINDOW", self.stop\_check)

        self.root.mainloop()



    def stop\_check(self):

        if not self.stop\_event.is\_set():

            self.stop\_event.set()

        if self.thread is not None and self.thread.is\_alive():

            self.thread.join(timeout=3)

        self.stop\_thread()

        self.root.destroy()

        self.root.quit()

        for t in threading.enumerate():

            if t != threading.current\_thread():

                t.join(timeout=3)



if \_\_name\_\_ == '\_\_main\_\_':

    checker = EmailChecker()

    checker.run()

pCMBARU.png
pCMBARU.png

安装

  1. 克隆存储库或下载文件。
  2. 确保计算机上已安装 Python。
  3. 运行以下命令安装所需的库:
代码语言:shell
复制

pip install -r requirements.txt

代码语言:txt
复制

使用

  1. 打开命令提示符或终端,导航到文件所在的目录。
  2. 运行以下命令启动程序:
代码语言:shell
复制

python email_checker.py

代码语言:txt
复制
  1. 程序将打开一个 GUI 窗口。
  2. 在“电子邮件”字段中输入您的电子邮件地址,然后单击“确定”按钮。
  3. 单击“开始检测”按钮以开始监控系统状态。
  4. 如果计算机处于唤醒状态并正在使用,程序将每 5 秒发送一封包含系统信息和屏幕截图的电子邮件。
  5. 如果计算机处于空闲或睡眠状态,程序将不会发送任何电子邮件。
  6. 要停止监控,请单击“停止检测”按钮。

注意事项

  • 该程序使用 邮件服务器发送电子邮件。请确保您拥有一个邮箱账户或者邮箱服务器,并在 send\_email 方法中提供正确的电子邮件地址和密码。
  • 该程序将电子邮件地址保存在名为 "emails.txt" 的文件中。请确保该文件与程序位于同一目录中。
  • 该程序使用 pyautogui 库进行屏幕截图。请确保您已安装该库并具有进行屏幕截图的必要权限。
  • 该程序使用线程在后台运行监控过程。stop\_event 用于在用户单击“停止检测”按钮时停止监控过程。
  • 程序将在 GUI 窗口中显示输出消息。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 刚考完试闲得发慌写的。
  • Smilinghan-SPCWC 是一个 Python 程序,允许用户监控计算机的系统状态并发送电子邮件通知。该程序使用 tkinter 库创建图形用户界面 (GUI),使用 smtplib 库发送电子邮件。还使用了其他库,如 socket、requests、datetime、pyautogui、threading、os、sys、time 和 ctypes。
  • 安装
  • 使用
  • 注意事项
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档