繁体   English   中英

从Bash脚本未知主机Ping

[英]Ping from bash-script unknown host

我有一个充满主机名的文件-每行一个。 现在,我想检查这些主机名是否存在(如果不存在,请最终从文件中删除它们)。 我已经在第一部分失败了:

#!/bin/bash
while read host; do
  ping -c1 "$host"
done <hosts

只给我

ping: unknown host google.com

(将google.com放在文件中进行测试)我也尝试删除了引号-无效。 但是,从终端运行命令时,我得到的是:

 $ ping -c1 "google.com"
   PING google.com (173.194.112.100) 56(84) bytes of data.
   ...

这里有什么问题?

您的hosts文件很可能是DOS行尾格式(CR-LF行尾),因此read使用google.com\\r read fills变量。

最简单的方法是将文件转换为使用dos2unix hosts UNIX行结尾。

我试图做同样的事情,最终得到了这个脚本,您可能会发现它很好并且有用。 仍在努力尝试识别“ ping:未知主机hostname.co.hk​​”,但这没关系。

    #!/bin/bash 
    cat list | while read domains; do
                reply=$(ping -c 1 $domains| grep -E '(from)' | wc -l)
                if [ $reply == 1 ]; then
                        DOMAIN=$(ping -c 1 $domains |grep 64 |awk '{print$4}')
                        IP=$(ping -c 1 $domains | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}" | head -1)
                        echo "$domains -> $DOMAIN -> $IP" >> ping.log;echo "$domains -> $DOMAIN -> $IP"
                else
                        echo "-----------------ping failed, verify domain name"
                fi 
done 
cat ping.log

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM