侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python实现微信远程控制电脑

Python  /  管理员 发布于 7年前   241

首先,我们要先看看微信远程控制电脑的原理是什么呢?

我们可以利用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.comsmtphost = smtp.sina.comport = 25username = [email protected] = XXX[Boss]mail = [email protected] = 2[Command]shutdown=shutdown -f -s -t 100 -c closing...dir=dir[Open]music = F:Masetti - Our Own Heaven.mp3video = F:Jai Waetford - Shy.mp4notepad = notepad

excutor.py

#coding:utf-8import sysreload(sys)sys.setdefaultencoding("utf-8")import osimport win32apifrom mccLog import mccLogclass 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 ConfigParserimport os,sysclass 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 loggingfrom datetime import datetimeclass 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 sysreload(sys)sys.setdefaultencoding("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.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 sysreload(sys)sys.setdefaultencoding("utf-8")import timeimport sysfrom mailHelper import mailHelperfrom excutor import executorfrom configReader import configReader__Author__ = 'william'__Verson__ = 0.5reload(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一些初级阶段的基础知识,并且更深刻体会到从项目的设计到项目的实施,以及项目的测试运维等步骤需要程序员深刻的理解,这样才能在项目中逐渐完善自我。

待续。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Python实现利用163邮箱远程关电脑脚本
    下一条:
    Python标准库笔记struct模块的使用
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客