首页 > 代码库 > telnet 扫描公网IP的22号端口是否存在暴露问题,并及时发送邮件

telnet 扫描公网IP的22号端口是否存在暴露问题,并及时发送邮件

#!/usr/bin/env python3  
#coding: utf-8
import time
import commands
import os
import smtplib
import email.MIMEMultipart
import email.MIMEText
import email.MIMEBase
import mimetypes
import 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 = "aochuanfei@163.com"
To = "158505233239@qq.com,123456@qq.com"
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‘] = From
main_msg[‘To‘] = To
main_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号端口是否存在暴露问题,并及时发送邮件