使用golang映射Windows驱动器的最佳方法是什么?

huangapple go评论87阅读模式
英文:

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

问题

使用Go语言将网络共享映射到Windows驱动器的最佳方法是什么?该共享还需要用户名和密码。

类似的问题已经在Python中提出过https://stackoverflow.com/questions/1271317

英文:

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 https://stackoverflow.com/questions/1271317

答案1

得分: 0

目前在Go语言中没有直接的方法来实现这个功能;我建议使用net use命令,当然这个功能只限于Windows系统,但这正是你所需要的。

所以,在Windows系统中,你可以通过在命令提示符中使用以下命令将网络共享映射到Windows驱动器:

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

其中,Q:代表你的Windows驱动器,\\SERVER\SHARE是网络地址,/user:Alice pa$$word是你的凭据,/P用于持久化。

在Go语言中执行这个命令的代码如下:

func mapDrive(letter string, address string, user string, pw string) ([]byte, error) {
  // 返回标准输出和错误输出的组合结果
  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)
  }
  // 打印输出结果
  log.Println(string(out))
}

以上是将网络共享映射到Windows驱动器的示例代码。

英文:

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

huangapple
  • 本文由 发表于 2016年12月22日 15:01:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/41277465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定