112 lines
2.1 KiB
Go
112 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"flag"
|
|
"os"
|
|
"syscall"
|
|
"strings"
|
|
"net"
|
|
"regexp"
|
|
)
|
|
|
|
// Option to parse
|
|
var (
|
|
HELP = flag.Bool("help", false, "print the help message")
|
|
IP = flag.String("ip", "", "ip expected")
|
|
FILE = flag.String("file", "", "path file expected")
|
|
COMMAND = flag.String("command", "", "command to execute")
|
|
NOT = flag.Bool("not", false, "execute the command if the ip or the file isn't present")
|
|
)
|
|
|
|
// Critical print a message and exit with code 2
|
|
func Critical(msg string) {
|
|
fmt.Println(fmt.Sprintf("CRITICAL - %s", msg))
|
|
os.Exit(2)
|
|
}
|
|
|
|
// Warning print a message and exit with code 1
|
|
func Warning(msg string) {
|
|
fmt.Println(fmt.Sprintf("WARNING - %s", msg))
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Ok print a message and exit with code 0
|
|
func Ok(msg string) {
|
|
fmt.Println(fmt.Sprintf("OK - %s", msg))
|
|
os.Exit(0)
|
|
}
|
|
|
|
func init() {
|
|
flag.Parse()
|
|
|
|
if *HELP {
|
|
flag.PrintDefaults()
|
|
os.Exit(3)
|
|
}
|
|
|
|
if *IP == "" && *FILE == "" {
|
|
Critical("Please set file or ip option")
|
|
}
|
|
|
|
if *COMMAND == "" {
|
|
Critical("Please set command option")
|
|
}
|
|
}
|
|
|
|
// fileExist return true if the file exist
|
|
func fileExist(path string) bool {
|
|
_, err := os.Stat(*FILE)
|
|
if err == nil {
|
|
return true
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// ipExist return true if an interface has the ip
|
|
func ipExist(ip string) bool {
|
|
r := regexp.MustCompile(`^(.*)/\d{1,2}$`)
|
|
|
|
ifaces, _ := net.Interfaces()
|
|
for _, i := range ifaces {
|
|
addrs, _ := i.Addrs()
|
|
for _, addr := range addrs {
|
|
match := r.FindSubmatch([]byte(fmt.Sprintf("%s", addr)))
|
|
if len(match) == 0 {
|
|
continue
|
|
}
|
|
|
|
if string(match[1]) == ip {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
func main() {
|
|
var execute bool
|
|
|
|
if *FILE != "" {
|
|
execute = fileExist(*FILE)
|
|
} else {
|
|
execute = ipExist(*IP)
|
|
}
|
|
|
|
if *NOT {
|
|
if execute {
|
|
execute = false
|
|
} else {
|
|
execute = true
|
|
}
|
|
}
|
|
|
|
if execute {
|
|
Ok("I have nothing to do, i going to sleep")
|
|
}
|
|
|
|
command := strings.Split(*COMMAND, " ")
|
|
syscall.Exec(command[0], command, []string{})
|
|
}
|