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 #MATLAB仿真#车辆换道路径规划
    • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
    • ¥15 数据可视化Python
    • ¥15 要给毕业设计添加扫码登录的功能!!有偿
    • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
    • ¥15 微信公众号自制会员卡没有收款渠道啊
    • ¥15 stable diffusion
    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条