shell - 如何通过Go运行此命令?

标签 shell go command

echo "test_metric:20|c" | nc -v -C -w 1 host.address port
我通过终端运行此命令,得到了预期的结果。但是如何通过Go代码执行相同的操作?
经过这里的回答后,我尝试了此操作-
sh:= os.Getenv("SHELL")
cmd := exec.Command(sh, "-c ", `echo "test_metric:20|c" | nc -v -C -w 1 host.address port`)

cmd.Stdout = os.Stdout

cmd.Run()
但是没有运气。

最佳答案

我看不到调用Shell来执行此操作的意义:

package main

import (
    "bytes"
    "flag"
    "fmt"
    "io"
    "log"
    "net"
    "time"
)

var (
    host    string
    port    int
    timeout string
)

func init() {
    flag.StringVar(&host, "host", "localhost", "host to connect to")
    flag.IntVar(&port, "port", 10000, "port to connect to")
    flag.StringVar(&timeout, "timeout", "1s", "timeout for connection")
}

func main() {
    flag.Parse()

    // Fail early on nonsensical input.
    if port < 1 || port > 65535 {
        log.Fatalf("Illegal port %d: must be >=1 and <=65535", port)
    }

    var (
        // The timeout for the connection including name resolution
        to time.Duration

        // The ubiquitous err
        err error

        // The dial string
        addr = fmt.Sprintf("%s:%d", host, port)

        // The actual connection
        con net.Conn

        // Your playload. It should be easy enough to make this
        // non-static.
        payload = []byte("test_metric:20|c")
    )

    // Check the user has given a proper timeout.
    if to, err = time.ParseDuration(timeout); err != nil {
        log.Fatalf("parsing timeout: %s", err)
    }

    // You might want to implement a retry strategy here.
    // See https://stackoverflow.com/a/62909111/1296707 for details
    if con, err = net.DialTimeout("tcp", addr, to); err != nil {
        log.Fatalf("Error while dialing: %s", err)
    }
    defer con.Close()

    // This simulates about every input.
    // You can use a pipe of a command or whatever you want.
    dummyReader := bytes.NewBuffer(payload)

    if w, err := io.Copy(con, dummyReader); err != nil && w < int64(len(payload)) {
        log.Printf("Short write: written (%d) < payload (%d): %s", w, len(payload), err)
    } else if err != nil {
        // This should not happen, as usually an error is accompanied by a short write
        log.Println("Uuupsie!")
    }

}
在一个shell上启动一个netcat侦听器:
$ nc -k -l 10000
通过运行代码
$ go run dacode.go
并且您应该在netcat侦听器的输出上看到您的有效负载。
如果要将程序的输出传输到远程服务器,只需通过os.Exec调用相应的命令,并在con上使用io.Copy以及命令的io.Reader返回的StdoutPipe()即可。

关于shell - 如何通过Go运行此命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63014441/

相关文章:

bash - 将标准输入复制到标准输出

go - 在端点上运行测试之前,无法在BeforeSuit中启动应用程序服务器

go - 如何在golang模板中的LOOP内执行IF/ELSE条件?

java - 如何使用java从另一个类获取命令行参数

java - 从命令行中传递的文件名获取文件(String[] args)

regex - 有没有更有效的方法来使用 grep 进行拼字游戏搜索?

linux - 在 bash 脚本中评估命令导致 $SHLVL 增加

shell - 如何在 Unix 命令行或 shell 脚本中打乱文本文件的行?

linux - 这个脚本中发生了什么?

go - 获取日志文件中的结构字符串