工作中会遇到验证到某某服务器端口是否连通,如果IP或端口多时,用shell还是很省时省力的,看下面的脚本:
#!/bin/bash # #database check #set -o nounset LOCALIP=`ifconfig | grep inet | head -1 | awk '{print $2}' | sed 's/addr://'` IPLIST='192.168.161.234
192.168.161.235
192.168.161.22
' PORTLIST='1521 1522 1523 1524 1525 1526 1527 1528 1529 1530' check_nc(){ for CHECK_IP in $IPLIST do for CHECK_PORT in $PORTLIST do nc -nz -w 1 $CHECK_IP $CHECK_PORT if [ $? -eq 0 ];then echo "$LOCALIP result $CHECK_IP $CHECK_PORT Connected" else echo "$LOCALIP result $CHECK_IP $CHECK_PORT Noconnected" fi done done } check_nc_7(){ for CHECK_IP in $IPLIST do for CHECK_PORT in $PORTLIST do nc -n -w 1 $CHECK_IP $CHECK_PORT < /dev/null if [ $? -eq 0 ];then echo "$LOCALIP result $CHECK_IP $CHECK_PORT Connected" else echo "$LOCALIP result $CHECK_IP $CHECK_PORT Noconnected" fi done done } check_telnet(){ for CHECK_IP in $IPLIST do for CHECK_PORT in $PORTLIST do echo -e " "| telnet $CHECK_IP $CHECK_PORT | grep Connected
if [ $? -eq 0 ];then echo "$LOCALIP result $CHECK_IP $CHECK_PORT Noconnected" else echo "$LOCALIP result $CHECK_IP $CHECK_PORT Connected" fi done done } echo "--------------------------------------" echo "execution time : `date`" echo "--------------------------------------" echo "Home ip : $LOCALIP" echo "--------------------------------------" which nc > /dev/null if [ $? -eq 0 ];then echo "------------------nc------------------" echo "--------------------------------------" cat /etc/redhat-release |grep 'release 7' > /dev/null if [ $? -eq 0 ];then check_nc_7 else check_nc fi else which telnet > /dev/null if [ $? -eq 0 ];then echo "-----------------telnet----------------" check_telnet fi fi
此脚本考虑了nc及telnet命令,及nc在redhat 7中应用的不同。可以直接复制使用,只要修改一下IP和端口。