郵件遠控電腦MCC-python實現

來源:互聯網
上載者:User

標籤:nbsp   except   sendmail   adc   處理   http   .sh   遠程   filename   

本次實現的是一個通過郵件來遠端控制電腦,以達到某些遠程操作,例如讓電腦執行CMD命令,播放音樂,開啟指定檔案等操作的項目。代碼參考了網上的部分教程。

 

具體流程:

在python代碼中,通過一個迴圈來接受指定郵箱中的郵件,此次採用的是通過郵件的title也就是標題來傳輸命令,程式接受到指定郵件後,根據title執行相應操作。操作成功後,再發送郵件給指定郵箱,表示操作執行成功。

 

(如若實際使用,該程式可能存在若干‘bug‘,部分為程式本身問題,部分由於郵件傳輸的延遲導致,部分由於郵件本身格式導致。經過自行調試可以正常運行,由於精力有限,暫不打算修改。)

 

項目結構:

 

項目代碼:

mcc.py:為項目主控程式,控制項目主要流程

#-*- coding:utf-8 -*-import timefrom utils.mailhelper import mailHelperfrom utils.excutor import excutorfrom utils.configReader import configReader__Author__=‘LOMO‘__Version__=1.0class 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.comsmtphost=smtp.sina.comport=25[email protected]password=xxxxxx[Boss][email protected]timelimit=20[Command]dir=dir[Open]music=E:\CloudMusic\Carly Rae Jepsen - Call Me Maybe.mp3notepad=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,sysimport ConfigParserclass 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,win32apifrom mccLog import mccLogfrom mailhelper import mailHelperclass 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 MIMETextfrom configReader import configReaderfrom mccLog import mccLogimport poplibimport smtplibimport reclass 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 Falseif __name__=="__main__":    mail=mailHelper()    body=mail.acceptMail()    print mail.analysisMail(body)    mail.sendMail(‘test‘,‘Boss‘)

  

mccLog.py:用於生產記錄檔

#-*- coding:utf-8 -*-import loggingfrom datetime import datetimeclass 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)

  

 

郵件遠控電腦MCC-python實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.