linux批量查询端口是否开通
业务需求:进行新老机器系统切换时,需要验证各个业务系统的端口连通性
分析:当系统对接业务系统过多时,手动验证会花费大量时间,且不方便存储,因此,编写批量程序
代码:
#!/bin/bash
# 检查端口是否可用
function check_port() {
local hosts=$1
local ports=$2
local name=$3
# 使用 IFS 分割字符串
IFS="," read -ra hostArray <<< "$hosts"
IFS="," read -ra array <<< "$ports"
# 使用 for 循环遍历每个机器信息
for host in "${hostArray[@]}"; do
# 使用 for 循环遍历每个子字符串
for port in "${array[@]}"; do
#开始
#local command="ping -c 1 $host > /dev/null && nc -zvw3 $host $port"
local command="nc -zvw3 $host $port"
if eval "$command"; then
echo "$name $host $port 联通成功"
else
echo "$name $host $port 联通失败"
fi
done
done
}
# 获取远程主机列表及其端口列表,按组区分,组内按逗号分隔
remote_hosts=("192.168.1.125" "192.168.1.126,192.168.1.127" )
remote_names=("邮件服务服务器" "redis")
remote_ports=("80,443" "26379")
echo "目标服务器名称 目标IP 端口 联通测试"
# 检查每个远程主机的每个端口是否可用
for ((i=0; i<${#remote_hosts[@]}; i++)); do
remote_host=${remote_hosts[i]}
remote_port=${remote_ports[i]}
remote_name=${remote_names[i]}
#echo "----------- 验证:${remote_names[i]}机器:${remote_host}端口:${remote_port}是否可用 -----------"
check_port $remote_host $remote_port $remote_name
done