您的位置:首页 > 其它

脚本应用之四: 批量端口扫描

2016-04-13 16:28 337 查看
作用:批量端口扫描,可根据扫描主机的配置调整后台扫描进程数量(手动执行后根据统计的执行时间调整脚本中关于进程数量的参数),通过定时任务作为简单的服务监控(可修改脚本添加其他报警功能,例如邮件等)
实现:使用nc指令扫描端口, 使用管道特性控制后台扫描进程数量
不足:仅仅对扫描端口状态为down的信息做记录,并没有其他报警操作
使用:需要提供包含被扫描主机的ip地址、协议和端口号的配置文件(格式见演示或代码专区注释)
需要一个日志文件记录端口down状态信息。

配置和日志文件在脚本中定义,默认为:ports_list.cfg 和 port_down.log

演示:



每扫描一次会在日志文件中做记录



代码专区:

#!/bin/bash

#  LY
#  ------------------
#  Copyright 2016.4.14, LingYi (lydygly@163.com) QQ:1519952564
#  "scan ports"

#the conf_file, like this:
#------------------------------------------------------
#        IP       PROTOCOL(tcp/upd)     PORTS(1,2,3)  |
#                                                     |
#  192.168.2.250      tcp                21,22,23     |
#------------------------------------------------------

#配置文件,根据情况修改
conf_file=ports_list.cfg
port_down_log=port_down.log

#后台扫描进程数量,根据服务器配置调整
number_of_background_processes=1000

host_count=0
port_count=0

time_start=0
time_end=0

all_cfg_infor=$( grep -E -v '(^ *#|^$)' $conf_file )

#check nc
if ! rpm -q nc &>/dev/null; then
yum install -y nc &>/dev/null
[[ $? -ne 0 ]] && exit 1
fi

#打印信息
function timestamp()
{
echo -n "$(date +"%Y-%m-%d %H:%M:%S") "
}

#扫描端口函数
# host {tcp|udp} port
function scan_host_port()
{
local this_protocol
if [[ $2 == 'udp' ]]; then
this_protocol='-u'
else
this_protocol=''
fi
if ! nc -z -w 1 $this_protocol $1 $3; then
#其他报警等操作可在此出添加
echo "$(timestamp) Connection to $1 $3 port [$2/$3] failed!" | tee -a $port_down_log
fi
}

sum_line_of_all_cfg_infor=$(echo "$all_cfg_infor" | wc -l)

#管道操作
fifo_file=$(date +%s)
if mkfifo $fifo_file; then
exec 46<>$fifo_file
rm -fr $fifo_file
else
echo "Create fifo file failed !"
exit 2
fi

#每个echo对应一个管道输入,多少次输入就只能最大对应多少次输出,以此来达到控制后台进程数量的目的
#关于shell多进程,参考:http://lingyi.blog.51cto.com/2837715/1575730
time_start=$(date +%s)
for((count_n=1; count_n<=number_of_background_processes; count_n++))
do
echo >&46
done

echo -----------------------------$(timestamp)--------------------------- >>$port_down_log
for((line_num=1; line_num<=sum_line_of_all_cfg_infor; line_num++))
do

line_infor=$( echo "$all_cfg_infor" | sed -n "${line_num}p" )
line_ip=$( echo $line_infor | awk  '{print $1}' )
line_protocol=$( echo $line_infor | awk '{print $2}' )
#read line_ip line_protocol < <(echo $line_infor | awk  '{print $1,$2}')
for this_port in $( echo $line_infor | awk '{print $3}' | tr ',' ' ')
do
#每做一个端口扫描动作读取一次管道
read -u46
#将扫描进程放入后台,以实现进程并发
{
scan_host_port $line_ip $line_protocol $this_port
#操作完成之后,对管道做一次写入操作
echo >&46
} &
let port_count++
done
let host_count++
done

wait
#释放
exec 46>&-
exec 46<&-
time_end=$(date +%s)

echo Hosts: $host_count  Ports: $port_count  Times: $((time_end-time_start))s | tee -a $port_down_log


代码下载链接

本文出自 “逆行者” 博客,请务必保留此出处http://lingyi.blog.51cto.com/2837715/1763482
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: