【发布时间】:2020-11-13 22:30:13
【问题描述】:
故事是这样的:我有一个名为 coletorbeat 的程序,它需要一个大参数才能运行。这个论点是建立在几个参数之上的。我构建了一个名为 bootstrapper 的第二个程序,它接受这些参数,构建 coletorbeat 所需的长参数,然后应该运行 coletorbeat,为其提供长参数。 我尝试了多种方法,包括转义引号、反引号等等。但是由于某种原因,程序被调用并且好像根本没有传递任何参数。我什至没有错误消息。 我将在下面发布代码,非常感谢任何帮助。
像 coletorbeat.ip=%v 这样的字段应该出现在命令行中的引号或反引号内,前面带有标志 -E。
package main
import (
"fmt"
"os"
"os/exec"
"time"
)
func main() {
if len(os.Args) < 8 {
fmt.Printf("%v arguments were given. 8 needed to work", len(os.Args))
return
}
// Parâmetros devem ser passados na ordem: ip, porta, data_inicio, data_fim, tipo_equipamento, versao, nivel, instituicao
//There can`t be empty spaces on any of the strings inside the Args. We gotta do some prevention in case it happens here.
flag := "-E"
Arg1 := fmt.Sprintf("`coletorbeat.ip=%v`", os.Args[1])
Arg2 := fmt.Sprintf("`coletorbeat.porta=%v`", os.Args[2])
Arg3 := fmt.Sprintf("`coletorbeat.dataInicio=%v`", os.Args[3])
Arg4 := fmt.Sprintf("`coletorbeat.dataFim=%v`", os.Args[4])
Arg5 := fmt.Sprintf("`coletorbeat.tipoEquipamento=%v`", os.Args[5])
Arg6 := fmt.Sprintf("`coletorbeat.versao=%v`", os.Args[6])
Arg7 := fmt.Sprintf("`coletorbeat.nivel=%v`", os.Args[7])
Arg8 := fmt.Sprintf("`coletorbeat.instituicao=%v`", os.Args[8])
Arg9 := fmt.Sprintf("`output.elasticsearch.index=collectorbeat-%v-%v-%v-%v`", os.Args[8], os.Args[5], time.Now().Format("20060201"), os.Args[1])
commandToExecute := &exec.Cmd{
Path: "coletorbeat",
Args: []string{"./", flag, Arg1, flag, Arg2, flag, Arg3, flag, Arg4, flag, Arg5, flag, Arg6, flag, Arg7, flag, Arg8, flag, Arg9},
Stdout: os.Stdout,
Stderr: os.Stdout,
}
fmt.Println(commandToExecute.Args)
fmt.Println("Copy the code")
if err := commandToExecute.Run(); err != nil {
fmt.Println("error caught on Bootstrapper")
fmt.Println("Error: ", err)
}
}
【问题讨论】:
-
即使 args 包含空格,也不要使用引号。您正在准备通过 shell 调用 args。直接执行程序时不需要。
-
可以尝试以下几点:1) 使用单引号而不是反引号。 2) 制作一个包含所有参数的长字符串,就好像您在 bash 命令行上键入它一样,然后将该单个字符串作为单个 arg 传递。 3) 制作一个新程序,它只读取 args 并将它们注销,用它代替 coletorbeat,看看你是否正在得到你期望的 args。 4)使 -E 成为 arg 的一部分,而不是他们自己的,例如"-E 'coletorbeat.ip=%v'"
-
这很简单,真的:因为不涉及 shell,所以传递给 exec.Command(或者,在这种情况下,分配给 Cmd.Args)的参数在被调用的程序中变成 os.Args, 没有任何改变。因此,除非 coletorbeat 需要迭代引号(这将是非常不寻常的),否则将它们全部删除。
-
另外,由于您是手动构建 Cmd,您必须使用程序名称(“coletorbeat”)作为 Args 的第一个元素:
Args: []string{"coletorbeat", "./" ...}。我强烈建议您改用 exec.Command。
标签: bash go command-line command-line-arguments