bash - 在golang中一起执行bash echo和nc

标签 bash go exec

<分区>

这可能是一个简单的问题。在 linux 机器上工作,我试图从 go 程序向 shell 发送命令。我有一个服务器监听请求。不过,这行代码给我带来了问题。

cmd := exec.Command("echo -n 'hello' | nc localhost 3333")

我的其余代码正确运行命令...

然而,它只是将它识别为一个 echo 参数,其余部分是它正在 echo 的字符串的一部分。我想将回显通过管道传输到 nc 以将消息发送到服务器。

我试过重新排列它,例如以这种方式:

cmd := exec.Command("echo", "-n", "'hello' | nc localhost 3333")

但它们产生相同的结果,或错误:

未找到可执行文件 $PATH

如何从 go 脚本以这种方式同时执行 echo 和管道命令(如 nc)。

最佳答案

| , > , < , & , ... , cd , ...还有更多是 shell 内置函数,这些由 shell 解释并据此执行。

所以你需要调用shell , 并使用 -c 执行您的命令标志,提到 shell将以下参数作为命令执行。

package main

import (
    "os"
    "os/exec"
)

func main() {
    sh := os.Getenv("SHELL") //fetch default shell
    //execute the needed command with `-c` flag
    cmd := exec.Command(sh, "-c ", `echo -n 'hello' | grep "h"`)
    cmd.Stdout = os.Stdout
    cmd.Run()
}

这里我用的是grep ,因为我没有 nc

关于bash - 在golang中一起执行bash echo和nc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52770746/

相关文章:

python - 在Python的jupyter笔记本中, `%%bash cat Testtext3.txt.*.decodes`有什么作用?

regex - 在 Bash 中引用正则表达式

go - 为每个 vscode 项目设置 `GOPATH`

c - Pipe、Fork 和 Exec - 父子进程之间的双向通信

flash - Flash编译器不允许覆盖

linux - 重复读取行和调用程序的更简单方法

bash - 将命令作为参数传递给 bash 脚本

json - 使用标准模板包从json对象获取前两个值

go - gRPC 设置有问题。获取间歇性 RPC 不可用错误

python - 如何以字符串形式执行 python print 语句?