首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Linux telnet shell脚本

Linux telnet shell脚本
EN

Stack Overflow用户
提问于 2019-05-21 11:54:37
回答 2查看 541关注 0票数 1

我正在尝试从一个文本文件(ip.txt)中读取多个主机和端口,并检查它们是否已连接/连接失败/超时,并回显对Telnet_Success.txt/Telnet_Failure.txt/Telnet_Refused.txt文件的响应

我已经尝试了以下脚本,它只是简单地显示所有连接结果为失败,但当手动逐个检查时,我发现其中一些连接。任何帮助都是非常感谢的。下面是脚本:

代码语言:javascript
复制
>Telnet_Success.txt
>Telnet_Refused.txt
>Telnet_Failure.txt
file=ip.txt
while read line ; do
  ip=$( echo "$line" |cut -d ' ' -f1 )
  port=$( echo "$line" |cut -d ' ' -f2 )
  if telnet -c $ip $port </dev/null 2>&1 | grep -q Escape; then
  echo "$ip $port Connected" >> Telnet_Success.txt
  elif telnet -c $ip $port </dev/null 2>&1 | grep -q refused; then
  echo "$ip $port Refused" >> Telnet_Refused.txt
  else
  echo "$ip $port Failed" >> Telnet_Failure.txt
  fi
 done < ${file}
EN

回答 2

Stack Overflow用户

发布于 2019-05-30 17:45:12

我不能从您提供的诊断中确切地告诉您失败的是什么,但这肯定是一个问题,您尝试多次调用telnet -您可能每次都会得到不同的结果,从而产生难以排除的错误。您的代码中还存在一些样式问题。

尝试这种重构;请参阅内联注释。

代码语言:javascript
复制
>Telnet_Success.txt
>Telnet_Refused.txt
>Telnet_Failure.txt
# Why use a variable for something you only reference once anyway?
file=ip.txt
# Use the shell's field splitting facility
# Cope with missing final newline; see
# https://mywiki.wooledge.org/BashFAQ/001#My_text_files_are_broken.21__They_lack_their_final_newlines.21
while read -r ip port _ || [[ -n $port ]]; do
  # Run telnet once, capture result for analysis 
  output=$(telnet -c "$ip" "$port" </dev/null 2>&1)
  case $output in
    *Escape*)
        echo "$ip $port Connected" >> Telnet_Success.txt;;
  *refused*)
        echo "$ip $port Refused" >> Telnet_Refused.txt;;
  *)
        echo "$ip $port Failed" >> Telnet_Failure.txt;;
  esac
# Always double quote file name variables, just in case
done < "${file}"
票数 1
EN

Stack Overflow用户

发布于 2019-05-21 14:58:57

Hi看起来telnet命令是罪魁祸首应该是"telnet ip port“而不是"telnet -c ip port”

代码语言:javascript
复制
file=ip.txt
while read line
do
  ip=$( echo "$line" |cut -d ' ' -f1 )
  port=$( echo "$line" |cut -d ' ' -f2 )
  if  telnet  $ip $port </dev/null 2>&1 | grep -q Escape 
  then  
    echo "$ip $port Connected" >> Telnet_Success.txt
  elif  telnet  $ip $port </dev/null 2>&1 | grep -q refused 
  then
    echo "$ip $port Refused" >> Telnet_Refused.txt
  else
    echo "$ip $port Failed" >> Telnet_Failure.txt
  fi
done < ${file}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56230852

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档