利用Python进行远程关电脑

import os
import time
import poplib
import email
import smtplib
from email.header import decode_header
from email.mime.text import MIMEText
from email.header import Header

# 读取Email,获取Email主题
def getEmailSubject():
    read = poplib.POP3('pop.163.com')
    read.user('[email protected]')  # 163邮箱用户名
    read.pass_('xxx')  # 163邮箱设置中的客户端授权密码
    allEmails = read.stat()  # 读取邮件信息
    topEmail = read.top(allEmails[0], 0)  # 获取最新的一封邮件
    tmp = []
    # 解码邮件,存入tmp
    for s in topEmail[1]:
        try:
            tmp.append(s.decode())
        except:
            try:
                tmp.append(s.decode('gbk'))
            except:
                tmp.append(s.decode('big5'))
    message = email.message_from_string('\n'.join(tmp))
    # 获取邮件主题
    subject = decode_header(message['Subject'])
    if subject[0][1]:
        subjectDecode = subject[0][0].decode(subject[0][1])
    else:
        subjectDecode = subject[0][0]
    return subjectDecode


# 检查Email的主题
def checkEmailSubject():
    while True:
        subject = getEmailSubject()
        print('正在检查邮件...')
        print(subject)
        if subject == '重启':
            os.system('shutdown -r -t 3')
            break
        if subject == '关机':
            os.system('shutdown -s -t 3')
            break
        if subject[:2] =='定时':
            shutdown_ontime(subject)
        time.sleep(10)  # 每10s检查一次

# 发送邮件(**为了防止启动后读取上一次发送的命令,如关机命令等,所以利用SMT给自己的邮箱发一封邮件**)
def sendEmail(user, content='From Python SMTP',subject='欢迎使用!'):
    mail_host = "smtp.163.com"  # 设置服务器
    mail_user = "[email protected]"  # 用户名
    mail_pass = "xxx"  # 口令

    sender = '[email protected]'
    receivers = [user]  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

    message = MIMEText(content, 'plain', 'utf-8')

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

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        # print("邮件发送成功")
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")
#用于定时关机,对得到的邮件主题进行解析,得出关机的时间
def shutdown_ontime(list_time):
    print(list_time)
    subject_list = list_time.split(':')
    try:
        h = int(subject_list[1])
        m = int(subject_list[2])
    except:
        print('输入的格式有误,请以"定时:小时:分钟"的格式发送邮件。切记冒号是英文的冒号!')
        return
    if h > 24 or h < 0:
        h = 0
    if m > 60 or m < 0:
        m = 0
    # 计算秒数
    s = h * 3600 + m * 60
    print('距离关机还有 %d 秒' % s)
    string = 'shutdown -s -t ' + str(s)
    os.system(string)
    time.sleep(s)
    return
if __name__ == '__main__':
    sendEmail(user='xxx')
    checkEmailSubject()

你可能感兴趣的:(利用Python进行远程关电脑)