-1

I am just trying to run an nmap scan on my system using Go with below main function

func main() {

execErr := exec.Command("cmd","/c","nmap -T4 -A -v localhost")
if execErr != nil {
panic(execErr)
}

}

Its panicking. I tried to search documentation online but could not find anything helpful for windows yet. Can someone help or point to some resources?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Neo
  • 13
  • 5

1 Answers1

2

exec.Command() does not return an error but *Cmd type struct on which you then can call a method Run() (or other methods, see NOTE below) to execute the command like this:

cmd := exec.Command("cmd","/c","nmap -T4 -A -v localhost")
err := cmd.Run()
if execErr != nil {
    log.Fatal(err)
}

Your code panics because exec.Command("cmd","/c","nmap -T4 -A -v localhost") returns a valid non-nil pointer to Cmd struct (panic message is likely full path to the cmd.exe and then arguments you provided which are values of fields Path and Args of Cmd struct...).

NOTE: It is not good practice to panic() here, use log.Fatal() instead. Also it might be better to run nmap directly and process its output in code. See examples of reading other command output using Output(), CombinedOutput() and Start() depending on what you are trying to do and how command behaves.

blami
  • 6,588
  • 2
  • 23
  • 31
  • Thank you for your response. I am trying to build an nmap scanner using golang where I take user input from an HTML form in a text box and run the nmap scan for that host/IP `cmd,err := exec.Command(`C:\Program Files (x86)\Nmap\nmap.exe`, "nmap -T4 -A -v localhost").Output() if err != nil { log.Fatal(err) } fmt.Printf("The output is %s\n", cmd) }` This code gives the below output `The output is Starting Nmap 7.91 ( https://nmap.org ) at 2021-01-17 22:21 Eastern Standard Time` It starts but doesnt wait to complete – Neo Jan 18 '21 at 03:26
  • I tried using `run()` as the alternative but that doesnt give any output at all – Neo Jan 18 '21 at 03:28
  • 1
    I believe you have nmap twice in your commandline so nmap fails to parse arguments and outputs error on stderr which you don't see because `Output()` only captures standard out (but not err) of the process. Your invocation should be `exec.Command("path\to\nmap.exe", "-T4 -A..."). I am not familiar with `nmap` at all but if it is somehow interactive process you'll probably have to attach to it's `std*` pipes using `Cmd.Std*Pipe()` functions. See the docs I linked in my reply, it's all there. – blami Jan 18 '21 at 03:52