亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 golang CLI 中在遠程機器上執行命令?

如何在 golang CLI 中在遠程機器上執行命令?

Go
夢里花落0921 2022-01-17 16:23:08
如何在 golang CLI 中在遠程機器上執行命令?我需要編寫一個 golang CLI,它可以通過密鑰 SSH 到遠程機器并執行 shell 命令。此外,我需要能夠做到這一點。例如,通過 SSH 連接到一臺機器(如云堡壘),然后通過 SSH 連接到另一臺內部機器并執行 shell 命令。我(還)沒有找到任何例子。
查看完整描述

3 回答

?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

"golang.org/x/crypto/ssh"您可以使用該軟件包通過 SSH 在遠程計算機上運行命令。


這是一個示例函數,演示了在遠程機器上運行單個命令并返回輸出的簡單用法:


//e.g. output, err := remoteRun("root", "MY_IP", "PRIVATE_KEY", "ls")

func remoteRun(user string, addr string, privateKey string, cmd string) (string, error) {

    // privateKey could be read from a file, or retrieved from another storage

    // source, such as the Secret Service / GNOME Keyring

    key, err := ssh.ParsePrivateKey([]byte(privateKey))

    if err != nil {

        return "", err

    }

    // Authentication

    config := &ssh.ClientConfig{

        User: user,

        // https://github.com/golang/go/issues/19767 

        // as clientConfig is non-permissive by default 

        // you can set ssh.InsercureIgnoreHostKey to allow any host 

        HostKeyCallback: ssh.InsecureIgnoreHostKey(),

        Auth: []ssh.AuthMethod{

            ssh.PublicKeys(key),

        },

        //alternatively, you could use a password

        /*

            Auth: []ssh.AuthMethod{

                ssh.Password("PASSWORD"),

            },

        */

    }

    // Connect

    client, err := ssh.Dial("tcp", net.JoinHostPort(addr, "22"), config)

    if err != nil {

        return "", err

    }

    // Create a session. It is one session per command.

    session, err := client.NewSession()

    if err != nil {

        return "", err

    }

    defer session.Close()

    var b bytes.Buffer  // import "bytes"

    session.Stdout = &b // get output

    // you can also pass what gets input to the stdin, allowing you to pipe

    // content from client to server

    //      session.Stdin = bytes.NewBufferString("My input")


    // Finally, run the command

    err = session.Run(cmd)

    return b.String(), err

}


查看完整回答
反對 回復 2022-01-17
?
青春有我

TA貢獻1784條經驗 獲得超8個贊

嘗試使用 os/exec https://golang.org/pkg/os/exec/來執行 ssh


package main


import (

    "bytes"

    "log"

    "os/exec"

)


func main() {

    cmd := exec.Command("ssh", "remote-machine", "bash-command")

    var out bytes.Buffer

    cmd.Stdout = &out

    err := cmd.Run()

    if err != nil {

        log.Fatal(err)

    }

}

要跳過機器,請使用 ssh 配置文件中的 ProxyCommand 指令。


Host remote_machine_name

  ProxyCommand ssh -q bastion nc remote_machine_ip 22


查看完整回答
反對 回復 2022-01-17
?
UYOU

TA貢獻1878條經驗 獲得超4個贊

這里的其他解決方案也可以,但我會拋出另一個你可以嘗試的選項:simplessh。我認為它更容易使用。對于這個問題,我將使用下面的選項 3,您可以在其中使用您的密鑰進行 ssh。


選項 1:使用密碼 SSH 到機器,然后運行命令


import (

    "log"


    "github.com/sfreiberg/simplessh"

)


func main() error {

    var client *simplessh.Client

    var err error


    if client, err = simplessh.ConnectWithPassword("hostname_to_ssh_to", "username", "password"); err != nil {

        return err

    }


    defer client.Close()


    // Now run the commands on the remote machine:

    if _, err := client.Exec("cat /tmp/somefile"); err != nil {

        log.Println(err)

    }


    return nil

}

選項 2:使用一組可能的密碼通過 SSH 連接到機器,然后運行命令


import (

    "log"


    "github.com/sfreiberg/simplessh"

)


type access struct {

    login    string

    password string

}


var loginAccess []access


func init() {

    // Initialize all password to try

    loginAccess = append(loginAccess, access{"root", "rootpassword1"})

    loginAccess = append(loginAccess, access{"someuser", "newpassword"})

}


func main() error {

    var client *simplessh.Client

    var err error


    // Try to connect with first password, then tried second else fails gracefully

    for _, credentials := range loginAccess {

        if client, err = simplessh.ConnectWithPassword("hostname_to_ssh_to", credentials.login, credentials.password); err == nil {

            break

        }

    }


    if err != nil {

        return err

    }


    defer client.Close()


    // Now run the commands on the remote machine:

    if _, err := client.Exec("cat /tmp/somefile"); err != nil {

        log.Println(err)

    }


    return nil

}

選項 3:使用您的密鑰通過 SSH 連接到機器


import (

    "log"


    "github.com/sfreiberg/simplessh"

)


func SshAndRunCommand() error {

    var client *simplessh.Client

    var err error


    // Option A: Using a specific private key path:

    //if client, err = simplessh.ConnectWithKeyFile("hostname_to_ssh_to", "username", "/home/user/.ssh/id_rsa"); err != nil {


    // Option B: Using your default private key at $HOME/.ssh/id_rsa:

    //if client, err = simplessh.ConnectWithKeyFile("hostname_to_ssh_to", "username"); err != nil {


    // Option C: Use the current user to ssh and the default private key file:

    if client, err = simplessh.ConnectWithKeyFile("hostname_to_ssh_to"); err != nil {

        return err

    }


    defer client.Close()


    // Now run the commands on the remote machine:

    if _, err := client.Exec("cat /tmp/somefile"); err != nil {

        log.Println(err)

    }


    return nil

}


查看完整回答
反對 回復 2022-01-17
  • 3 回答
  • 0 關注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號