chore: better io handling and minor style enhancements

main v0.0.3
parent 3113a10e0c
commit 8ebdb0854d

@ -1,13 +1,22 @@
package main package main
import ( import (
"bufio"
"fmt" "fmt"
"io"
"net" "net"
"os" "os"
"os/exec" "os/exec"
"strings"
) )
var commands = map[string]string{
"cpu": `top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | sed "s/^/100 - /" | bc`,
"memory": `free -m | awk '/Mem/{print $3 " " $2}'`,
"network": `cat /sys/class/net/[e]*/statistics/{r,t}x_bytes`,
"storage": `df -Ph | grep mmcblk0p5 | awk '{print $2 " " $3}' | sed 's/G//g'`,
"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)
@ -18,34 +27,33 @@ func ExecuteCommand(command string) string {
return string(output) return string(output)
} }
// handleConnection handles one command per connection
func handleConnection(conn net.Conn) { func handleConnection(conn net.Conn) {
defer conn.Close() defer conn.Close()
scanner := bufio.NewScanner(conn) command, err := io.ReadAll(conn)
for scanner.Scan() { if err != nil {
command := scanner.Text() fmt.Println(err)
return
}
switch command { cmd, valid := commands[strings.TrimSpace(string(command))]
case "cpu": if !valid {
fmt.Fprintln(conn, ExecuteCommand("top -bn1 | grep \"Cpu(s)\" | sed \"s/.*, *\\([0-9.]*\\)%* id.*/\\1/\" | sed \"s/^/100 - /\" | bc")) fmt.Fprintln(conn, "Invalid command")
case "memory": return
fmt.Fprintln(conn, ExecuteCommand("free -m | awk '/Mem/{print $3\" \"$2}'"))
case "network":
fmt.Fprintln(conn, ExecuteCommand("cat /sys/class/net/[e]*/statistics/{r,t}x_bytes"))
case "storage":
fmt.Fprintln(conn, ExecuteCommand("df -Ph | grep mmcblk0p5 | awk '{print $2\" \"$3}' | sed 's/G//g'"))
case "uptime":
fmt.Fprintln(conn, ExecuteCommand("cut -f1 -d. /proc/uptime"))
case "exit":
return
default:
fmt.Fprintln(conn, "Invalid command")
}
} }
stdout := ExecuteCommand(cmd)
fmt.Fprintln(conn, stdout)
} }
func main() { func main() {
ln, err := net.Listen("tcp", ":12345") host, ok := os.LookupEnv("HOST")
if !ok {
host = ":12345"
}
ln, err := net.Listen("tcp", host)
if err != nil { if err != nil {
fmt.Println("Error:", err) fmt.Println("Error:", err)
os.Exit(1) os.Exit(1)

Loading…
Cancel
Save