Mail Remote control Computer Mcc-python Realization

Source: Internet
Author: User

The implementation of this is a remote control of the computer via mail to achieve certain remote operations, such as the computer to perform the cmd command, play music, open the specified files and other operations of the project. The code references some of the tutorials on the web.

Specific process:

In Python code, the message in the specified mailbox is accepted through a loop, this time using the title of the message to transfer the command, the program receives the specified message, according to the title to do the corresponding action. After the operation succeeds, the message is sent to the specified mailbox, indicating that the operation was successful.

(in case of actual use, the program may have a number of ' bugs ', part of the program itself, partly due to delays in the transmission of the message, partly due to the format of the message itself.) After self-commissioning can be normal operation, due to limited energy, and do not intend to modify. )

Project structure:

Project Code:

MCC.PY: Control The main process of the project for the Project master control program

#-*-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 ' K Ey_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 Tru E:self.run () Time.sleep (SELF.TIMELIMIT) def run (self): Mailbody=self.mailhelper.acceptmai     L () if Mailbody:exe=self.mailhelper.analysismail (mailbody) if EXE:           Self.excutor.excute (EXE) if __name__== ' __main__ ': MCC=MCC () 

  

_config.ini: Configuration files, which store, slave mailbox, boss mailbox information, etc.

[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: Log files, automatically generated by programs

2017-02-03 10:22:20,394 Info Start login Mailbox 2017-02-03 10:22:21,341 info start configuring Outbox 2017-02-03 10:22:35,490 Info Outbox configuration Successful 2017-02-03 10 : 22:35,493 info start crawl mailbox 2017-02-03 10:22:36,461 info Crawl Mailbox Success 2017-02-03 10:22:36,463 info start crawl subject and Sender

  

configreader.py: for reading configuration files

#-*-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: The program used to execute the command,

#-*-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.open Dict=opendict Self.mailhelper=mailhelper () def excute (self,exe): #执行邮件 subject=exe[' Subject '].stri P () Self.mccLog.mccWriteLog (U ' start processing command ') print EXE if subject in SELF.COMMANDDICT:SELF.MCC Log.mccwritelog (U ' execute Command ') try:command=self.commanddict[subject] os.system (command                Self.mailHelper.sendMail (' Pass ', ' Slave ') self.mailHelper.sendMail (' Success ', ' Boss ') Self.mccLog.mccWriteLog (U ' execute command succeeded ') except Exception,e:self.mcclog.mccerror (U ' execute command failed ' + STR (e)) self.mailHelper.sendMail (' Error ', ' Boss ', e) elif subject in SELF.OPENDICT:SELF.MC Clog.mccwritelog (U ' open file ') Try:openfile=self.opendict[subject] Win32API. ShellExecute (0, ' open ', OpenFile, ', ', ', 1) self.mailHelper.sendMail (' Pass ', ' Slave ') Self.mailh                Elper.sendmail (' Success ', ' Boss ') self.mccLog.mccWriteLog (U ' open file succeeded ') except Exception,e: Self.mccLog.mccError (U ' Open file Failed ' +str (e)) Else:pass # self.mailHelper.sendMail (' Error ', ' Boss ', ' no such command ')

  

Mailhelper.py: A series of actions about a mailbox, such as logging in to a mailbox, analyzing a message, sending a message, etc.

#-*-coding=utf-8-*-from email.mime.text import mimetextfrom configreader import configreaderfrom mcclog import Mcclogim Port 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 ', ' s Mtphost ') 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 ' start login mailbox ') 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 () #尝试所List mail print u ' login succeeded ' except Exception,e:print U ' logon failed ' self.mccLog.mccError (U ' login mailbox failed ' +str (e)) exit () def acceptmail (self): #收取邮件 self.loginmail () self.mccLog.mccWriteLo G (U ' start crawl mailbox ') Try:ret=self.pp.list () Mailbody=self.pp.retr (Len (ret[1)) Self.mcclo G.mccwritelog (U ' crawl mailbox succeeded ') return mailbody except Exception,e:self.mcclog.mccerror (U ' crawl mailbox failed ' +s TR (e)) return None def analysismail (self,mailbody): #分析邮件, get the sender and command self.mccLog.mccWriteLog (U ' start crawl Subject and Sender ') 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 ' crawl subjecT and Sender success ') return command except Exception,e:self.mcclog.mccerror (U ' crawl subject and Sender failed ' +str (e)) Return None def configslavemail (self): #配置发件箱 self.mccLog.mccWriteLog (U ' start config Outbox ') try : Self.handle=smtplib. SMTP (Self.smtphost,self.port) self.handle.login (Self.username,self.password) Self.mccLog.mccWriteLog (U ' Outbox configuration succeeded ') except Exception,e:self.mcclog.mccerror (U ' Outbox configuration Failed ' +str (e)) exit () def SENDMA Il (self,subject,receiver,body= ' Success '): #发送邮件 self.loginmail () msg=mimetext (body, ' plain ', ' utf-8 ') m  sg[' Subject ']=subject msg[' from ']=self.username self.mccLog.mccWriteLog (U ' start sending mail ' + ' to ' +receiver) if                receiver== ' Slave ': Try:self.handle.sendmail (self.username,self.username,msg.as_string ())           Self.mccLog.mccWriteLog (U ' send mailbox succeeded ') return True except Exception,e:     Self.mccLog.mccError (U ' send Message failed ' +str (e)) ' Return False elif receiver== ' Boss ': try: Self.handle.sendmail (Self.username,self.bossmail,msg.as_string ()) Self.mccLog.mccWriteLog (U ' e-mail Success ') except Exception,e:self.mcclog.mccerror (U ' send Message failed ' +str (e)) return Falseif _ _name__== "__main__": Mail=mailhelper () body=mail.acceptmail () print mail.analysismail (body) mail.sendmail (' tes T ', ' Boss ')

  

mcclog.py: For production log files

#-*-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):   # Log        logging.info (logcontent)    def mccerror (self,errorcontent):    #记录报错日志        Logging.error ( Errorcontent)

  

Mail Remote control Computer Mcc-python Realization

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.