go - 从输出中排除 SSH 命令执行状态

标签 go ssh

我正在尝试使用 Go 语言开发 SSH 客户端。我编写了以下代码来获取用户的命令,在远程服务器上执行它们并打印响应。

下面的代码有一个小问题。在屏幕上打印输出会在响应结束时打印命令执行状态(无/错误状态)。如何从我的输出中排除它?

SSH.go

package main

import "fmt"
import "io"
import "bufio"
import "os"
import "net"
import "golang.org/x/crypto/ssh"

func main(){

    sshConfig := &ssh.ClientConfig{
        User: "[USERNAME]",
        Auth: []ssh.AuthMethod{
            ssh.Password("[PASSWORD]"),
        },
        HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
            return nil
        },
    }

    connection,err := ssh.Dial("tcp", "[IP]:[PORT]", sshConfig)
    if err != nil {
        fmt.Println("Failed to connect: %s", err)
    }

    reader := bufio.NewReader(os.Stdin)

    for{
        input, _ := reader.ReadString('\n')
        session,err := connection.NewSession()
        if err != nil {
            fmt.Println("Failed to create session: %s", err)
        }
        stdout,err := session.StdoutPipe()
        if err != nil {
            fmt.Println("Failed to get stdout: %s", err)
        }
        go io.Copy(os.Stdout, stdout)
        output := session.Run(input);
        fmt.Println(output)
    }

}

当前结果

hello
Process exited with status 127
df -hP /tmp
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda6       198G   13G  176G   7% /
<nil>

预期结果

hello
df -hP /tmp
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda6       198G   13G  176G   7% /

最佳答案

<nil>上面显示的是 session.Run 的输出,它返回一个 error (根据 docs )。

命令的输出已经通过以下 goroutine 显示在您的控制台上:

go io.Copy(os.Stdout, stdout)

您不需要打印 output ,即 nil因为 session.Run 时不会发生错误通话完成。更好的做法是检查错误:

// ...
if err := session.Run(input); err != nil {
  // handle error
}
// ...

关于go - 从输出中排除 SSH 命令执行状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45582678/

相关文章:

string - Go - 将原始字节字符串转换为 uuid

ssh - 使用 ssh key 身份验证无缝自动挂载 ecryptfs?

linux - bash 脚本中的命令无法正常工作

使用 Protocol Buffer 错误 : too few values in struct initializer 进行构建

node.js - 如何让 Go 应用程序等待 Redis 列表中的数据可用?

ssh - 在没有 ssh session 的服务器上运行应用程序

linux - SSH 连接到 Ubuntu 打开 SSH 服务器需要先通过密码登录(物理)服务器

linux - mkdir : missing operand - ssh -tt ${REMOTE_SERVER} sudo sh -c "mkdir -p/opt/migration"

model-view-controller - golang中的连接DB

url - 在 Go 中通过代理获取 URL 时出错