英文:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论