命令

可使用命令包括但不限以下:curl, ssh, nmap, telnet,nc

测试代码以 opcai.top 443 端口为例。

目的

  • 找到一种更通用的能在几乎所有环境下完成检查的方法
  • 找到一种更稳定的几乎不会判断出错的方法

示例

nmap

缺点:

  • 一般需要额外安装
  • 某些检测方法需要 sudo 权限

优点:

  • 判断更为准确

输出文本

nmap -p443 opcai.top
Starting Nmap 6.40 ( http://nmap.org ) at 2020-03-09 09:58 CST
Nmap scan report for opcai.top (180.97.125.228)
Host is up (0.026s latency).
PORT    STATE SERVICE
443/tcp open  https

Nmap done: 1 IP address (1 host up) scanned in 0.10 seconds

判断命令

nmap -p443 opcai.top | grep "^443/tcp.*open"

注:如果有可能,使用 sudo 权限执行可以使 namp 在更多情况下准确地判断端口状态。

telnet

缺点:

  • 可能需要额外安装
  • 一些情况下无法正常断开连接

优点:

  • 可能不需要额外安装

输出文本

telnet opcai.top 443
Trying 180.97.125.228... 
Connected to opcai.top.
Escape character is '^]'.
HTTP/1.1 400 Bad Request
Server: stgw/1.3.12_1.13.5
Date: Mon, 09 Mar 2020 02:06:41 GMT
Content-Type: text/html
Content-Length: 179
Connection: close

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>stgw/1.3.12_1.13.5</center>
</body>
</html>
Connection closed by foreign host.

判断命令

echo -e '\n' | telnet opcai.top 443 | grep "Connected to"

ssh

缺点:

  • 可能因配置文件设置而使判断失败(如设置代理)

优点:

  • 通用,几乎所有 Linux 环境都默认安装该命令

输出文本

ssh -v -p 443 opcai.top
OpenSSH_7.4p1, OpenSSL 1.0.2k-fips  26 Jan 2017
... 
debug1: /home/pysense/.ssh/config line 2: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 58: Applying options for *
debug1: Connecting to opcai.top [180.97.125.228] port 443.
debug1: Connection established.
... 

判断命令

ssh -v -p 443 opcai.top 2>&1 | grep "Connection established"

nc

缺点:

  • 需要额外安装
  • -z 参数在早期版本不支持(如 6.40)

优点:

*功能强大

输出文本

nc -t opcai.top 443
get
HTTP/1.1 400 Bad Request
Server: stgw/1.3.12_1.13.5
Date: Tue, 10 Mar 2020 02:10:06 GMT
Content-Type: text/html
Content-Length: 179
Connection: close

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>stgw/1.3.12_1.13.5</center>
</body>
</html>

测试命令

nc -z -w 3 opcai.top 443 && echo ok || echo not ok