OS X 和 Linux/其他操作系统之间的 ping 超时差异

OS X 和 Linux/其他操作系统之间的 ping 超时差异

我编写的这个函数应该体现了 OSX 和 Linux 命令之间的特性ping,特别是它们的-W超时选项:

# Checks if a host is up-and-running and responding to pings

function my_function_is_network_host_up() {

  local -ri N_ARGUMENTS=1
  if ! check_n_arguments "${FUNCNAME}" "${N_ARGUMENTS}" "${@}"; then return; fi

  local -r NETWORK_HOST=$1

  local -ri n_requests=1

  local -i wait_for_reply=1 # Seconds
  if [[ $my_global_os_type == 'OSX' ]]; then
    ((wait_for_reply *= 1000)) # Milliseconds
  fi

  ping -c "$n_requests" \
       -W "$wait_for_reply" \
       -q \
       "$NETWORK_HOST" \
       &> /dev/null

  return $?

}

真正的系统管理员是否使用更好的 Bash 功能来独立于他们刚刚跳上的机器来检查主机?

我的典型用法:

hs=(...);
for h in "${hs[@]}"; do
    if my_function_is_network_host_up $h; then
        do_stuff
    fi
done

要不就:

my_function_is_network_host_up $h && do_stuff

背景

操作系统X

Time in milliseconds to wait for a reply for each packet sent.  If a reply arrives later, the packet is not printed as replied, but considered as replied when calculating statistics.

Linux

Time to wait for a response, in seconds. The option affects only timeout in absense of any responses, otherwise ping waits for two RTTs.

答案1

我不明白你的功能应该做什么。它比简单的跑步有什么好处

for host in host1 host2 host3; do ping -c 1 host >/dev/null && do_stuff; done

如果您只想知道主机是否已启动,并在启动时运行命令,则上述内容应该足够了。

相关内容