我们可以使用以下命令来测试 telnet VIA 端口;在以下示例中,我们测试端口 6667:
[root@kafka03 ~]# telnet kafka02 6667
Trying 103.64.35.86...
Connected to kafka02.
Escape character is '^]'.
^CConnection closed by foreign host
由于在某些机器上我们无法使用 telnet(出于内部原因),有哪些替代方法可以检查端口(例如 telnet)?
答案1
答案2
如果使用 Bash Shell,那么您可以使用其功能来检查端口是打开还是关闭:
(timeout 1 bash -c '</dev/tcp/127.0.0.1/17500 && echo PORT OPEN || echo PORT CLOSED') 2>/dev/null
PORT OPEN
(timeout 1 bash -c '</dev/tcp/127.0.0.1/7500 && echo PORT OPEN || echo PORT CLOSED') 2>/dev/null
PORT CLOSED
请注意,如果服务器在 1 秒后没有响应,则达到超时,命令之间的命令将'
中断,因此不会打印任何内容。
答案3
“curl”可以让生活更轻松。无需root; curl 可在所有 Linux 系统上轻松使用:
如果端口未打开,将显示以下输出
[niti@SourceServerName ~]$ curl -vv telnet://DestinationServerName:80 * About to connect() to DestinationServerName port 80 (#0) * Trying 192.168.0.100...
如果端口打开将显示以下输出
[niti@SourceServerName ~]$ curl -vv telnet://DestinationServerName:443 * About to connect() to DestinationServerName port 443 (#0) * Trying 192.168.0.100... * Connected to DestinationServerName (192.168.0.100) port 443 (#0)
Ctrl + C退出。
答案4
如果 Perl 是一个选项,您可以使用它IO::Socket
用于测试与特定主机和端口的连接的模块;下面的脚本将 TCP 硬编码为协议(这是 telnet 将使用的协议):
#!/usr/bin/perl -w
# tries to connect to the given IP and port (tcp)
use strict;
use IO::Socket;
my $desthost = shift or die "Usage: $0 host port\n";
my $destport = shift or die "Usage: $0 host port\n";
gethostbyname($desthost) || die "Invalid host given\n";
my $handle = IO::Socket::INET->new(
PeerAddr => $desthost,
PeerPort => $destport,
Proto => 'tcp')
or die "can't connect to $desthost:$destport: $!\n";
close $handle;
print "Success!\n"
关闭端口的输出示例:
$ ./above-script kafka02 6667
can't connect to kafka02:6667: Connection refused
开放端口的输出示例:
$ ./above-script kafka02 4200
Success!