功能并非原創(chuàng), 只是重復(fù)實(shí)現(xiàn)了?http://codecloud.net/python-control-128.html 中描述的功能.?
實(shí)現(xiàn)功能: 通過(guò)給固定郵件地址發(fā)送命令(包含在主題中)的方式控制遠(yuǎn)程電腦實(shí)現(xiàn)相應(yīng)功能(譬如關(guān)機(jī)等, 可以根據(jù)實(shí)際需要實(shí)現(xiàn)更復(fù)雜的功能)
實(shí)現(xiàn)原理: 遠(yuǎn)程電腦不斷(每隔10s)利用 python 腳本檢查郵件服務(wù)器是否有新郵件, 如有則對(duì)郵件進(jìn)行分析, 如果包含可執(zhí)行命令, 則執(zhí)行相應(yīng)命令
你需要的: 裝有 PYTHON 的 PC; 最好兩個(gè)郵箱(一個(gè)用于接收命令, 一個(gè)用來(lái)發(fā)郵件); 可選手機(jī)郵件客戶端(可以實(shí)現(xiàn)在手機(jī)上發(fā)送郵件, 更高大上)
注意: 不要使用163郵箱來(lái)接受命令, 每隔 10s 的檢查間隔會(huì)導(dǎo)致網(wǎng)易拒絕讓你登錄的~?
我反正喪心病狂用學(xué)校的服務(wù)器. ?Python 代碼如下:
# -*- coding: utf-8 -*-
import poplib,email,re
from email.header import decode_header
import smtplib
from email.mime.text import MIMEText
import time
import os,sys
import random
def send_mail(to_mail_addr, message):
? ? from_mail_addr = "****@fudan.edu.cn"
? ? password = "****"
? ? smtp_server = "mail.fudan.edu.cn"? #smtp_server
? ? message = "Hello, mission received: \n \t \t" + message
? ? msg = MIMEText(message, 'plain', 'gb2312')
? ? msg['Subject'] = 'This is a reply msg by PythonMailControl'
? ? msg['From'] = from_mail_addr
? ? msg['To'] = to_mail_addr
? ? server = smtplib.SMTP(smtp_server, 25)
? ? server.set_debuglevel(1)
? ? server.login(from_mail_addr, password)
? ? server.sendmail(from_mail_addr, [to_mail_addr], msg.as_string())
? ? server.quit()
def get_last_mail():
? ? try:
? ? ? ? host = 'mail.fudan.edu.cn'? # pop3 server
? ? ? ? username = '****@fudan.edu.cn'
? ? ? ? password = '****'
? ? ? ? p = poplib.POP3_SSL(host)
? ? ? ? p.user(username)
? ? ? ? p.pass_(password)
? ? ? ? ret = p.stat()
? ? except poplib.error_proto,e:
? ? ? ? print "Login failed:",e
? ? ? ? return (-2,0,0)? # error code, nonsense, nonsense
? ? mail_number = ret[0] # return the total number of mails
? ? ret = p.list()
? ? down = p.retr(1)? ? # return the last received mail
? ? return (1,mail_number,down)
if __name__ == "__main__":
? ? mail_number_old = 0
? ? while 1:
? ? ? ? (error,mail_number,down) = get_last_mail()
? ? ? ? if (error==1) and (mail_number != mail_number_old):? # no error and have new mail
? ? ? ? ? ? mail_number_old = mail_number? ?
? ? ? ? ? ? for line in down[1]:? ? # check the mail line by line, get the sender and subject
? ? ? ? ? ? ? ? if line[0:4]=="From":
? ? ? ? ? ? ? ? ? ? from_mail_addr = re.search( '[0-9a-zA-Z_]*@[0-9a-zA-Z_.]*', line).group(0)?
? ? ? ? ? ? ? ? if line[0:7]=="Subject":
? ? ? ? ? ? ? ? ? ? content = line[9:]
? ? ? ? ? ? if content[0] == '@':? # response according to the subject
? ? ? ? ? ? ? ? cmd = content[1:]
? ? ? ? ? ? ? ? try:
? ? ? ? ? ? ? ? ? ? os.system(cmd)? # do sth.
? ? ? ? ? ? ? ? ? ? send_mail(from_mail_addr,cmd)? # reply message to the mail sender
? ? ? ? ? ? ? ? except:
? ? ? ? ? ? ? ? ? ? os.system('echo error')
? ? ? ? time.sleep(10)
運(yùn)行待機(jī)情況:?
然后用手機(jī)給我的學(xué)號(hào)郵箱發(fā)個(gè)郵件. 主題是 @shutdown -s -t 600
其中 @ 是前導(dǎo)字符, 用于給程序判斷這是一個(gè)命令. shutdown 等則是10分鐘后關(guān)機(jī)的命令.?