Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add ExecStream for long-running commands #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -44,4 +44,4 @@ func main() {
```

## License
SimpleSSH is licensed under the MIT license.
SimpleSSH is licensed under the MIT license.
49 changes: 49 additions & 0 deletions simplessh.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package simplessh

import (
"bufio"
"bytes"
"fmt"
"io"
@@ -232,6 +233,31 @@ func (c *Client) Exec(cmd string) ([]byte, error) {
return session.CombinedOutput(cmd)
}

// Execute cmd on the remote host and return combined stderr and stdout in
// real time
func (c *Client) ExecStream(cmd string, stdout io.Writer) error {
session, err := c.SSHClient.NewSession()
if err != nil {
return err
}
defer session.Close()

sessOut, err := session.StdoutPipe()
if err != nil {
return err
}

sessErr, err := session.StderrPipe()
if err != nil {
return err
}

go streamOutput(sessOut, stdout)
go streamOutput(sessErr, stdout)

return session.Run(cmd)
}

// Execute cmd via sudo. Do not include the sudo command in
// the cmd string. For example: Client.ExecSudo("uptime", "password").
// If you are using passwordless sudo you can use the regular Exec()
@@ -375,3 +401,26 @@ func addPortToHost(host string) string {

return host
}

func streamOutput(read io.Reader, write io.Writer) {
var (
r = bufio.NewReader(read)
line = ""
)

for {
b, err := r.ReadByte()
if err != nil {
break
}

if b == byte('\n') {
fmt.Fprintln(write, line)
line = ""

continue
}

line += string(b)
}
}