dongying9756 2018-05-09 17:25
浏览 29

从标准输出读取永不返回golang

I am trying to read from the stdoutpipe of an SSH connection. I am able to read it when there is data in the buffer, but when I try to read later after it's empty the read hangs.

Is there a way I can check if there is data in the buffer before reading it? or is something else going on here entirely?

I made a quick example to show what I'm seeing.

package main

import (
    "fmt"
    "strconv"

    "golang.org/x/crypto/ssh"
)

func main() {
    var user = "<user>"
    var passwd = "<password>"
    var ip = "<ip>"

    sshConfig := &ssh.ClientConfig{
        User:            user,
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
        Auth: []ssh.AuthMethod{
            ssh.Password(passwd),
        },
    }

    var conn, _ = ssh.Dial("tcp", ip + ":22", sshConfig)

    var sess, _ = conn.NewSession()

    var stdin, _ = sess.StdinPipe()
    var stdout, _ = sess.StdoutPipe()
    sess.Shell()

    stdin.Write([]byte("ls
"))

    var numBytes = 1
    var readCount = 0

    for numBytes > 0 {
        fmt.Println("Read count: " + strconv.Itoa(readCount))
        var recvData = make([]byte, 1024)
        numBytes, _ = stdout.Read(recvData)
        fmt.Println(string(recvData[:numBytes]))
        readCount++
    }
}

You'll need to update the user, passwd, and ip vars, but after that you should see the program freeze after stdout is empty.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 HLs设计手写数字识别程序编译通不过
    • ¥15 Stata外部命令安装问题求帮助!
    • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
    • ¥15 TYPCE母转母,插入认方向
    • ¥15 如何用python向钉钉机器人发送可以放大的图片?
    • ¥15 matlab(相关搜索:紧聚焦)
    • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
    • ¥15 路易威登官网 里边的参数逆向
    • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
    • ¥50 需求一个up主付费课程