duanaoou4105 2018-11-28 07:22
浏览 96
已采纳

无法从SSH获取stderr

I am trying to get the error info when running a command from ssh. Here is the example:

package main

import (
    "golang.org/x/crypto/ssh"
    "net"
)

func main() {
    config := &ssh.ClientConfig{
        User: "xx",
        Auth: []ssh.AuthMethod{
            ssh.Password("xxx"),
        },

        HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
            return nil
        },
    }

    sshClient, err := ssh.Dial("tcp", "x.x.x.x:22", config)
    if err != nil {
        panic(err.Error())
    }

    session, err := sshClient.NewSession()
    if err != nil {
        panic(err.Error())
    }

    data, err := session.CombinedOutput("ls2")
    if err != nil {
        // This prints : error = Process exited with status 127
        // Pos1
        print("error = " + err.Error())
        return
    }

    // Pos2
    content := string(data)
    println(content)
}

I test a wrong command: ls2, and I want to get the actual error info "-bash: ls2: command not found" at Pos2. But this test program failed at Pos1, and print "error = Process exited with status 127", which is not what I want, because I need the actual info.

  • 写回答

1条回答 默认 最新

  • dppcyt6157 2018-11-28 08:23
    关注

    try like this

    session, err := sshClient.NewSession()
    if err != nil {
        panic(err.Error())
    }
    
    defer session.Close()
    data, err := session.CombinedOutput("ls2")
    if err != nil {
        if v, ok := err.(*ssh.ExitError); ok {
            fmt.Println(v.Msg())
        }
    }
    fmt.Println(string(data))
    

    and will output command not found: ls2

    you can see the issues at here https://github.com/golang/go/issues/14251

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题