host_check/host_check.go

75 lines
2.1 KiB
Go

package main
import (
"fmt"
"net"
"os"
"os/exec"
"strings"
)
func main() {
hostnames := os.Getenv("HOSTNAMES")
if hostnames == "" {
fmt.Println("Error: Environment variable HOSTNAMES not set or empty.")
return
}
hosts := strings.Split(hostnames, ",")
// Environment Variables
failOnError := os.Getenv("FAIL_ON_ERROR") == "true"
commandStr := os.Getenv("COMMAND")
errorCommandStr := os.Getenv("ERROR_COMMAND")
for _, host := range hosts {
host = strings.TrimSpace(host)
fmt.Println("\n---", host, "---")
// DNS Resolution (Remove if you don't need this)
ip, err := net.LookupIP(host)
if err != nil {
fmt.Println("DNS Resolution Failed:", err)
} else {
fmt.Println("Resolved IPs:", ip)
}
// Ping
pingCmd := exec.Command("ping", "-c", "3", host)
pingOutput, err := pingCmd.Output()
if err != nil {
fmt.Println("Ping Failed:", err)
if failOnError {
os.Exit(1)
}
// Execute error command if specified
if errorCommandStr != "" {
cmdParts := strings.Fields(errorCommandStr)
cmd := exec.Command(cmdParts[0], cmdParts[1:]...)
cmdOutput, cmdErr := cmd.Output()
if cmdErr != nil {
fmt.Println("Error Command Execution Failed:", errorCommandStr, cmdErr)
} else {
fmt.Println("Error Command Output:\n", string(cmdOutput))
}
}
} else {
fmt.Println("Ping Output:\n", string(pingOutput))
}
// Execute additional command if specified
if commandStr != "" {
cmdParts := strings.Fields(commandStr)
cmd := exec.Command(cmdParts[0], cmdParts[1:]...)
cmdOutput, err := cmd.Output()
if err != nil {
fmt.Println("Command Execution Failed:", commandStr, err)
} else {
fmt.Println("Command Output:\n", string(cmdOutput))
}
}
}
}