bash脚本telnet测试多个地址和端口 [英] Bash script telnet to test multiple addresses and ports

查看:265
本文介绍了bash脚本telnet测试多个地址和端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am required to test at least 130 ip addresses and ports. I am hoping to write a bash script such that it reads the ip address and ports from an input file.

我有以下

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

这是一个蹩脚的code,因为它不能确定其是否连接,或者失败了,我不得不依靠其汽车转义字符从连接断开。

This is a crappy code as it cannot determine whether its connected or failed, and I have to rely on its auto escape character to disconnect from a connection.

我怎么能凑合这使得它更新$ 2快速的现状如何?
我工作的RedHat和没有netcat的或预计安装。

How can I improvise this such that it updates $2 with the status quickly? I am working on Redhat and do not have netcat or expect installed..

推荐答案

至于其他stackoverflower的说,我会建议使用的nmap 的netcat 如果即时拍摄。
但是,如果您不能使用这些软件,你可以使用bash的内置的/ dev / TCP /&LT;主机&GT; /&LT;港口方式&gt; 而不是

As other stackoverflower's said, I would recommend using nmap or netcat if avilable. However, if you cannot use those software, you can use bash's builtin /dev/tcp/<host>/<port> instead.

http://www.gnu.org/software/bash/手动/ bashref.html#重定向

我could'nt弄清楚你正在使用bash的版本,但的/ dev / TCP /...似乎因为一些老的bash来实现的。

I could'nt figure out which version of bash you are using, but /dev/tcp/... seems to implemented since some old 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

更新:下面可以做超时。
虽然它似乎有点棘手,想法只是一些超时后杀掉子进程。

UPDATED: The following can do timeout. Although it may seem little tricky, idea is just to kill the child process after some timeout.

<一个href=\"http://stackoverflow.com/questions/5161193/bash-script-that-kills-a-child-process-after-a-given-timeout\">Bash脚本给定超时后杀死一个子进程

#!/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

没有在我的本地网络存在。

since 192.168.100 does not exist in my local network.

这篇关于bash脚本telnet测试多个地址和端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆