標籤:smtplib 存在 login multipart lines 格式 stream att 附件
#!/usr/bin/env python3 #coding: utf-8import timeimport commandsimport osimport smtplibimport email.MIMEMultipartimport email.MIMETextimport email.MIMEBaseimport mimetypesimport email.MIMEImage#import MIMEImage# 功能:掃描主機的22號連接埠是否開放並將成功的匯出日誌,如果有22號連接埠被檢測到公開出去了,則匯出日誌,並立即發送郵件給責任人aochaunfei # 第一步:開啟檔案(檔案存放了私網IP = 公網IP 22 格式),對檔案的內容一行一行的讀取,同時進行telnte操作 # a.如果telnet傳回值為0說明telnet成功,則公網的22號連接埠被公開出去,有被攻擊的風險,那麼將對應得 公用IP 寫入到以一個時間打頭的檔案裡面 # b.反之則將 公網IP 寫入到另外一個時間打頭的檔案裡面作為區分f = open("/lianxi/aochuanfei/telnet/telnet.txt","r")ExposePort_log = open("/lianxi/aochuanfei/telnet/ExposePort/ExposePort.log","w")NoExposePort_log = open("/lianxi/aochuanfei/telnet/NoExposePort/NoExposePort.log","w")for ip_port in f.readlines(): # 此處有問題,截取出來的不是 # os.environ[‘ip_port‘] = str(ip_port) #ip = str(ip_port.strip()) ip = ip_port.split("=")[-1].strip() print ip status = commands.getstatusoutput(‘telnet $ip‘) if status == 0: ExposePort_log.write(ip_port) else: NoExposePort_log.write(ip_port)f.close()ExposePort_log.close()NoExposePort_log.close()Time = time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime(time.time()))commands.getstatusoutput(‘mv /lianxi/aochuanfei/telnet/ExposePort/ExposePort.log /lianxi/aochuanfei/telnet/ExposePort/$Time_ExposePort.log‘)commands.getstatusoutput(‘mv /lianxi/aochuanfei/telnet/NoExposePort/NoExposePort.log /lianxi/aochuanfei/telnet/NoExposePort/$Time_NoExposePort.log‘) # 第二步:將暴露公網IP 22號連接埠的檔案通過郵件附件的形式發送個郵箱From = "[email protected]"To = "[email protected],[email protected]"file_name = "/lianxi/aochuanfei/telnet/ExposePort/$Time_ExposePort.log" #附件名 server = smtplib.SMTP("smtp.163.com")server.login("aochuanfei","aixocm123") #僅smtp伺服器需要驗證時 # 構造MIMEMultipart對象做為根容器 main_msg = email.MIMEMultipart.MIMEMultipart()# 構造MIMEText對象做為郵件顯示內容並附加到根容器 text_msg = email.MIMEText.MIMEText("請注意附件裡的公網的22號連接埠已經暴露",_charset="utf-8")main_msg.attach(text_msg)# 構造MIMEBase對象做為檔案附件內容並附加到根容器 ctype,encoding = mimetypes.guess_type(file_name)if ctype is None or encoding is not None: ctype=‘application/octet-stream‘maintype,subtype = ctype.split(‘/‘,1)file_msg=email.MIMEImage.MIMEImage(open(file_name,‘rb‘).read(),subtype)print ctype,encoding## 設定附件頭 basename = os.path.basename(file_name)file_msg.add_header(‘Content-Disposition‘,‘attachment‘, filename = basename)#修改郵件標頭 main_msg.attach(file_msg)# 設定根容器屬性 main_msg[‘From‘] = Frommain_msg[‘To‘] = Tomain_msg[‘Subject‘] = "請注意!!!"main_msg[‘Date‘] = email.Utils.formatdate( )# 得到格式化後的完整文本 fullText = main_msg.as_string( )# 用smtp發送郵件 try: server.sendmail(From, To.split(‘,‘), fullText)finally: server.quit()
telnet 掃描公網IP的22號連接埠是否存在暴露問題,並及時發送郵件