GO - 通过ssh连接执行命令时出现未知错误

时间:2015-09-29 00:08:56

标签: ssh go runtime-error

我试图通过ssh连接上的 session.Run()功能执行命令。到目前为止,我可以成功执行一些命令但是在其他命令上我不断收到以下错误:"进程退出:1。原因是:()退出状态1"

func (p *project) connect(config *ssh.ClientConfig) {

    log.Printf("Trying connection...\n")

    conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", p.hostname.name, p.port.name), config)
    checkError("Failed to dial: ", err)
    log.Printf("Connection established.\n")

    for step := range p.typ.program.setup {
        p.install(step, conn)
    }
}

func (p *project) install(step int, conn *ssh.Client) {
    session, err := conn.NewSession()
    checkError("Failed to build session: ", err)
    defer session.Close()

    var stdoutBuf bytes.Buffer
    session.Stdout = &stdoutBuf

    log.Printf("Executing command: %s", p.typ.program.setup[step])

    if err := session.Run(p.typ.program.setup[step]); err != nil {
        log.Println(session.Stdout)
        log.Fatal("Error on command execution", err.Error())
    }
}


// That would be an example of a command which returns me an error
// "cd ~/www/www/ && git commit -m 'on the beginning was the commit'"
// That comes inside a slice on p.typ.program.setup accessed by the step(index).

命令输出(session.Stdout)是我期望的那个:

 "# On branch master nothing to commit, working directory clean"

只是要注意我已经尝试直接在控制台上执行命令,它运行正常。

所以,代码似乎没问题,命令在远程运行,但无论如何我仍然有错误。

有没有人知道为什么会这样?

提前致谢。

1 个答案:

答案 0 :(得分:0)

也许我的图书馆会对你的情况有所帮助:https://github.com/shagabutdinov/shell;它介绍了在一个会话中运行ssh命令的基本情况。

请尝试以下操作:

handler := func(outputType int, message string) {
    if(outputType == shell.Stdout) {
        log.Println("stdout: ", message)
    } else if(outputType == shell.Stdout) {
        log.Println("stderr: ", message)
    }
}

key, err := ssh.ParsePrivateKey([]byte(YOUR_PRIVATE_KEY))
if(err != nil) {
    panic(err)
}

auth := []ssh.AuthMethod{ssh.PublicKeys(key)}
shell = shell.NewRemote(shell.RemoteConfig{
    Host: "root@example.com:22",
    Auth: auth,
})

if(err != nil) {
    panic(err)
}

status, err := shell.Run("cd ~/www/www/", handler)
if(err != nil) {
    panic(err)
}

status, err := shell.Run("git commit -m 'on the beginning was the commit'", handler)
if(err != nil) {
    panic(err)
}

if(status == 0) {
    console.log("command executed successfully")
} else {
    console.log("command execution failed")
}