• 邮件远控电脑MCC-python实现


    本次实现的是一个通过邮件来远程控制电脑,以达到某些远程操作,例如让电脑执行CMD命令,播放音乐,打开指定文件等操作的项目。代码参考了网上的部分教程。

    具体流程:

    在python代码中,通过一个循环来接受指定邮箱中的邮件,此次采用的是通过邮件的title也就是标题来传输命令,程序接受到指定邮件后,根据title执行相应操作。操作成功后,再发送邮件给指定邮箱,表示操作执行成功。

    (如若实际使用,该程序可能存在若干‘bug‘,部分为程序本身问题,部分由于邮件传输的延迟导致,部分由于邮件本身格式导致。经过自行调试可以正常运行,由于精力有限,暂不打算修改。)

    项目结构:

    项目代码:

    mcc.py:为项目主控程序,控制项目主要流程

    #-*- coding:utf-8 -*-
    import time
    from utils.mailhelper import mailHelper
    from utils.excutor import excutor
    from utils.configReader import configReader
    
    __Author__='LOMO'
    __Version__=1.0
    
    class MCC(object):
        CONFIGPATH='_config.ini'
        KEY_COMMAND='Command'
        KEY_OPEN='Open'
        KEY_BOSS='Boss'
        KEY_TIMELIMIT='timelimit'
    
        def __init__(self):
            self.mailHelper=mailHelper()
            self.configReader=configReader(self.CONFIGPATH)
            commandDict=self.configReader.getDict(self.KEY_COMMAND)   #CMD命令字典
            openDict=self.configReader.getDict(self.KEY_OPEN)         #打开文件命令字典
            self.timeLimit=int(self.configReader.readConfig(self.KEY_BOSS,self.KEY_TIMELIMIT))
            self.excutor=excutor(commandDict,openDict)
            self.toRun()
    
        def toRun(self):
            while True:
                self.run()
                time.sleep(self.timeLimit)
    
        def run(self):
            mailBody=self.mailHelper.acceptMail()
            if mailBody:
                exe=self.mailHelper.analysisMail(mailBody)
                if exe:
                    self.excutor.excute(exe)
    
    if __name__=='__main__':
        mcc=MCC()
    

      

    _config.ini:配置文件,其中存放了,奴隶邮箱,boss邮箱的信息等

    [Slave]
    pophost=pop.sina.com
    smtphost=smtp.sina.com
    port=25
    username=xxx@sina.com
    password=xxxxxx
    
    [Boss]
    mail=xxx@qq.com
    timelimit=20
    
    [Command]
    dir=dir
    
    [Open]
    music=E:CloudMusicCarly Rae Jepsen - Call Me Maybe.mp3
    notepad=notepad
    

      

    xxx.log:日志文件,由程序自动生成

    2017-02-03 10:22:20,394 INFO 开始登录邮箱
    2017-02-03 10:22:21,341 INFO 开始配置发件箱
    2017-02-03 10:22:35,490 INFO 发件箱配置成功
    2017-02-03 10:22:35,493 INFO 开始抓取邮箱
    2017-02-03 10:22:36,461 INFO 抓取邮箱成功
    2017-02-03 10:22:36,463 INFO 开始抓取subject和发件人
    

      

    configReader.py:用于读取配置文件

    #-*- coding:utf-8 -*-
    import os,sys
    import ConfigParser
    
    class configReader(object):
        def __init__(self,configPath):
            configFile=os.path.join(sys.path[0],configPath)
            self.cReader=ConfigParser.ConfigParser()
            self.cReader.read(configFile)
    
        def readConfig(self,section,item):   #获取单元内容
            return self.cReader.get(section,item)
    
        def getDict(self,section):           #获取项目内容
            commandDict={}
            items=self.cReader.items(section)
            for key,value in items:
                commandDict[key]=value
            return commandDict
    

      

    excutor.py:用于执行命令的程序,

    #-*- coding:utf-8 -*-
    import os,win32api
    from mccLog import mccLog
    from mailhelper import mailHelper
    
    class excutor(object):
        def __init__(self,commandDict,openDict):
            self.mccLog=mccLog()
            self.commandDict=commandDict
            self.openDict=openDict
            self.mailHelper=mailHelper()
    
        def excute(self,exe):        #执行邮件
            subject=exe['subject'].strip()
            self.mccLog.mccWriteLog(u'开始处理命令')
            print  exe
            if subject in self.commandDict:
                self.mccLog.mccWriteLog(u'执行命令')
                try:
                    command=self.commandDict[subject]
                    os.system(command)
                    self.mailHelper.sendMail('pass', 'Slave')
                    self.mailHelper.sendMail('Success','Boss')
                    self.mccLog.mccWriteLog(u'执行命令成功')
                except Exception,e:
                    self.mccLog.mccError(u'执行命令失败'+str(e))
                    self.mailHelper.sendMail('error','Boss',e)
            elif subject in self.openDict:
                self.mccLog.mccWriteLog(u'打开文件')
                try:
                    openFile=self.openDict[subject]
                    win32api.ShellExecute(0,'open',openFile,'','',1)
                    self.mailHelper.sendMail('pass', 'Slave')
                    self.mailHelper.sendMail('Success','Boss')
                    self.mccLog.mccWriteLog(u'打开文件成功')
                except Exception,e:
                    self.mccLog.mccError(u'打开文件失败'+str(e))
            else:
                pass
                # self.mailHelper.sendMail('error','Boss','no such command')
    

      

    mailHelper.py:关于邮箱的一系列操作,例如登录邮箱,分析邮件,发送邮件等

    #-*- coding=utf-8 -*-
    from email.mime.text import MIMEText
    from configReader import configReader
    from mccLog import mccLog
    import poplib
    import smtplib
    import re
    
    class mailHelper(object):
        CONFIGPATH='_config.ini'
    
        def __init__(self):
            self.mccLog=mccLog()
            cfReader=configReader(self.CONFIGPATH)
            self.pophost=cfReader.readConfig('Slave','pophost')
            self.smtphost=cfReader.readConfig('Slave','smtphost')
            self.port=cfReader.readConfig('Slave','port')
            self.username=cfReader.readConfig('Slave','username')
            self.password=cfReader.readConfig('Slave','password')
            self.bossMail=cfReader.readConfig('Boss','mail')
            self.configSlaveMail()
    
        def loginMail(self):            #登录邮箱
            self.mccLog.mccWriteLog(u'开始登录邮箱')
            try:
                self.pp=poplib.POP3_SSL(self.pophost)
                self.pp.set_debuglevel(0)  #是否显示debug信息
                self.pp.user(self.username)
                self.pp.pass_(self.password)
                self.pp.list()          #尝试所列出邮件
                print u'登陆成功'
            except Exception,e:
                print u'登录失败'
                self.mccLog.mccError(u'登录邮箱失败'+str(e))
                exit()
    
        def acceptMail(self):           #收取邮件
            self.loginMail()
            self.mccLog.mccWriteLog(u'开始抓取邮箱')
            try:
                ret=self.pp.list()
                mailBody=self.pp.retr(len(ret[1]))
                self.mccLog.mccWriteLog(u'抓取邮箱成功')
                return mailBody
            except Exception,e:
                self.mccLog.mccError(u'抓取邮箱失败'+str(e))
                return None
    
        def analysisMail(self,mailBody):    #分析邮件,获取发件人以及命令
            self.mccLog.mccWriteLog(u'开始抓取subject和发件人')
            try:
                subject=re.findall("Subject:(.*?)',",str(mailBody[1]).decode('utf-8'),re.S)
                print subject
                subject=subject[1]
                print subject
                sender =re.search("X-Sender:(.*?)',",str(mailBody[1]).decode('utf-8'), re.S).group(1)
                command={'subject':subject,'sender':sender}
                self.mccLog.mccWriteLog(u'抓取subject和发件人成功')
                return command
            except Exception,e:
                self.mccLog.mccError(u'抓取subject和发件人失败'+str(e))
                return None
    
        def configSlaveMail(self):          #配置发件箱
            self.mccLog.mccWriteLog(u'开始配置发件箱')
            try:
                self.handle=smtplib.SMTP(self.smtphost,self.port)
                self.handle.login(self.username,self.password)
                self.mccLog.mccWriteLog(u'发件箱配置成功')
            except Exception,e:
                self.mccLog.mccError(u'发件箱配置失败'+str(e))
                exit()
    
        def sendMail(self,subject,receiver,body='Success'): #发送邮件
            self.loginMail()
            msg=MIMEText(body,'plain','utf-8')
            msg['Subject']=subject
            msg['from']=self.username
            self.mccLog.mccWriteLog(u'开始发送邮件'+' to '+receiver)
            if receiver=='Slave':
                try:
                    self.handle.sendmail(self.username,self.username,msg.as_string())
                    self.mccLog.mccWriteLog(u'发送邮箱成功')
                    return True
                except Exception,e:
                    self.mccLog.mccError(u'发送邮件失败'+str(e))
                    return False
            elif receiver== 'Boss':
                try:
                    self.handle.sendmail(self.username,self.bossMail,msg.as_string())
                    self.mccLog.mccWriteLog(u'发送邮件成功')
                except Exception,e:
                    self.mccLog.mccError(u'发送邮件失败'+str(e))
                    return False
    
    if __name__=="__main__":
        mail=mailHelper()
        body=mail.acceptMail()
        print mail.analysisMail(body)
        mail.sendMail('test','Boss')
    

      

    mccLog.py:用于生产日志文件

    #-*- coding:utf-8 -*-
    import logging
    from datetime import datetime
    
    class mccLog(object):
        def __init__(self):
            logging.basicConfig(level=logging.DEBUG,
                                format='%(asctime)s %(levelname)s %(message)s',
                                detafmt='%Y-%m-%d %H:%M:%S',
                                filename=datetime.now().strftime('%Y%m%d%H%M%S')+'.log',
                                filemode='a')
    
        def mccWriteLog(self,logContent):   #记录日志
            logging.info(logContent)
    
        def mccError(self,errorContent):    #记录报错日志
            logging.error(errorContent)
    

      

  • 相关阅读:
    HTTP-Headers-And-Tricks
    Burp减少干扰
    HTTP 请求低位三连的解决办法
    apk 脱壳 报错:Failed to spawn: unable to access zygote64 while preparing for app launch; try disablin...
    mysql 如何分批 读取数据
    记录一次问题排查
    navicat打开几秒后就自动关闭
    1013 Battle Over Cities (25 分)
    1012 The Best Rank (25 分)
    1011 World Cup Betting (20 分)
  • 原文地址:https://www.cnblogs.com/lomooo/p/6362432.html
Copyright © 2020-2023  润新知