3

go exec cmd /c 处理空格和双引号问题,大家有什么好办法吗?

 11 months ago
source link: https://www.v2ex.com/t/979299
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  程序员

go exec cmd /c 处理空格和双引号问题,大家有什么好办法吗?

  LonnyWong · 7 小时 28 分钟前 · 383 次点击

开源 issue: https://github.com/trzsz/trzsz-ssh/issues/46

复现 demo:

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	command := `"C:\WINDOWS\System32\OpenSSH\ssh.exe" -V`
	// command = `"C:\Program Files\ssh.exe" -V`
	cmd := exec.Command("cmd", "/c", command)
	output, _ := cmd.CombinedOutput()
	fmt.Println(string(output))
}

错误输出:

'\"C:\WINDOWS\System32\OpenSSH\ssh.exe\"' is not recognized as an internal or external command,
operable program or batch file.

原始问题,用户在 ~/.ssh/config 中配置任意的 ProxyCommand,要用 os/exec 来执行它,并且获取它的标准输出。用 cmd /c 是想避免解释每一个具体的参数是什么,有双引号,有空格,有转义,要准确地解释出每一个参数不简单啊。

大佬们有什么好想法吗?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK