-
-
Notifications
You must be signed in to change notification settings - Fork 376
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Alex Ellis <[email protected]>
- Loading branch information
Showing
2 changed files
with
96 additions
and
77 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
package ssh | ||
|
||
import ( | ||
"bytes" | ||
"io" | ||
"os" | ||
"sync" | ||
|
||
"golang.org/x/crypto/ssh" | ||
) | ||
|
||
type SSHOperator struct { | ||
conn *ssh.Client | ||
} | ||
|
||
func (s *SSHOperator) Close() error { | ||
|
||
return s.conn.Close() | ||
} | ||
|
||
func NewSSHOperator(address string, config *ssh.ClientConfig) (*SSHOperator, error) { | ||
conn, err := ssh.Dial("tcp", address, config) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
operator := SSHOperator{ | ||
conn: conn, | ||
} | ||
|
||
return &operator, nil | ||
} | ||
|
||
func (s *SSHOperator) Execute(command string) (commandRes, error) { | ||
|
||
sess, err := s.conn.NewSession() | ||
if err != nil { | ||
return commandRes{}, err | ||
} | ||
|
||
defer sess.Close() | ||
|
||
sessStdOut, err := sess.StdoutPipe() | ||
if err != nil { | ||
return commandRes{}, err | ||
} | ||
|
||
output := bytes.Buffer{} | ||
|
||
wg := sync.WaitGroup{} | ||
|
||
stdOutWriter := io.MultiWriter(os.Stdout, &output) | ||
wg.Add(1) | ||
go func() { | ||
io.Copy(stdOutWriter, sessStdOut) | ||
wg.Done() | ||
}() | ||
sessStderr, err := sess.StderrPipe() | ||
if err != nil { | ||
return commandRes{}, err | ||
} | ||
|
||
errorOutput := bytes.Buffer{} | ||
stdErrWriter := io.MultiWriter(os.Stderr, &errorOutput) | ||
wg.Add(1) | ||
go func() { | ||
io.Copy(stdErrWriter, sessStderr) | ||
wg.Done() | ||
}() | ||
|
||
err = sess.Run(command) | ||
|
||
wg.Wait() | ||
|
||
if err != nil { | ||
return commandRes{}, err | ||
} | ||
|
||
return commandRes{ | ||
StdErr: errorOutput.Bytes(), | ||
StdOut: output.Bytes(), | ||
}, nil | ||
} | ||
|
||
type commandRes struct { | ||
StdOut []byte | ||
StdErr []byte | ||
} | ||
|
||
func executeCommand(cmd string) (commandRes, error) { | ||
|
||
return commandRes{}, nil | ||
} |