telnet来确定开放端口(shell脚本)

时间:2014-07-28 20:45:04

标签: linux bash telnet rhel

我正在尝试编写一个shell脚本,它将IP地址和端口号作为输入,并输出端口是否在主机上打开。我的shell脚本看起来像这样

#!/bin/bash

name=$(echo exit | telnet $1 $2 | grep "Connected")

if [ "$name" == "" ]
then
    echo "Port $2 is not open on $1"
else
    echo "Port $2 is open on $1"
fi

它工作正常,但我的输出包含2行,如下所示:

[root@ip-172-31-8-36 Scripts]# ./test.sh 172.31.35.246 7199
Connection closed by foreign host.
Port 7199 is open on 172.31.35.246

OR

[root@ip-172-31-8-36 Scripts]# ./test.sh 172.31.35.246 7200
telnet: connect to address 172.31.35.246: Connection refused
Port 7200 is not open on 172.31.35.246

我想在两种情况下都抑制输出的第一行。 知道怎么做吗?

3 个答案:

答案 0 :(得分:3)

telnet的错误输出直接发送到/dev/null

name=$(echo exit | telnet $1 $2 2>/dev/null | grep "Connected")

答案 1 :(得分:3)

穷人的nmap纯粹的狂欢:

host="127.0.0.1"
for port in {1..1024}
do
    echo "" > /dev/tcp/$host/$port && echo "Port $port is open"
done 2>/dev/null

答案 2 :(得分:1)

如何使用netcat呢?

$ nc -v -z <host> <port> Connection to <host> <port> port [tcp/https] succeeded!