今天来分享一个“高大上”的技术――使用python编写一个可以用微信远程控制电脑的程序!
先来分析一下控制的具体流程:
我们使用微信给特定的邮箱发送一封邮件,其中包含了我们想要电脑执行的命令,然后电脑上的python程序获取到这封邮件,然后解析其中的命令,再交付给电脑执行。可以看出,这其中主要的技术难点就是获取邮件了!但是!这没有任何问题,大家看到我的上一篇博客《python 收发邮件》就可以了!
下面给出使用python收发邮件并执行邮件命令的代码。
# -*- coding:utf-8 -*- from email.mime.text import MIMEText import poplib import smtplib import os class MailManager(object): def __init__(self): self.popHost = 'pop.sina.com' self.smtpHost = 'smtp.sina.com' self.port = 25 self.userName = 'ivanzgj@sina.com' self.passWord = 'zgj123' self.bossMail = '475176416@qq.com' self.login() self.configMailBox() # 登录邮箱 def login(self): try: self.mailLink = poplib.POP3_SSL(self.popHost) self.mailLink.set_debuglevel(0) self.mailLink.user(self.userName) self.mailLink.pass_(self.passWord) self.mailLink.list() print u'login success!' except Exception as e: print u'login fail! ' + str(e) quit() # 获取邮件 def retrMail(self): try: mail_list = self.mailLink.list()[1] if len(mail_list) == 0: return None mail_info = mail_list[0].split(' ') number = mail_info[0] mail = self.mailLink.retr(number)[1] self.mailLink.dele(number) subject = u'' sender = u'' for i in range(0, len(mail)): if mail[i].startswith('Subject'): subject = mail[i][9:] if mail[i].startswith('X-Sender'): sender = mail[i][10:] content = {'subject': subject, 'sender': sender} return content except Exception as e: print str(e) return None def configMailBox(self): try: self.mail_box = smtplib.SMTP(self.smtpHost, self.port) self.mail_box.login(self.userName, self.passWord) print u'config mailbox success!' except Exception as e: print u'config mailbox fail! ' + str(e) quit() # 发送邮件 def sendMsg(self, mail_body='Success!'): try: msg = MIMEText(mail_body, 'plain', 'utf-8') msg['Subject'] = mail_body msg['from'] = self.userName self.mail_box.sendmail(self.userName, self.bossMail, msg.as_string()) print u'send mail success!' except Exception as e: print u'send mail fail! ' + str(e) if __name__ == '__main__': mailManager = MailManager() mail = mailManager.retrMail() if mail is not None: cmd = mail['subject'] os.system(cmd) mailManager.sendMsg()
上述代码的逻辑是:邮件的主题为要执行的命令,然后python获取邮箱的邮件,解析其主题,然后交到命令行执行。执行成功后发送一封success的邮件给我。
下面测试一下。我使用qq邮箱给我指定的邮箱发送了下面这样一封邮件。
新闻热点
疑难解答