检测指定主机的某些端口是否处于监听状态
#!/bin/bash
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # 无颜色
# 指定要检查的目标主机
read -p "请输入目标主机IP地址(default:127.0.0.1): " host
if [ -z $host ];then
host=${host:-127.0.0.1}
fi
# 指定要检查的端口数组
read -p "请输入需要检测的端口,用空格分隔.(default:22 80 6379 3306 1884): " -a ports
ports=(${ports[@]:-22 80 3306 6379 1884})
# 检查端口是否开放的函数
check_port() {
(echo > /dev/tcp/$1/$2) > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo -e "${GREEN}Port $2 on host $1 is open${NC}"
else
echo -e "${RED}Port $2 on host $1 is closed${NC}"
fi
}
# 遍历指定的端口数组
for port in "${ports[@]}"; do
check_port $host $port
done