Bash脚本telnet测试多个地址和端口

时间:2014-05-02 06:13:08

标签: bash shell unix telnet firewall

我需要测试至少130个ip地址和端口。 我希望编写一个bash脚本,以便从输入文件中读取ip地址和端口。

我有以下

while read line
do
telnet $line >> $2
done < $1

这是一个糟糕的代码,因为它无法确定它是连接还是失败,我必须依赖其自动转义字符来断开连接。

我怎样才能即兴发布,以便快速更新$ 2状态? 我正在使用Redhat,没有netcat或期望安装..

1 个答案:

答案 0 :(得分:7)

正如其他stackoverflower所说,如果可以使用,我建议使用nmapnetcat。 但是,如果您无法使用这些软件,则可以使用bash的内置/dev/tcp/<host>/<port>代替。

http://www.gnu.org/software/bash/manual/bashref.html#Redirections

我无法弄清楚你正在使用哪种版本的bash,但/dev/tcp/...似乎已经实现了一些旧的bash。

#!/bin/bash
echo "scanme.nmap.org 21
scanme.nmap.org 22
scanme.nmap.org 23
scanme.nmap.org 79
scanme.nmap.org 80
scanme.nmap.org 81" | \
while read host port; do
  r=$(bash -c 'exec 3<> /dev/tcp/'$host'/'$port';echo $?' 2>/dev/null)
  if [ "$r" = "0" ]; then
    echo $host $port is open
  else
    echo $host $port is closed
  fi
done

这会产生

scanme.nmap.org 21 is closed
scanme.nmap.org 22 is open
scanme.nmap.org 23 is closed
scanme.nmap.org 79 is closed
scanme.nmap.org 80 is open
scanme.nmap.org 81 is closed

更新:以下内容可以超时。 虽然看起来有点棘手,但想法是在一些超时后杀死子进程。

Bash script that kills a child process after a given timeout

#!/bin/bash
echo "scanme.nmap.org 80
scanme.nmap.org 81
192.168.0.100 1" | (
  TCP_TIMEOUT=3
  while read host port; do
    (CURPID=$BASHPID;
    (sleep $TCP_TIMEOUT;kill $CURPID) &
    exec 3<> /dev/tcp/$host/$port
    ) 2>/dev/null
    case $? in
    0)
      echo $host $port is open;;
    1)
      echo $host $port is closed;;
    143) # killed by SIGTERM
       echo $host $port timeouted;;
     esac
  done
  ) 2>/dev/null # avoid bash message "Terminated ..."

这会产生

scanme.nmap.org 80 is open
scanme.nmap.org 81 is closed
192.168.0.100 1 timeouted

因为我的本地网络中不存在192.168.100。