如何在golang CLI中的远程计算机上执行命令? [英] How do I execute a command on a remote machine in a golang CLI?

查看:116
本文介绍了如何在golang CLI中的远程计算机上执行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在golang CLI中的远程计算机上执行命令?我需要编写一个golang CLI,该CLI可以通过一个密钥SSH到远程计算机并执行shell命令。此外,我需要能够做到这一步。例如SSH进入一台计算机(如云堡垒),然后SSH进入另一台内部计算机,然后执行shell命令。

How do I execute a command on a remote machine in a golang CLI? I need to write a golang CLI that can SSH into a remote machine via a key and execute a shell command. Furthermore, I need to be able to do this one hop away. e.g. SSH into a machine (like a cloud bastion) and then SSH into another, internal, machine and execute a shell command.

我(尚未)没有发现任何示例

I haven't (yet) found any examples for this.

推荐答案

尝试使用os / exec https://golang.org/pkg/os/exec/ 执行ssh

Try with os/exec https://golang.org/pkg/os/exec/ to execute a 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指令。

To jump over machines use the ProxyCommand directive in a ssh config file.

Host remote_machine_name
  ProxyCommand ssh -q bastion nc remote_machine_ip 22

这篇关于如何在golang CLI中的远程计算机上执行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆