python实现微信远程控制电脑
作者:Wlain 发布时间:2023-07-07 07:43:43
首先,我们要先看看微信远程控制电脑的原理是什么呢?
我们可以利用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一些初级阶段的基础知识,并且更深刻体会到从项目的设计到项目的实施,以及项目的测试运维等步骤需要程序员深刻的理解,这样才能在项目中逐渐完善自我。
待续。
来源:http://blog.csdn.net/qq_30070433/article/details/73731187
猜你喜欢
- 在python显示图象时,我们用matplotlib模块时会遇到图像色彩失真问题,究竟是什么原因呢,下面就来看看究竟。待显示图像为:impo
- XPath 的安装以及使用1 . XPath 的介绍刚学过正则表达式,用的正顺手,现在就把正则表达式替换掉,使用 XPath,有人表示这太坑
- 前言本文做的是基于三层神经网络实现手写数字分类,神经网络设计是设计复杂深度学习算法应用的基础,本文将介绍如何设计一个三层神经网络模型来实现手
- 最近因工作需要,要学习PHP的基础编程,于是学习架设PHP工作环境。但按照教材上介绍的那样,安装了WMAP后,一直无法运行成功。后发现Apa
- 要自动签到,最简单的是打开页面分析请求,然后我们用脚本实现请求的自动化。但是发现食行没有页面,只有 APP,这不是一个好消息,这意味着需要抓
- 1. 问题抓取某个网站,发现请求参数是乱码格式,这是点击 TextView,发现请求参数如下图所示3. 那么=%B9%FA%CE%F1%D4
- 第一招、mysql服务的启动和停止net stop mysqlnet start mysql第二招、登陆mysql语法如下: mysql -
- 查询数据库中的表名查询一个数据库中含有某关键词的表名搜索一个数据库中包含一些关键字,词的表。SELECT  
- # 比较两个字符串,如果不同返回第一个不相同的位置# 如果相同返回0def cmpstr(str1, str2): &
- 具体如下: 1>如我们知道开始时间,要加减一个时间,得出一个结果时间,可以用以下代码 $time1='2008-10-1 12
- 项目需要在electron的项目中新打开一个窗口,利用webpack作为静态资源打包器,发现在webpack中可以设置多页面的入口,今天来讲
- 本文实例为大家分享了Python实现发送QQ邮件的封装代码,供大家参考,具体内容如下封装codeimport smtplibfrom ema
- 本文实例讲述了MySQL 事务概念与用法。分享给大家供大家参考,具体如下:事务的概念MySQL事务是一个或者多个的数据库操作,要么全部执行成
- 前言本文主要是积累一下在使用前端的watch开发过程中遇到的问题点和经验。一、watch是什么根据本人的理解,它就是一个 * ,就是说监听的
- 本文实例为大家分享了python绘制散点图和折线图的具体代码,供大家参考,具体内容如下#散点图,一般和相关分析、回归分析结合使用import
- 原文地址:30 Days of Mootools 1.2 Tutorials - Day 19 - TooltipsMootools 1.2
- 本文实例为大家分享了python实现电子书翻页的具体代码,供大家参考,具体内容如下1.题目:电子书翻页:(1)自动翻页:每次默认读三行,读完
- 在定向爬虫的制作过程中,使用分布式爬取技术可以显著提高爬取效率。而 Redis 配合 Scrapy 是实现分布式爬取的基础。Redis 是一
- MySQL从5.1.4版开始带有一个压力测试工具mysqlslap,通过模拟多个并发客户端访问mysql来执行测试,使用起来非常的简单。通过
- 以前看到 andy的关于“Quiet Structure”觉的很不错,于是今天到她的个人站点上逛逛,发现不少好的文章,今天介绍的是