如何从动态变量ping地址?

时间:2018-09-25 18:27:00

标签: bash eval ping

我想使用动态名称ping for loop。 当我尝试ping -c1 -w1 10.0.0.10 > /dev/null时,它可以很好地工作,但是当我尝试将静态地址更改为动态地址时,会出现错误。

declare -A array=([piotr_pc]=10.0.0.10 )

for item in ${!array[*]}
do
    file=$(grep $item homesystem/web/openvpn-status.log | tr 'm\n' 'p,')
    IFS=','
    for x in $file
    do          
        eval $item+=\("$x"\)
    done

    eval echo \${$item[9]}

    if ping -c1 -w1 eval echo \${$item[9]} > /dev/null; then
        echo eval echo \${$item[9]} "ONLINE" $NOW
        echo "UPDATE openvpn SET status='ONLINE', last_online='$NOW' , Common Name = '${piotr_pc[0]}', Real Address = '${piotr_pc[1]}', Bytes Received = '${piotr_pc[2]}', Bytes Sent = '${piotr_pc[3]}', Connected Since = '${piotr_pc[4]}', Virtual Address = '${piotr_pc[5]}' , Last Ref = '${piotr_pc[8]}' WHERE ip_vpn='${piotr_pc[5]}'"
        #mysql -uphptest -pphphaslo openwrt -e "UPDATE openvpn SET status='ONLINE', last_online='$NOW'  WHERE ip_vpn='$ip'"
    else
        eval echo \${$item[9]} "OFFLINE"
        #mysql -uphptest -pphphaslo openwrt -e "UPDATE openvpn SET status='OFFLINE' WHERE ip_vpn='$ip'"
    fi
done

结果:

root@VigoradoNetwork:/www1# ./ping.sh
10.0.0.10
BusyBox v1.28.3 () multi-call binary.

Usage: ping [OPTIONS] HOST

Send ICMP ECHO_REQUEST packets to network hosts

        -4,-6           Force IP or IPv6 name resolution
        -c CNT          Send only CNT pings
        -s SIZE         Send SIZE data bytes in packets (default 56)
        -t TTL          Set TTL
        -I IFACE/IP     Source interface or IP address
        -W SEC          Seconds to wait for the first response (default 10)
                        (after all -c CNT packets are sent)
        -w SEC          Seconds until ping exits (default:infinite)
                        (can exit earlier with -c CNT)
        -q              Quiet, only display output at start
                        and when finished
        -p HEXBYTE      Pattern to use for payload
10.0.0.10 OFFLINE

我想用10.0.0.10来更改此eval echo \${$item[9]},但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

我不确定我是否正确理解了您,但是如果您正在使用主机列表文件对主机进行多次ping操作,则以下内容可能会有所帮助。

#!/bin/bash
echo "`date` Starting the Ping Check...."

function pingHost () {
    hostTarget=${1}
    # send stdout/stderr to /dev/null since all we need is the return code
    ping -c2 ${hostTarget} >/dev/null 2>&1 &&
    echo Host ${hostTarget} is SUCCESS||
    echo Host ${hostTarget} is FAILED
}

data=$(<my_hostlist)  # Place your hostlist here example "Master_hostlist"
for line in ${data}
do
    # call our function and place the call in the background
    pingHost ${line} &
done
# wait for all outstanding background jobs to complete before continuing
wait
# [optional] let operator know we're done.
echo "Completed @=> `date`"