簡體   English   中英

如何通過 Go 運行此命令?

[英]How to run this command via Go?

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 偵聽器的 output 上看到您的有效負載。

如果您想將程序的 output 傳輸到遠程服務器,只需通過os.Exec調用相應的命令並使用io.Copy on conZF98ED07A4D5F50F7DE1410D905F14返回命令

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM