Skip to content

Instantly share code, notes, and snippets.

@ismits
Last active May 12, 2017 21:13
Show Gist options
  • Save ismits/1ec5136d532c6a44332db1672d786e47 to your computer and use it in GitHub Desktop.
Save ismits/1ec5136d532c6a44332db1672d786e47 to your computer and use it in GitHub Desktop.
Ping a remote host in groovy
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class Ping
{
public static Boolean isReachable(String hostname) {
Logger logger = LoggerFactory.getLogger('com.example.utils.system.ping')
logger.debug("[Ping.isReachable] isReachable called with hostname: {}", hostname)
if (! hostname?.trim()) {
logger.lifecycle("[Ping.isReachable] hostname is null or empty.")
return false
}
String pingargs = (System.properties['os.name'].toLowerCase().contains('windows')) ? '-n 4' : '-c 4'
logger.debug("[Ping.isReachable] ping args are [{}]", pingargs)
logger.lifecycle("[Ping.isReachable] Pinging {}...", hostname)
String response = "ping ${hostname} ${pingargs}".execute().text
Boolean isAlive = false
logger.debug("[Ping.isReachable] Ping response is:\n{}", response)
response.eachLine() { line ->
if (line.startsWith('Reply from') || line.startsWith('64 bytes from')) {
isAlive = true
}
}
return isAlive
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment