What is the best way to map windows drives using golang?

3k views Asked by At

What is the best way to map a network share to a windows drive using go-lang? This share also requires a username and password. A similar question was asked for python What is the best way to map windows drives using Python?

1

There are 1 answers

0
Kiril On BEST ANSWER

As of now there is no direct way to do that in Go; I would recommend using net use, which of course limits the functionality to Windows, but that's actually what you need.

So, when you open a command prompt in Windows you can map network shares to Windows drives by using:

net use Q: \\SERVER\SHARE /user:Alice pa$$word /P

Q: represents your windows drive, \\SERVER\SHARE is the network address, /user:Alice pa$$word are your credentials, and /P is for persistence.

Executing this in Go would look something like:

func mapDrive(letter string, address string, user string, pw string) ([]byte, error) {
  // return combined output for std and err
  return exec.Command("net use", letter, address, fmt.Sprintf("/user:%s", user), pw, "/P").CombinedOutput()
}

func main() {
  out, err := mapDrive("Q:", `\\SERVER\SHARE`, "Alice", "pa$$word")
  if err != nil {
    log.Fatal(err)
  }
  // print whatever comes out
  log.Println(string(out))
}