检查服务器是否在没有 telnet 的情况下从 CLI 进行侦听?

And*_*e M 3 linux osx telnet

通常,检查应用程序服务器是否正在运行的简单诊断方法是再次在主机和端口上运行 telnet:

\n\n
telnet somehost port\n
Run Code Online (Sandbox Code Playgroud)\n\n

问题是,某些操作系统(例如 macOS)现在默认使该工具不可用。因此,我不想尝试了解如何安装 telnet,而是想知道是否有其他 CLI 方法来检查服务器是否正在侦听,而不需要特殊权限?

\n\n

澄清一下,我正在寻找在任何系统上都可以像 telnet 一样快速使用的解决方案,只需 5 秒即可实现。编写解决方案并不能真正提供快速访问方法。

\n

Rom*_*nov 6

您可以尝试多种方法来检查是否有某些内容侦听特定端口:

wget/curl

wget your_IP:port
Run Code Online (Sandbox Code Playgroud)

netstat

netstat -an|grep LISTEN|grep :port
Run Code Online (Sandbox Code Playgroud)

lsof

lsof -i :port
Run Code Online (Sandbox Code Playgroud)

netcat

nc -vz your_IP port
Run Code Online (Sandbox Code Playgroud)

使用/proc文件系统(可能仅适用于 Linux)(此处解释

ss

ss|grep LISTEN|grep :port
Run Code Online (Sandbox Code Playgroud)

nmap

nmap -sS -O -pport your_IP
Run Code Online (Sandbox Code Playgroud)

EDIT1另外(几乎)每个 ssh、http、ftp 客户端都可以使用,但有时很难理解端口是否被防火墙关闭或不可用。
EDIT2在此 Q/A示例中找到使用catecho完成工作的方法:

true &>/dev/null </dev/tcp/127.0.0.1/$PORT && echo open || echo closed
Run Code Online (Sandbox Code Playgroud)

或仅使用exec命令(如果您没有看到错误端口已打开):

exec 6<>/dev/tcp/your_IP/port
Run Code Online (Sandbox Code Playgroud)

我找到了一种仅用于awk完成这项工作的方法(原文在这里):

awk -v port=your_port 'function hextodec(str,ret,n,i,k,c){
    ret = 0
    n = length(str)
    for (i = 1; i <= n; i++) {
        c = tolower(substr(str, i, 1))
        k = index("123456789abcdef", c)
        ret = ret * 16 + k
    }
    return ret
}
function getIP(str,ret){
    ret=hextodec(substr(str,index(str,":")-2,2)); 
    for (i=5; i>0; i-=2) {
        ret = ret"."hextodec(substr(str,i,2))
    }
    ret = ret":"hextodec(substr(str,index(str,":")+1,4))
    return ret
} 
NR > 1 {{local=getIP($2);remote=getIP($3) }{ if (remote ~ "0:0" && local ~ ":"port) print local}}' /proc/net/tcp 
Run Code Online (Sandbox Code Playgroud)

EDIT3正如评论中提到的一些方法,特别是基于/dev文件系统的方法可能会在您的环境中工作

EDIT4对于 Solaris,我发现了很好的 Q/A,用于pfiles获取开放端口。

  • 不,我的意思是它完全是 bash 内部的,只有 bash 及其内置命令才能使用这些路径。将 `cat &lt;/dev/tcp/localhost/smtp` 与 `cat /dev/tcp/localhost/smtp` 进行比较 (2认同)