从文件Ping扫描主机名列表,然后使用Cisco APIC Bash将其解析为IP

时间:2019-05-07 03:19:39

标签: shell cisco

我一直在阅读一些通过使用dig, getent, host, and nslookup在Bash脚本中将主机名解析为IP地址的解决方案,不幸的是,这些工具都无法在Cisco APIC bash中将主机名解析为IP地址。

https://unix.stackexchange.com/a/20793/349707

用于此目的的唯一工具是ping

使用此脚本,我能够确定主机是启动还是关闭。但是,我无法在输出中获得IP地址。

user@CiscoAPIC> cat script01.sh
#!/bin/bash
date
cat host.txt |  while read h
do
    ping -c 1 "$h" > /dev/null
    if [ $? -eq 0 ]; then
                echo "$h is up"
    else
                echo "$h is down"
    fi
done
user@CiscoAPIC>

script1.sh的输出

user@CiscoAPIC> ./script1.sh
Mon May  6 10:14:20 UTC 2019
Nexus01 is down
Nexus02 is up
user@CiscoAPIC>

意识到如果我使用> /dev/null不会产生IP,我已经在script2.sh上将其删除了

user@CiscoAPIC> cat script2.sh
#!/bin/bash
date
cat host.txt |  while read h
do
    ping -c 1 "$h"
    if [ $? -eq 0 ]; then
                echo "$h is up"
    else
                echo "$h is down"
    fi
done
user@CiscoAPIC>

不幸的是,有太多不必要的输出。

user@CiscoAPIC> ./script2.sh
Mon May  6 10:15:27 UTC 2019
PING Nexus01 (10.1.1.1) 56(84) bytes of data.

--- Nexus01 ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms

Nexus01 is down
PING Nexus02 (10.1.1.2) 56(84) bytes of data.
64 bytes from Nexus02 (10.1.1.2): icmp_seq=1 ttl=64 time=0.132 ms

--- Nexus02 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.132/0.132/0.132/0.000 ms
Nexus02 is up
user@CiscoAPIC>

然后我添加了| head -1 | cut -d ' ' -f3 | tr -d '()'来删除不必要的内容,但是最终输出不是很好。

user@CiscoAPIC> cat script3.sh
#!/bin/bash
date
cat host.txt |  while read h
do
    ping -c 1 "$h" | head -1 | cut -d ' ' -f3 | tr -d '()'
    if [ $? -eq 0 ]; then
                echo "$h is up"
    else
                echo "$h is down"
    fi
done
user@CiscoAPIC>

script3.sh的输出

user@CiscoAPIC> ./script3.sh
Mon May  6 10:17:42 UTC 2019
10.1.1.1
Nexus01 is down
10.1.1.2
Nexus02 is up
user@CiscoAPIC>

请让我知道最好的解决方案是,仅当其他工具在此特定系统上无法正常工作时,才能使用ping在Bash上获得以下输出。

所需的输出

Mon May  6 10:17:42 UTC 2019

Nexus01 - 10.1.1.1 is down
Nexus02 - 10.1.1.2 is up

1 个答案:

答案 0 :(得分:0)

只需检查ping返回值并将其输出重定向到/ dev / null。

cat host.txt | while read h
do
    if ping -c 1 "$h" >/dev/null; then
                echo "$h is up"
    else
                echo "$h is down"
    fi
done

所有| head -1 | cut -d ' ' -f3 | tr -d '()'都是不必要的-您对输出完全不感兴趣。还请注意,在您的情况下,tr -d '()'(通常,除非设置了bash的pipefail),管道的退出状态通常是最右命令的退出状态。如果您希望退出状态为ping,请仅检查ping。