需求:
工作中常用到服务器之间需要开通端口,怎样确认端口是否都开通完毕呢? 写一个批量测试端口是否开通的sh脚本,亲测可用
ps:
1. 脚本放到每台服务器上执行
2. 梳理未开通的端口
- 批量 telnet测试端口连通性
addresses=(
10.***.**.11:3306
10.***.**.22:22
10.***.**.22:1521
)
for address in "${addresses[@]}"
do
# 使用 awk 分割地址和端口
ip=$(echo "$address" | awk -F':' '{print $1}')
port=$(echo "$address" | awk -F':' '{print $2}')
echo "Telnetting to $address..."
echo -e "\n"| telnet $ip $port |grep "Connected to\|Escape character" >/dev/null
if [ $? -eq 0 ];then
echo "$ip result $ip $port connected" >>test.log
else
echo "$ip result $ip $port can not Connected" >>test.log
fi
done
日志格式:
知识点补充:
1)$?:表示脚本执行的状态,0表示正常,其他表示错误
2)for 循环使用
3)数组使用
4)echo -e "OK! \n" # -e 开启转义
参考
[1] https://www.runoob.com/linux/linux-shell-echo.html
[2]https://blog.youkuaiyun.com/qq_36326332/article/details/112543884