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

落花浮王杯 提交于 2019-12-12 17:17:31

问题


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:


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))
}


来源:https://stackoverflow.com/questions/41277465/what-is-the-best-way-to-map-windows-drives-using-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!