Millet Porridge

English version of https://corvo.myseu.cn

0%

Some Bash Tricks (II)

Printing colored logs in bash

Mainly using ascii color characters; the colored LOG effect can basically be achieved:

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 $@
}


# check whether port 22 is open
type=TCP
server=127.0.0.1
port=22
nc -z -w5 $server $port
result=$?

# print different colors for different results
if [ "$result" != 0 ]; then
failed "$type port $server:$port is closed"
else
success "$type port $server:$port is open"
fi

Checking Whether Specific TCP and UDP Ports Are Open

TCP port check

  1. Using 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. Using 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 port detection

Please note: the UDP protocol differs from TCP — even if an application listens on the port, a successful probe is not guaranteed.

Using 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

For UDP port detection, I generally only use it as a reference when confirming iptables configuration; this method is not 100% reliable. Please test carefully and mind the applicable scenarios.

Combining the Two Check Methods

I wrote the two probing methods into one function. If you don’t want to use the failed and success functions above, just replace them with 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
}