bash中打印彩色log

主要使用了ascii彩色字符, 可以基本实现彩色LOG的效果

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
#!/bin/bash

colorize(){
GREEN="\033[0;32m"
CYAN="\033[0;36m"
RED="\033[0;31m"
GRAY="\033[0;37m"
BLUE="\033[0;34m"
YELLOW="\033[0;33m"
NORMAL="\033[m"
color=\$${1:-NORMAL}
# activate color passed as argument
echo -ne "`eval echo ${color}`"
# read stdin (pipe) and print from it:
echo "${*:2}"
# Note: if instead of reading from the pipe, you wanted to print
# the additional parameters of the function, you could do:
# shift; echo $*
# back to normal (no color)
echo -ne "${NORMAL}"
}

success() {
colorize GREEN $@
}

failed() {
colorize RED $@
}


# 检查22端口是否开启
type=TCP
server=127.0.0.1
port=22
nc -z -w5 $server $port
result=$?

# 根据不同的结果打印不同的颜色
if [ "$result" != 0 ]; then
failed "$type port $server:$port is closed"
else
success "$type port $server:$port is open"
fi

检查特定的TCP与UDP端口有无开放

TCP端口检查

1.使用telnet

1
2
3
4
5
6
7
8
9
10
~ ❤️  telnet 127.0.0.1 6380
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
~ ❤️ telnet 127.0.0.1 6379
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
^]
telnet> q
Connection closed.
  1. 使用netcat
1
2
3
4
5
6
~ ❤️  nc -z -w5 127.0.0.1 6380
~ ❤️ echo $?
1
~ ❤️ nc -z -w5 127.0.0.1 6379
~ ❤️ echo $?
0

UDP端口检测

请注意, UDP协议与TCP协议不同, 即使该端口有应用监听也不一定能保证探测成功.

使用netcat

1
2
3
4
5
6
7
8
9
 ~ ❤️ nc -vz -w5 -u 127.0.0.1 519
localhosti [127.0.0.1] 519 (?) : Connection refused
~ ❤️ echo $?
1

~ ❤️ nc -vz -w5 -u 127.0.0.1 514
localhost [127.0.0.1] 514 (syslog) open
~ ❤️ echo $?
0

UDP端口的检测, 一般我只用在确认iptable的配置时, 提供一个参考, 并不是说这种方式百分百可行. 请一定要认真测试, 并且注意适用场景.

合并两种检查方式

我将两种探测方式写了一个函数, 如果你不想使用上方的failed与success函数, 换成echo即可.

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
# Test is port open
# Usage:
# test_port TCP 1.2.3.4 22
# test_port UDP 1.2.3.4 514
test_port() {
[ $# != 3 ] && return

type=$1
server=$2
port=$3
if [ $type == "TCP" ]; then
nc -z -w5 $server $port
result=$?
else
nc -vz -w5 -u $server $port >> /dev/null 2>&1
result=$?
fi


if [ "$result" != 0 ]; then
failed "$type port $server:$port is closed"
else
success "$type port $server:$port is open"
fi
}