python实现微信远程控制电脑


Posted in Python onFebruary 22, 2018

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

我们可以利用Python的标准库控制本机电脑,然后要实现远程的话,我们可以把电子邮件作为远程控制的渠道,我们用Python自动登录邮箱检测邮件,当我们发送关机指令给这个邮箱的时候,若Python检测到相关的指令,那么Python直接发送本机的相关命令。

下面来分析一下该项目:

1.需求分析

1.范围:用Python开发一个远程操控电脑的项目。

2.总体要求:

2.1 总体功能要求:能够通过该软件远程控制该软件所在的电脑的重启或关机操作。
2.2 系统要求:开发语言使用Python,并且开发出来的程序能在Windows运行。

2.设计

首先,我们可以利用Python的标准库控制本机电脑,然后要实现远程的话,我们可以把电子邮件作为远程控制的渠道,我们用Python自动登录邮箱检测邮件,当我们发送关机指令给这个邮箱的时候,若Python检测到关机的指令,那么Python直接发送本机的关闭。

3.编写

本项目的流程图如下

python实现微信远程控制电脑 

第一步,需要注册一个新浪邮箱。然后点击新浪邮箱点击右上角设置如图

python实现微信远程控制电脑

选择“客户端pop/imap/smtp”

python实现微信远程控制电脑 

打开新浪邮箱的SMTP与POP3功能

python实现微信远程控制电脑

具体实现代码:
配置文件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()

运行截图:

python实现微信远程控制电脑

4.总结

在这个小项目的编写过程中,知道了项目开发的基本流程并且走了一遍,通过项目管理的方式去开发项目,并且在这个小项目开发的过程中,复习了Python一些初级阶段的基础知识,并且更深刻体会到从项目的设计到项目的实施,以及项目的测试运维等步骤需要程序员深刻的理解,这样才能在项目中逐渐完善自我。

待续。

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

Python 相关文章推荐
python实现apahce网站日志分析示例
Apr 02 Python
python进阶教程之动态类型详解
Aug 30 Python
kNN算法python实现和简单数字识别的方法
Nov 18 Python
Python实现把回车符\r\n转换成\n
Apr 23 Python
python比较2个xml内容的方法
May 11 Python
Python实现将json文件中向量写入Excel的方法
Mar 26 Python
spark: RDD与DataFrame之间的相互转换方法
Jun 07 Python
Python3将数据保存为txt文件的方法
Sep 12 Python
深入浅析Python 命令行模块 Click
Mar 11 Python
对python中return与yield的区别详解
Mar 12 Python
python实现每天自动签到领积分的示例代码
Aug 18 Python
python制作微博图片爬取工具
Jan 16 Python
Python标准库笔记struct模块的使用
Feb 22 #Python
python实现手机通讯录搜索功能
Feb 22 #Python
Python实现通讯录功能
Feb 22 #Python
Python SQLite3简介
Feb 22 #Python
Python Web程序部署到Ubuntu服务器上的方法
Feb 22 #Python
Python中 传递值 和 传递引用 的区别解析
Feb 22 #Python
centos 安装python3.6环境并配置虚拟环境的详细教程
Feb 22 #Python
You might like
phpMyAdmin下载、安装和使用入门教程
2007/05/31 PHP
php 保留字列表
2012/10/04 PHP
ThinkPHP中I(),U(),$this->post()等函数用法
2014/11/22 PHP
thinkphp多层MVC用法分析
2015/12/30 PHP
微信公众平台开发教程③ PHP实现微信公众号支付功能图文详解
2019/04/10 PHP
Javascript中的for in循环和hasOwnProperty结合使用
2013/06/05 Javascript
常规表格多表头查询示例
2014/02/21 Javascript
Express.JS使用详解
2014/07/17 Javascript
JQuery实现鼠标移动图片显示描述层的方法
2015/06/25 Javascript
JQuery实现级联下拉框效果实例讲解
2015/09/17 Javascript
Highcharts使用简例及异步动态读取数据
2015/12/30 Javascript
javascript实现label标签跳出循环操作
2016/03/06 Javascript
js表单处理中单选、多选、选择框值的获取及表单的序列化
2016/03/08 Javascript
41个Web开发者必须收藏的JavaScript实用技巧
2016/07/22 Javascript
javascript常用经典算法详解
2017/01/11 Javascript
JavaScript 网页中实现一个计算当年还剩多少时间的倒数计时程序
2017/01/25 Javascript
详解使用Visual Studio Code对Node.js进行断点调试
2017/09/14 Javascript
vue-cli 打包使用history模式的后端配置实例
2018/09/20 Javascript
vue项目使用axios发送请求让ajax请求头部携带cookie的方法
2018/09/26 Javascript
vue下使用nginx刷新页面404的问题解决
2019/08/02 Javascript
mpvue网易云短信接口实现小程序短信登录的示例代码
2020/04/03 Javascript
python snownlp情感分析简易demo(分享)
2017/06/04 Python
Python 中字符串拼接的多种方法
2018/07/30 Python
python可视化爬虫界面之天气查询
2019/07/03 Python
Pycharm简单使用教程(入门小结)
2019/07/04 Python
python实现自动化报表功能(Oracle/plsql/Excel/多线程)
2019/12/02 Python
TensorFlow自定义损失函数来预测商品销售量
2020/02/05 Python
如何使用Cython对python代码进行加密
2020/07/08 Python
平民服装店创业计划书
2014/01/17 职场文书
高中生期末评语
2014/01/28 职场文书
销售职业生涯规划范文
2014/03/14 职场文书
端午节演讲稿
2014/05/23 职场文书
计算机专业求职信
2014/06/02 职场文书
四风批评与自我批评范文
2014/10/14 职场文书
初中班主任工作总结2015
2015/05/13 职场文书
2015年党员发展工作总结
2015/05/13 职场文书