Skip to content

Instantly share code, notes, and snippets.

@paul-d-ray
Created May 21, 2025 03:57
Show Gist options
  • Save paul-d-ray/8d8f0675936b4c7cf76d5a12d56c5b93 to your computer and use it in GitHub Desktop.
Save paul-d-ray/8d8f0675936b4c7cf76d5a12d56c5b93 to your computer and use it in GitHub Desktop.
Ping a list of hosts

Ping a list of hosts

Tested under Windows (I used Windows). Should work under Unix like systems (not tested).

# PR 2025-05-20 23:33:44
# Manual with some help from Grok 3 for Unix style ping
# from discord about ping
# https://discord.com/channels/601130461678272522/615253963645911060/threads/1374058672120135813


# Ping a list of hosts (from argument or pipe) and return results in a table; use -1 for time if host cannot be pinged
# Detects Windows vs. Unix-like (Linux/macOS/BSD) for appropriate ping command
def ping-host [hosts: list<string> = []] {
  let input_hosts = if ($in | is-not-empty) { $in } else { $hosts }
  let is_windows = ($nu.os-info.family == "windows")
  let results = ($input_hosts | each { |host|
    let ping_output = if $is_windows {
      (^ping $host -n 1 | find "reply" -i | ansi strip)
    } else {
      (^ping $host -c 1 | find "from" -i | ansi strip)
    }
    if ($ping_output | is-empty) {
      { hostname: $host, ip: "none", time: -1 }
    } else {
      let parsed = if $is_windows {
        ($ping_output | parse "Reply from {ip} time{time}")
      } else {
        ($ping_output | parse "from {ip}: icmp_seq={seq} ttl={ttl} time={time} ms")
      }
      let ip = ($parsed | get -i 0.ip)
      let time = ($parsed | get -i 0.time)
      {
        hostname: $host,
        ip: ($ip | if $in == null { "none" } else { $in }),
        time: ($time | if $in == null { -1 } else {
          $in | str replace "=" "" | str replace "ms" "" | into float | into int
        })
      }
    }
  })
  $results | table
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment