fix: random changes

main v0.0.4
parent 8ebdb0854d
commit 30b92345b0

@ -1,8 +1,9 @@
package main package main
import ( import (
"bufio"
"fmt" "fmt"
"io" "log"
"net" "net"
"os" "os"
"os/exec" "os/exec"
@ -17,13 +18,14 @@ var commands = map[string]string{
"uptime": `cut -f1 -d. /proc/uptime`, "uptime": `cut -f1 -d. /proc/uptime`,
} }
// ExecuteCommand runs a system command and returns its output // executeCommand runs a system command and returns its output
func ExecuteCommand(command string) string { func executeCommand(command string) string {
cmd := exec.Command("bash", "-c", command) cmd := exec.Command("bash", "-c", command)
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
if err != nil { if err != nil {
return fmt.Sprintf("Error: %s", err) return err.Error()
} }
return string(output) return string(output)
} }
@ -31,20 +33,22 @@ func ExecuteCommand(command string) string {
func handleConnection(conn net.Conn) { func handleConnection(conn net.Conn) {
defer conn.Close() defer conn.Close()
command, err := io.ReadAll(conn) scanner := bufio.NewScanner(conn)
if err != nil { if !scanner.Scan() {
fmt.Println(err) log.Printf("Error reading from %s, %s", conn.RemoteAddr(), scanner.Err())
return return
} }
command := scanner.Text()
cmd, valid := commands[strings.TrimSpace(string(command))] cmd, valid := commands[strings.TrimSpace(string(command))]
if !valid { if !valid {
fmt.Fprintln(conn, "Invalid command") fmt.Fprintln(conn, "invalid command")
return return
} }
stdout := ExecuteCommand(cmd) output := executeCommand(cmd)
fmt.Fprintln(conn, stdout) fmt.Fprintln(conn, output)
} }
func main() { func main() {
@ -60,6 +64,7 @@ func main() {
} }
defer ln.Close() defer ln.Close()
log.Printf("Listening on %s...", host)
for { for {
conn, err := ln.Accept() conn, err := ln.Accept()
if err != nil { if err != nil {
@ -67,6 +72,7 @@ func main() {
continue continue
} }
log.Printf("Connection from %s", conn.RemoteAddr())
go handleConnection(conn) go handleConnection(conn)
} }
} }

Loading…
Cancel
Save