python实现微信远程控制电脑
首先,我们要先看看微信远程控制电脑的原理是什么呢?
我们可以利用python的标准库控制本机电脑,然后要实现远程的话,我们可以把电子邮件作为远程控制的渠道,我们用python自动登录邮箱检测邮件,当我们发送关机指令给这个邮箱的时候,若python检测到相关的指令,那么python直接发送本机的相关命令。
下面来分析一下该项目:
1.需求分析
1.范围:用python开发一个远程操控电脑的项目。
2.总体要求:
2.1 总体功能要求:能够通过该软件远程控制该软件所在的电脑的重启或关机操作。
2.2 系统要求:开发语言使用python,并且开发出来的程序能在windows运行。
2.设计
首先,我们可以利用python的标准库控制本机电脑,然后要实现远程的话,我们可以把电子邮件作为远程控制的渠道,我们用python自动登录邮箱检测邮件,当我们发送关机指令给这个邮箱的时候,若python检测到关机的指令,那么python直接发送本机的关闭。
3.编写
本项目的流程图如下
第一步,需要注册一个新浪邮箱。然后点击新浪邮箱点击右上角设置如图
选择“客户端pop/imap/smtp”
打开新浪邮箱的smtp与pop3功能
具体实现代码:
配置文件config.ini
[slave] pophost = pop.sina.com smtphost = smtp.sina.com port = 25 username = xxx@sina.com password = xxx [boss] mail = xxx@qq.com timelimit = 2 [command] shutdown=shutdown -f -s -t 100 -c closing... dir=dir [open] music = f:masetti - our own heaven.mp3 video = f:jai waetford - shy.mp4 notepad = notepad
excutor.py
#coding:utf-8 import sys reload(sys) sys.setdefaultencoding("utf-8") import os import win32api from mcclog import mcclog class executor(object): def __init__(self,commanddict,opendict): ''' 创建方法 :param commanddict: :param opendict: ''' self.mcclog = mcclog() self.commanddict = commanddict self.opendict = opendict def execute(self,exe,mailhelper): self.mailhelper = mailhelper subject = exe['subject'] # self.mcclog.mccwritelog(u'开始处理命令') print u'start to process' if subject !='pass': self.mailhelper.sendmail('pass','slave') if subject in self.commanddict: # self.mcclog.mccwritelog(u'执行命令!') print u'start command' try: command = self.commanddict[subject] os.system(command) self.mailhelper.sendmail('success','boss') # self.mcclog.mccwritelog(u'执行命令成功!') print u'command success' except exception,e: # self.mcclog.mccerror(u'执行命令失败'+ str(e)) print 'command error' self.mailhelper.sendmail('error','boss',e) elif subject in self.opendict: # self.mcclog.mccwritelog(u'此时打开文件') print u'open the file now' try: openfile = self.opendict[subject] win32api.shellexecute(0,'open',openfile,'','',1) self.mailhelper.sendmail('success','boss') # self.mcclog.mccwritelog(u'打开文件成功!') print u'open file success' except exception,e: # self.mcclog.mccerror(u'打开文件失败!' + str(e)) print u'open file error' self.mailhelper.sendmail('error','boss',e) elif subject[:7].lower() =='sandbox': self.sandbox(subject[8:]) else: self.mailhelper.sendmail('error','boss','no such command!') def sandbox(self,code): name = code.split('$n$')[0] code = code.split('$n$')[1] codestr = '\n'.join(code.split('$c$')) codestr = codestr.replace('$',' ') with open(name,'a') as f: f.write(codestr) os.system('python' + name)
configreader.py
#-*-coding:utf-8-*- import configparser import os,sys 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
日志文件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', datefmt='%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)
mailhelper.py
#-*-coding:utf-8-*- import sys reload(sys) sys.setdefaultencoding("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.loginmail() self.configslavemail() def loginmail(self): ''' 验证登陆 :return: ''' self.mcclog.mccwritelog('start to login the e-mail') print 'start to login e-mail' try: self.pp = poplib.pop3_ssl(self.pophost) self.pp.set_debuglevel(0)#可以为0也可以为1,为1时会显示出来 self.pp.user(self.username)#复制 self.pp.pass_(self.password) self.pp.list()#列出赋值 print 'login successful!' self.mcclog.mccwritelog('login the email successful!') print 'login the email successful!' except exception,e: print 'login failed!' self.mcclog.mccwritelog('login the email failed!') exit() def acceptmail(self): ''' 接收邮件 :return: ''' self.mcclog.mccwritelog('start crawling mail!') print 'start crawling mail' try: ret = self.pp.list() mailbody = self.pp.retr(len(ret[1])) self.mcclog.mccwritelog('catch the message successfully') print 'catch the message successfully' return mailbody except exception,e: self.mcclog.mccerror('catch the message failed' + e) print 'catch the message failed' return none def analysismail(self,mailbody): ''' 正则分析邮件 :param mailbody: :return: ''' self.mcclog.mccwritelog('start crawling subject and sender') print 'start crawling subject and sender' try: subject = re.search("subject: (.*?)',",str(mailbody[1]).decode('utf-8'),re.s).group(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("crawling subject and sender successful!") print 'crawling subject and sender successful' return command except exception,e: self.mcclog.mccerror("crawling subject and sender failed!" + e) print 'crawling subject and sender failed!' return none def sendmail(self,subject,receiver,body='success'): ''' 发送邮件 :param subject: :param receiver: :param body: :return: ''' msg = mimetext(body,'plain','utf-8') #中文需要参数utf-8,单字节字符不需要 msg['subject'] = subject msg['from'] = self.username self.mcclog.mccwritelog('start sending mail' + 'to' +receiver) print 'start sending mail' if receiver == 'slave': try: self.handle.sendmail(self.username,self.username,msg.as_string()) self.mcclog.mccwritelog('send the message successfully') print 'send the message successfully' except exception,e: self.mcclog.mccerror('send the message failed' + e) print 'send the message failed' return false elif receiver == 'boss': try: self.handle.sendmail(self.username,self.bossmail,msg.as_string()) self.mcclog.mccwritelog('send the message successfully') print 'send the message successfully' except exception,e: self.mcclog.mccerror('send the message failed!' + e) print 'send the message failed!' return false def configslavemail(self): ''' 配置邮件 :return: ''' self.mcclog.mccwritelog('start configuring the mailbox') print 'start configuring the mailbox' try: self.handle = smtplib.smtp(self.smtphost, self.port) self.handle.login(self.username, self.password) self.mcclog.mccwritelog('the mailbox configuration is successful') print 'the mailbox configuration is successful' except exception, e: self.mcclog.mccerror('the mailbox configuration is failed' + e) print 'the mailbox configuration is failed' exit() # # if __name__=='__main__': # mail = mailhelper() # body = mail.acceptmail() # print body # print mail.analysismail(body) # mail.sendmail('ok','slave')
weichatcontrolcomputer.py
#-*-coding:utf-8-*- import sys reload(sys) sys.setdefaultencoding("utf-8") import time import sys from mailhelper import mailhelper from excutor import executor from configreader import configreader __author__ = 'william' __verson__ = 0.5 reload(sys) sys.setdefaultencoding('utf-8') 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) opendict = self.configreader.getdict(self.key_open) self.timelimit = int(self.configreader.readconfig(self.key_boss,self.key_timelimit)) self.excutor = executor(commanddict,opendict) self.torun() def torun(self): ''' 实现轮训操作 :return: ''' while true: self.mailhelper = mailhelper() self.run() time.sleep(self.timelimit) def run(self): mailbody = self.mailhelper.acceptmail() if mailbody: exe = self.mailhelper.analysismail(mailbody) if exe: self.excutor.execute(exe,self.mailhelper) if __name__ == '__main__': mcc = mcc()
运行截图:
4.总结
在这个小项目的编写过程中,知道了项目开发的基本流程并且走了一遍,通过项目管理的方式去开发项目,并且在这个小项目开发的过程中,复习了python一些初级阶段的基础知识,并且更深刻体会到从项目的设计到项目的实施,以及项目的测试运维等步骤需要程序员深刻的理解,这样才能在项目中逐渐完善自我。
待续。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。