在go lang中使用exec.command进行网络使用

问题描述 投票:-3回答:1

我需要使用go在Windows中映射驱动器,并发现此链接有用What is the best way to map windows drives using golang?

当我尝试使用这里给出的代码时,我遇到了这个错误

exec: "net use": executable file not found in %PATH% 

我验证了go的bin文件夹在PATH变量中。我也尝试过运行它

cmd, err := exec.Command("cmd", "/c", "NET USE", "T:", \\SERVERNAME\C$, "/PERSISTENT").CombinedOutput()  

但我得到这个错误:

exit status 1 You used an option with an invalid value.  

我在这里做错了什么帮忙?

windows go
1个回答
1
投票

exec.Command()的每个参数都用作单个参数,因此:

exec.Command(... "NET USE", ..)

这意味着NET USE作为单个参数传递,这与从命令行执行此操作相同:

cmd /c "net use"

这意味着它将尝试找到net use.exe,而不是将参数use传递给net.exe

所以正确的方法是:

exec.Command("cmd", "/c", "net", "use", "Q:, `\\SERVER\SHARE`, "/user:Alice pa$$word", "/P")

可能不需要cmd /c部分,但我没有Windows机器来验证。

还要注意我是如何使用反引号(`)代替\\SERVER\SHARE而不是",所以你不必加倍反斜杠。

© www.soinside.com 2019 - 2024. All rights reserved.