shell script中使用telnet命令测试TCP端口

  1. 命令行方式
  • TCP端口未打开
[root@bee-a ~]# telnet 127.0.0.1 23
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
  • TCP端口已打开
[root@bee-a ~]# telnet 127.0.0.1 22
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.   <---------使用Ctrl + ]进入 telnet> 提示符状态
SSH-2.0-OpenSSH_7.4
^]
telnet> quit      <-----------使用quit退出 telnet> 提示符状态
Connection closed.
  1. 在shell script中的使用方式
  • TCP端口未打开(refused
[root@bee-a ~]# echo "" | telnet 127.0.0.1 23
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
  • TCP端口已打开(closed
[root@bee-a ~]# echo "" | telnet 127.0.0.1 22
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Connection closed by foreign host.
  • 延迟2秒后退出
[root@bee-a ~]# sleep 2 | telnet 127.0.0.1 22       
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
SSH-2.0-OpenSSH_7.4
Connection closed by foreign host.
  1. 实例
#!/bin/bash

# tcp_port.sh

RESULT=`echo "" | telnet $1 $2 2> /dev/null`
# tcp port is opening:
# Escape character is '^]'.

# tcp port is closed:
# Trying 127.0.0.1...

# RESULT string includes "Escape"
if [[ $RESULT =~ "Escape"  ]]; then
    echo -e "host $1's tcp port $2 is \033[31mopening\033[0m."
else
    # Defect: time consuming
    echo -e "host $1's tcp port $2 is \033[31mclosed\033[0m."
fi

你可能感兴趣的:(运维及自动化)