duannian3494 2017-08-27 20:15
浏览 127

在golang中使用crypto / ssh在远程主机中运行本地脚本

I am trying to replicate this command

ssh user@host /bin/bash < dummy.sh

using golang's crypto library.

I am opening a connection the remote host using ssh-agent. Then I am trying to run the command. Below is the snippet.

func executeSSHCmdToBuffer(cmd, hostname string, config *ssh.ClientConfig) (string, error) {
    conn, err := getSSHConnection(hostname, sshPort, config)
    if err != nil {
        return "", err
    }
    session, err := conn.NewSession()
    if err != nil {
        return "", err
    }
    defer session.Close()

    var stdoutBuf bytes.Buffer
    session.Stdout = &stdoutBuf
    session.Run(cmd)
    output := stdoutBuf.String()
    log.Printf("SSH Output %s", output)
    return output, nil
}

func ExecuteSSHCommand(cmd, hostname string) (string, error) {
    sshAuth, err := sshAgent()
    log.Printf("Executing %s on %s", cmd, hostname)
    if err != nil {
        log.Fatalf("SSH Agent Failed to init: %s", err)
    }

    sshConfig := &ssh.ClientConfig{
        User: sshUser,
        Auth: []ssh.AuthMethod{
            sshAuth,
        },
        Timeout:         time.Duration(1 * time.Minute),
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
    }
    return executeSSHCmdToBuffer(cmd, hostname, sshConfig)
}

func main() {
    out, err := ExecuteSSHCommand("/bin/sh < dummy.sh", "test.example.com")

    if err != nil {
        log.Print("Cannot execute the command")
        log.Print(err)
    }

    log.Print(out)
}

This seems to give out empty output. Anyone have an idea how this can be achieved?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
    • ¥15 CSAPPattacklab
    • ¥15 一直显示正在等待HID—ISP
    • ¥15 Python turtle 画图
    • ¥15 关于大棚监测的pcb板设计
    • ¥15 stm32开发clion时遇到的编译问题
    • ¥15 lna设计 源简并电感型共源放大器
    • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
    • ¥15 Vue3地图和异步函数使用
    • ¥15 C++ yoloV5改写遇到的问题