flask+docker+shell实现网段扫描

项目要求

  • 1.搭建一个监控平台或者脚本也可以,检测指定的范围内的所有IP是否能够Ping通,能够Ping通的记录下来到一个文件,不同通的记录下来到一个文件。

  • 2.每天22点自动检测,并将所有的结果通过邮件形式或者微信平台发送给指定的人员

  • 3.需要将所有的搭建过程以及操作的方式形成文档提供以后使用

项目规划

拓扑图

规划

  • 1.为了提高资源的利用率,采用docker容器的方式快速的部署需要的环境

  • 2.单纯的脚本单调没有可视化,采取了flask结合shell脚本方式实现项目目标

  • 3.为了容器的可持续化定义了volume卷

目录结构

本地数据库

项目的部署

手动部署


\#docker环境安装 curl -fsSL get.docker.com -o get-docker.sh;sh get-docker.sh –mirror Aliyun;systemctl restart docker;systemctl enable docker #开启docker镜像加速 echo '{ "registry-mirrors": ["https://hie6dt5f.mirror.aliyuncs.com"] }'>/etc/docker/daemon.json systemctl restart docker #运行容器 docker run -itd -p 80:80 --name ip-ping registry.cn-shenzhen.aliyuncs.com/opsself/ipmonitor:v3

修改邮箱信息

#第一步进入容器
docker exec -it ip-ping bash

#修改参数
cd /app/sh
send_email.py

项目效果

  • 帮助一键安装部署,不需要人为的干预,直接达到目标。

  • 简单易懂,端口映射为80,如果需要修改,请去compose文件中的修改对应的端口即可

项目源代码

python-flask代码实现

# Auth:Andrew, ddy
# Date:2018-06-12

import os
import subprocess
from flask import Flask
from flask import render_template,request,redirect,url_for

app = Flask(__name__)

ip_active_list = []
ip_fail_list = []


@app.route("/")
def index():
  return render_template("index.html")

@app.route("/check", methods=['POST','GET'])
def check():
  if request.method == 'POST':
    begin_ip = request.form['begin_ip']
    end_ip = request.form['end_ip']
    ip_str = "%s %s"%(begin_ip,end_ip)

    #写IP操作
    f_write(ip_str)

    #调用底层shell脚本
    f_check()

    #读取文件
    f_read()

    return render_template("content.html", ip_str=ip_str,ip_active_list=ip_active_list,ip_fail_list=ip_fail_list)

def f_write(ip_str):
  f = open("/app/sh/ip.txt","w")
  f.write(ip_str)
  f.close()

def f_read():
  global ip_active_list
  global ip_fail_list
  f = open("/app/sh/result/ip_active.txt","r")
  ip_active_list = f.readlines()
  print(ip_active_list)
  f.close()
  f = open("/app/sh/result/ip_fail.txt","r")
  ip_fail_list = f.readlines()
  print(ip_fail_list)
  f.close()

def f_check():
    #os.system("/app/sh/scan.sh")
    os.system("ssh mycentos /app/sh/scan.sh")


if __name__ == "__main__":
  app.run(host='0.0.0.0', debug=True, port=80)

前端base代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            margin: 0;
        }
        .c_head{
            text-align: center;
            font-size: 20px;
            color: white;
            background: steelblue;
        }
    </style>
    {% block head %}
    {% endblock %}
</head>
<body>
    <div class="c_head">
        <span>IP检测平台</span>
    </div>
    {% block main %}
    {% endblock %}
</body>
</html>

前端content代码

{% extends 'base.html' %}

{% block head %}
    <style>
        .box{
            text-align: center;
        }
        .active_box{
            width: 150px;
            height: 350px;
            margin: 10px 10px;
            padding: 10px;
            border: 2px solid;
            border-radius:2%;
            overflow: scroll;
         }
        .fail_box{
            width: 150px;
            height: 350px;
            margin: 10px 10px;
            padding: 10px;
            border: 2px solid;
            border-radius:2%;
            overflow: scroll;
        }
        table{
            margin: 0 auto;
        }
    </style>
{% endblock %}

{% block main %}
    <div class="box">
        <table>
            <tr>
                <td>
                    <div class="active_box">
                        <p>活跃IP</p>
                        {% for active_ip in ip_active_list %}
                            <p>{{ active_ip }}</p>
                        {% endfor %}
                    </div>
                </td>
                <td>
                    <div class="fail_box">
                        <p>下线IP</p>
                        {% for fail_ip in ip_fail_list %}
                            <p>{{ fail_ip }}</p>
                        {% endfor %}
                    </div>
                </td>
            </tr>
        </table>
    </div>
{% endblock %}

前端index.html代码

{% extends 'base.html' %}

{% block head %}
<style>
    body{
        margin: 0;
    }
    .c_head{
        text-align: center;
        font-size: 20px;
        color: white;
        background: steelblue;
    }
    .c_body{
        margin: 10px auto;
    }
    table{
        margin:0 auto;
    }
</style>
{% endblock %}

{% block main %}
<div class="c_body">
    <form action="/check" method="post">
        <table>
            <tr>
                <td align="right">Begin of IP:</td>
                <td><input type="text" name="begin_ip"></td>
            </tr>

            <tr>
                <td align="right">End of IP:</td>
                <td><input type="text" name="end_ip"></td>
            </tr>
        </table>
        <div style="text-align: center; margin-top: 10px;">
            <input type="submit" value="检测">
            <input type="reset">
        </div>
    </form>
</div>
{% endblock %}

后端代码实现

#!/bin/bash 
#time:2018-06-12
#auth:ddy
#项目:自动化扫描网段

#自定义函数
check(){   #环境的检测
ping -c 2 www.baidu.com
if [ ! ? -eq 0 ];then     echo "网络环境异常请修复!">>/app/sh/log/scan.log fi while : do which nmap >/dev/null if [ ? -eq 0 ];then
    break
else
    echo 环境检查失败>>/app/sh/log/scan.log
    yum -y install nmap >/dev/null
fi

done

}

fail(){
while :
do
  for i in `seq ip_begin ip_end`
  do
    for ae  in `seq 1 255`
    do
      for be in `cat /app/sh/result/ip_active.txt|head -1|cut -d . -f4`
      do
      echo ""
      done
      if [ ! "ae" == "be" ];then
        echo 176.121.i.ae >>/app/sh/result/ip_fail.txt
      fi
    done
  if [ i -eq ip_end  ];then
  clear
  echo "执行完毕!"
  break
  fi
  done
break
done
echo "`date "+%Y-%m-%d %H:%M:%S"` 执行成功打印失败的IP" >>/app/sh/log/scan.log
}
#变量
ip_begin=`cat /app/sh/ip.txt |cut -d " " -f 1|cut -d . -f 3`
ip_end=`cat /app/sh/ip.txt |cut -d " " -f 2|cut -d . -f 3`

#主函数
#check
echo >/app/sh/result/ip_active.txt
echo >/app/sh/result/ip_fail.txt

#if [ ip_begin == ip_end ];then
#ip_b=`cat ip.txt |cut -d " " -f1|cut -d . -f4`
#ip_e=`cat ip.txt |cut -d " " -f2|cut -d . -f4`
#for g in `seq ip_b ip_e`
#do
#nmap -n -p 22 -PA 176.121.ip_begin.ip_g-ip_e |grep 'Nmap'|grep -v "scanned"|grep -v "Starting Nmap"|cut -d " " -f 5 >>/app/sh/result/ip_active.txt #done #else for i in `seq ip_begin ip_end` do nmap -n -p 22 -PA 176.121.i.0/24 |grep 'Nmap'|grep -v "scanned"|grep -v "Starting Nmap"|cut -d " " -f 5 >>/app/sh/result/ip_active.txt
done
echo "`date "+%Y-%m-%d %H:%M:%S"` 执行成功扫描IP" >>/app/sh/log/scan.log
sed -ie "/^$/d" /app/sh/result/ip_active.txt
fail
#fi

Python发送邮件代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

sender = 'from@runoob.com'
receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header("测试邮件", 'utf-8')
msgRoot['To'] =  Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
msgRoot['Subject'] = Header(subject, 'utf-8')

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)


mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.runoob.com">菜鸟教程链接</a></p>
<p>图片演示:</p>
<p><img src="cid:image1"></p>
"""
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))

# 指定图片为当前目录
fp = open('test.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

# 定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, msgRoot.as_string())
    print "邮件发送成功"
except smtplib.SMTPException:
    print "Error: 无法发送邮件"

开启QQ邮件服务

我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3aeiwlzqcmiok

flask+docker+shell实现网段扫描》有3个想法

  1. I not to mention my friends have already been looking through the good pointers from the blog then all of a sudden I got an awful suspicion I never thanked the web site owner for those techniques. The guys are actually for this reason excited to learn them and have in effect absolutely been tapping into those things. Many thanks for actually being so kind and also for using variety of ideal information most people are really wanting to be aware of. My sincere regret for not saying thanks to you earlier.

发表评论