1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
| #!/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对应一个管道输入,多少次输入就只能最大对应多少次输出,以此来达到控制后台进程数量的目的
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
|