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

问题描述 投票:2回答:1

我需要至少测试130个的IP地址和端口。我希望写一个bash脚本,使得它读取输入文件中的IP地址和端口。

我有以下

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

这是一个蹩脚的代码,因为它不能确定其是否连接或失败,我不得不依靠它的自动转义字符从连接断开。

我怎么能凑合这使得它更新$ 2快的状态?我的工作在RedHat和没有netcat的或期望安装..

bash shell unix telnet firewall
1个回答
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并不在我的本地网络存在。

© www.soinside.com 2019 - 2024. All rights reserved.