title: Reading Data from SSH Session Golang
body: <p>I posted a similar question <a href="https://stackoverflow.com/questions/51046139/reading-data-from-socket-golang/51046333?noredirect=1#comment89085103_51046333">here</a> for reading from a telnet session.</p>
  
  <p>I am trying to read data from an SSH session in golang. I wrote the following functions to try to accomplish this.</p>
  
  <p>I was running into an issue where I was trying to read from stdout and it was empty and it caused my program to lock. To try to work around this I wrote BufferSocketData, it checks the channel ReadDataFromSocket is supposed to append to and if it has data it adds it to the buffer. If after 1 second it still hasn't received any data it stops the read.</p>
  
  <p>This isn't working correctly though and I'm unsure why. Only the first read gets new data subsequent reads return an empty string even if there is data in the buffer.</p>
  
  <p>In my previous question I was able to use SetReadDeadline to limit the amount of time reading from the socket, is there something similar I can use with an SSH session? or do I need to use a different strategy all together?</p>
  
  <pre><code>/*
  ReadDataFromSocket - Attempts to read any data in the socket.
  */
  func ReadDataFromSocket(sock io.Reader, c chan string) {
      var recvData = make([]byte, 1024)
      var numBytes, _ = sock.Read(recvData)
      c &lt;- string(recvData[:numBytes])
  }
  
  /*
  BufferSocketData - Read information from the socket and store it in the buffer.
  */
  func (s *SSHLib) BufferSocketData(inp chan string, out chan string) {
      var data string
      var timeout int64 = 1000 // 1 second timeout.
      var start = utils.GetTimestamp()
  
      for utils.GetTimestamp()-start &lt; timeout {
          select {
          case data = &lt;-inp:
          default:
          }
          if data != "" {
              break
          }
      }
      out &lt;- data
  }
  
  /*
  GetData - Start goroutines to get and buffer data.
  */
  func (s *SSHLib) GetData() {
      var sockCh = make(chan string)
      var buffCh = make(chan string)
  
      go ReadDataFromSocket(s.Stdout, sockCh)
      go s.BufferSocketData(sockCh, buffCh)
  
      var data = &lt;-buffCh
  
      if data != "" {
          s.Buffer += data
      }
  }
  </code></pre>
  
  <p>Please let me know if you need any other information.</p>