gpt4 book ai didi

go - 如何在 golang CLI 中在远程机器上执行命令?

转载 作者:IT老高 更新时间:2023-10-28 13:08:01 25 4
gpt4 key购买 nike

如何在 golang CLI 中在远程机器上执行命令?我需要编写一个 golang CLI,它可以通过 key SSH 到远程机器并执行 shell 命令。此外,我需要能够做到这一点。例如SSH 连接到一台机器(如云堡垒),然后 SSH 连接到另一台内部机器并执行 shell 命令。

我(还)没有找到任何例子。

最佳答案

您可以使用 "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
}

关于go - 如何在 golang CLI 中在远程机器上执行命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37679939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com