Compare commits

..

20 Commits

Author SHA1 Message Date
Bo-Yi Wu b5b13e8b72 upgrade easyssh to 1.1.6 (#81)
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-16 15:45:00 +08:00
Bo-Yi Wu 26b3d47ee2 add exit code example.
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-13 13:47:00 +08:00
Bo-Yi Wu 0a78278313 add return error code command example.
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-12 14:21:33 +08:00
Bo-Yi Wu a7c37e0936 fix panic from easyssh-proxy
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-11 15:14:28 +08:00
Bo-Yi Wu 699d9148d8 update readme.
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-10 21:55:56 +08:00
Bo-Yi Wu ceec42efdd bump easyssh package.
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-10 21:37:48 +08:00
Bo-Yi Wu 88b5394dac update output
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-10 21:26:34 +08:00
Bo-Yi Wu 1637772e0b hide domain if only single host in config. (#80)
* hide domain if only single host in config.

Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>

* fix host

Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>

* refactor

Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-10 21:17:31 +08:00
Bo-Yi Wu efdac217bd update log format.
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-10 16:42:37 +08:00
Bo-Yi Wu f81056261d add demo gif
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-10 16:21:22 +08:00
Bo-Yi Wu 3fffe80a14 remove timestamp in log
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-10 15:36:20 +08:00
Bo-Yi Wu 2d568d1fde Support stream output logs. (#79)
* Support stream output logs.

Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>

* fix block channel.

Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-10 11:34:00 +08:00
Bo-Yi Wu f26bd7f7f7 update makefile
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-09 15:13:50 +08:00
Bo-Yi Wu 95427edbba update makefile
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-09 15:11:17 +08:00
Bo-Yi Wu 7f168bd1cb update makefile
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-09 15:07:57 +08:00
Bo-Yi Wu b6c973ef1e fix: get exit code from ssh run command. (#78) 2017-05-09 09:38:31 +08:00
Bo-Yi Wu 356b2ae6cc feat: support group build (#76) 2017-05-08 09:06:35 +08:00
Bo-Yi Wu b698d56d60 add some secrets.
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-02 22:03:26 +08:00
Bo-Yi Wu 06f4f77ebc update drone to 0.6
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
2017-05-02 21:51:15 +08:00
Bo-Yi Wu b63f275e9e refactor: show errors if set password and key at the same time (#72) 2017-04-23 11:49:40 +08:00
10 changed files with 276 additions and 88 deletions
+20 -13
View File
@@ -2,17 +2,20 @@ workspace:
base: /srv/app
path: src/github.com/appleboy/drone-ssh
pipeline:
clone:
clone:
git:
image: plugins/git
depth: 50
tags: true
pipeline:
test:
image: appleboy/golang-testing
pull: true
environment:
TAGS: netgo
GOPATH: /srv/app
secrets: [ codecov_token ]
commands:
- make ssh-server
- make vet
@@ -26,6 +29,16 @@ pipeline:
when:
event: [ push, tag, pull_request ]
publish_latest:
image: plugins/docker
repo: ${DRONE_REPO}
tags: [ 'latest' ]
secrets: [ docker_username, docker_password ]
when:
event: [ push ]
branch: [ master ]
local: false
release:
image: appleboy/golang-testing
pull: true
@@ -43,23 +56,17 @@ pipeline:
image: plugins/docker
repo: ${DRONE_REPO}
tags: [ '${DRONE_TAG}' ]
secrets: [ docker_username, docker_password ]
group: release
when:
event: [ tag ]
branch: [ refs/tags/* ]
local: false
publish_latest:
image: plugins/docker
repo: ${DRONE_REPO}
tags: [ 'latest' ]
when:
event: [ push ]
branch: [ master ]
local: false
release:
release_tag:
image: plugins/github-release
api_key: ${GITHUB_RELEASE_API_KEY}
secrets: [ github_release_api_key ]
group: release
files:
- dist/release/*
when:
+6 -5
View File
@@ -10,7 +10,7 @@ GOFMT ?= gofmt "-s"
TARGETS ?= linux darwin windows
PACKAGES ?= $(shell go list ./... | grep -v /vendor/)
GOFILES := find . -name "*.go" -type f -not -path "./vendor/*"
GOFILES := $(shell find . -name "*.go" -type f -not -path "./vendor/*")
SOURCES ?= $(shell find . -name "*.go" -type f)
TAGS ?=
LDFLAGS ?= -X 'main.Version=$(VERSION)'
@@ -32,14 +32,15 @@ all: build
.PHONY: fmt-check
fmt-check:
# get all go files and run go fmt on them
@files=$$($(GOFILES) | xargs $(GOFMT) -l); if [ -n "$$files" ]; then \
@diff=$$($(GOFMT) -d $(GOFILES)); \
if [ -n "$$diff" ]; then \
echo "Please run 'make fmt' and commit the result:"; \
echo "$${files}"; \
echo "$${diff}"; \
exit 1; \
fi;
fi;
fmt:
$(GOFILES) | xargs $(GOFMT) -w
$(GOFMT) -w $(GOFILES)
vet:
go vet $(PACKAGES)
+1
View File
@@ -9,6 +9,7 @@ information and a listing of the available options please take a look at [the do
**Note: Please update your image config path to `appleboy/drone-ssh` for drone. `plugins/ssh` is no longer maintained.**
![demo](./screenshot/demo2017.05.10.gif)
## Build
Build the binary with the following commands:
+42 -17
View File
@@ -2,7 +2,6 @@ package main
import (
"fmt"
"log"
"strconv"
"strings"
"sync"
@@ -11,12 +10,11 @@ import (
"github.com/appleboy/easyssh-proxy"
)
var wg sync.WaitGroup
const (
missingHostOrUser = "Error: missing server host or user"
missingPasswordOrKey = "Error: can't connect without a private SSH key or password"
commandTimeOut = "Error: command timeout"
setPasswordandKey = "can't set password and key at the same time"
)
type (
@@ -41,19 +39,28 @@ type (
)
func (p Plugin) log(host string, message ...interface{}) {
log.Printf("%s: %s", host, fmt.Sprintln(message...))
if count := len(p.Config.Host); count == 1 {
fmt.Printf("%s", fmt.Sprintln(message...))
} else {
fmt.Printf("%s: %s", host, fmt.Sprintln(message...))
}
}
// Exec executes the plugin.
func (p Plugin) Exec() error {
if len(p.Config.Host) == 0 && p.Config.UserName == "" {
if len(p.Config.Host) == 0 && len(p.Config.UserName) == 0 {
return fmt.Errorf(missingHostOrUser)
}
if p.Config.Key == "" && p.Config.Password == "" && p.Config.KeyPath == "" {
if len(p.Config.Key) == 0 && len(p.Config.Password) == 0 && len(p.Config.KeyPath) == 0 {
return fmt.Errorf(missingPasswordOrKey)
}
if len(p.Config.Key) != 0 && len(p.Config.Password) != 0 {
return fmt.Errorf(setPasswordandKey)
}
wg := sync.WaitGroup{}
wg.Add(len(p.Config.Host))
errChannel := make(chan error, 1)
finished := make(chan bool, 1)
@@ -80,18 +87,34 @@ func (p Plugin) Exec() error {
}
p.log(host, "commands: ", strings.Join(p.Config.Script, "\n"))
outStr, errStr, isTimeout, err := ssh.Run(strings.Join(p.Config.Script, "\n"), p.Config.CommandTimeout)
p.log(host, "outputs:", outStr)
if len(errStr) != 0 {
p.log(host, "errors:", errStr)
}
stdoutChan, stderrChan, doneChan, errChan, err := ssh.Stream(strings.Join(p.Config.Script, "\n"), p.Config.CommandTimeout)
if err != nil {
errChannel <- err
}
} else {
// read from the output channel until the done signal is passed
isTimeout := true
loop:
for {
select {
case isTimeout = <-doneChan:
break loop
case outline := <-stdoutChan:
p.log(host, "out:", outline)
case errline := <-stderrChan:
p.log(host, "err:", errline)
case err = <-errChan:
}
}
if !isTimeout {
errChannel <- fmt.Errorf(commandTimeOut)
// get exit code or command error.
if err != nil {
errChannel <- err
}
// command time out
if !isTimeout {
errChannel <- fmt.Errorf(commandTimeOut)
}
}
wg.Done()
@@ -107,12 +130,14 @@ func (p Plugin) Exec() error {
case <-finished:
case err := <-errChannel:
if err != nil {
log.Println("drone-ssh error: ", err)
fmt.Println("drone-ssh error: ", err)
return err
}
}
log.Println("Successfully executed commands to all host.")
fmt.Println("==========================================")
fmt.Println("Successfully executed commands to all host.")
fmt.Println("==========================================")
return nil
}
+87
View File
@@ -30,6 +30,22 @@ func TestMissingKeyOrPassword(t *testing.T) {
assert.Equal(t, missingPasswordOrKey, err.Error())
}
func TestSetPasswordAndKey(t *testing.T) {
plugin := Plugin{
Config{
Host: []string{"localhost"},
UserName: "ubuntu",
Password: "1234",
Key: "1234",
},
}
err := plugin.Exec()
assert.NotNil(t, err)
assert.Equal(t, setPasswordandKey, err.Error())
}
func TestIncorrectPassword(t *testing.T) {
plugin := Plugin{
Config: Config{
@@ -105,6 +121,39 @@ func TestSSHScriptFromKeyFile(t *testing.T) {
assert.Nil(t, err)
}
func TestStreamFromSSHCommand(t *testing.T) {
plugin := Plugin{
Config: Config{
Host: []string{"localhost", "127.0.0.1"},
UserName: "drone-scp",
Port: 22,
KeyPath: "./tests/.ssh/id_rsa",
Script: []string{"whoami", "for i in {1..5}; do echo ${i}; sleep 1; done", "echo 'done'"},
CommandTimeout: 60,
},
}
err := plugin.Exec()
assert.Nil(t, err)
}
func TestSSHScriptWithError(t *testing.T) {
plugin := Plugin{
Config: Config{
Host: []string{"localhost", "127.0.0.1"},
UserName: "drone-scp",
Port: 22,
KeyPath: "./tests/.ssh/id_rsa",
Script: []string{"exit 1"},
CommandTimeout: 60,
},
}
err := plugin.Exec()
// Process exited with status 1
assert.NotNil(t, err)
}
func TestSSHCommandTimeOut(t *testing.T) {
plugin := Plugin{
Config: Config{
@@ -142,3 +191,41 @@ func TestProxyCommand(t *testing.T) {
err := plugin.Exec()
assert.Nil(t, err)
}
func TestSSHCommandError(t *testing.T) {
plugin := Plugin{
Config: Config{
Host: []string{"localhost"},
UserName: "drone-scp",
Port: 22,
KeyPath: "./tests/.ssh/id_rsa",
Script: []string{"mkdir a", "mkdir a"},
CommandTimeout: 60,
},
}
err := plugin.Exec()
assert.NotNil(t, err)
}
func TestSSHCommandExitCodeError(t *testing.T) {
plugin := Plugin{
Config: Config{
Host: []string{"localhost"},
UserName: "drone-scp",
Port: 22,
KeyPath: "./tests/.ssh/id_rsa",
Script: []string{
"set -e",
"echo 1",
"mkdir a",
"mkdir a",
"echo 2",
},
CommandTimeout: 60,
},
}
err := plugin.Exec()
assert.NotNil(t, err)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 MiB

+6 -6
View File
@@ -1,8 +1,7 @@
.PHONY: test drone-ssh fmt vet errcheck lint install update coverage embedmd
GOFMT ?= gofmt "-s"
GOFILES := find . -name "*.go" -type f -not -path "./vendor/*"
GOFILES := $(shell find . -name "*.go" -type f -not -path "./vendor/*")
PACKAGES ?= $(shell go list ./... | grep -v /vendor/)
all: install lint
@@ -14,16 +13,17 @@ install:
govendor sync
fmt:
$(GOFILES) | xargs $(GOFMT) -w
$(GOFMT) -w $(GOFILES)
.PHONY: fmt-check
fmt-check:
# get all go files and run go fmt on them
@files=$$($(GOFILES) | xargs $(GOFMT) -l); if [ -n "$$files" ]; then \
@diff=$$($(GOFMT) -d $(GOFILES)); \
if [ -n "$$diff" ]; then \
echo "Please run 'make fmt' and commit the result:"; \
echo "$${files}"; \
echo "$${diff}"; \
exit 1; \
fi;
fi;
vet:
go vet $(PACKAGES)
+56 -1
View File
@@ -1,6 +1,11 @@
# easyssh-proxy
[![GoDoc](https://godoc.org/github.com/appleboy/easyssh-proxy?status.svg)](https://godoc.org/github.com/appleboy/easyssh-proxy) [![Build Status](http://drone.wu-boy.com/api/badges/appleboy/easyssh-proxy/status.svg)](http://drone.wu-boy.com/appleboy/easyssh-proxy) [![codecov](https://codecov.io/gh/appleboy/easyssh-proxy/branch/master/graph/badge.svg)](https://codecov.io/gh/appleboy/easyssh-proxy) [![Go Report Card](https://goreportcard.com/badge/github.com/appleboy/easyssh-proxy)](https://goreportcard.com/report/github.com/appleboy/easyssh-proxy) [![Sourcegraph](https://sourcegraph.com/github.com/appleboy/easyssh-proxy/-/badge.svg)](https://sourcegraph.com/github.com/appleboy/easyssh-proxy?badge)
[![GoDoc](https://godoc.org/github.com/appleboy/easyssh-proxy?status.svg)](https://godoc.org/github.com/appleboy/easyssh-proxy)
[![Build Status](http://drone.wu-boy.com/api/badges/appleboy/easyssh-proxy/status.svg)](http://drone.wu-boy.com/appleboy/easyssh-proxy)
[![codecov](https://codecov.io/gh/appleboy/easyssh-proxy/branch/master/graph/badge.svg)](https://codecov.io/gh/appleboy/easyssh-proxy)
[![Go Report Card](https://goreportcard.com/badge/github.com/appleboy/easyssh-proxy)](https://goreportcard.com/report/github.com/appleboy/easyssh-proxy)
[![Sourcegraph](https://sourcegraph.com/github.com/appleboy/easyssh-proxy/-/badge.svg)](https://sourcegraph.com/github.com/appleboy/easyssh-proxy?badge)
[![Release](https://github-release-version.herokuapp.com/github/appleboy/easyssh-proxy/release.svg?style=flat)](https://github.com/appleboy/easyssh-proxy/releases/latest)
easyssh-proxy provides a simple implementation of some SSH protocol features in Go.
@@ -124,3 +129,53 @@ See [example/proxy/proxy.go](./example/proxy/proxy.go)
},
}
```
### SSH Stream Log
See [example/stream/stream.go](./example/stream/stream.go)
[embedmd]:# (example/stream/stream.go go /func/ /^}$/)
```go
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
Server: "localhost",
User: "drone-scp",
KeyPath: "./tests/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
}
// Call Run method with command you want to run on remote server.
stdoutChan, stderrChan, doneChan, errChan, err := ssh.Stream("for i in {1..5}; do echo ${i}; sleep 1; done; exit 2;", 60)
// Handle errors
if err != nil {
panic("Can't run remote command: " + err.Error())
} else {
// read from the output channel until the done signal is passed
isTimeout := true
loop:
for {
select {
case isTimeout = <-doneChan:
break loop
case outline := <-stdoutChan:
fmt.Println("out:", outline)
case errline := <-stderrChan:
fmt.Println("err:", errline)
case err = <-errChan:
}
}
// get exit code or command error.
if err != nil {
fmt.Println("err: " + err.Error())
}
// command time out
if !isTimeout {
fmt.Println("Error: command timeout")
}
}
}
```
+53 -41
View File
@@ -86,8 +86,9 @@ func getSSHConfig(config DefaultConfig) *ssh.ClientConfig {
}
if config.Key != "" {
signer, _ := ssh.ParsePrivateKey([]byte(config.Key))
auths = append(auths, ssh.PublicKeys(signer))
if signer, err := ssh.ParsePrivateKey([]byte(config.Key)); err == nil {
auths = append(auths, ssh.PublicKeys(signer))
}
}
return &ssh.ClientConfig{
@@ -155,36 +156,45 @@ func (ssh_conf *MakeConfig) connect() (*ssh.Session, error) {
// Stream returns one channel that combines the stdout and stderr of the command
// as it is run on the remote machine, and another that sends true when the
// command is done. The sessions and channels will then be closed.
func (ssh_conf *MakeConfig) Stream(command string, timeout int) (stdout chan string, stderr chan string, done chan bool, err error) {
// connect to remote host
session, err := ssh_conf.connect()
if err != nil {
return stdout, stderr, done, err
}
// connect to both outputs (they are of type io.Reader)
outReader, err := session.StdoutPipe()
if err != nil {
return stdout, stderr, done, err
}
errReader, err := session.StderrPipe()
if err != nil {
return stdout, stderr, done, err
}
// combine outputs, create a line-by-line scanner
stdoutReader := io.MultiReader(outReader)
stderrReader := io.MultiReader(errReader)
err = session.Start(command)
stdoutScanner := bufio.NewScanner(stdoutReader)
stderrScanner := bufio.NewScanner(stderrReader)
func (ssh_conf *MakeConfig) Stream(command string, timeout int) (<-chan string, <-chan string, <-chan bool, <-chan error, error) {
// continuously send the command's output over the channel
stdoutChan := make(chan string)
stderrChan := make(chan string)
done = make(chan bool)
doneChan := make(chan bool)
errChan := make(chan error)
go func(stdoutScanner, stderrScanner *bufio.Scanner, stdoutChan, stderrChan chan string, done chan bool) {
// connect to remote host
session, err := ssh_conf.connect()
if err != nil {
return stdoutChan, stderrChan, doneChan, errChan, err
}
// defer session.Close()
// connect to both outputs (they are of type io.Reader)
outReader, err := session.StdoutPipe()
if err != nil {
return stdoutChan, stderrChan, doneChan, errChan, err
}
errReader, err := session.StderrPipe()
if err != nil {
return stdoutChan, stderrChan, doneChan, errChan, err
}
err = session.Start(command)
if err != nil {
return stdoutChan, stderrChan, doneChan, errChan, err
}
// combine outputs, create a line-by-line scanner
stdoutReader := io.MultiReader(outReader)
stderrReader := io.MultiReader(errReader)
stdoutScanner := bufio.NewScanner(stdoutReader)
stderrScanner := bufio.NewScanner(stderrReader)
go func(stdoutScanner, stderrScanner *bufio.Scanner, stdoutChan, stderrChan chan string, doneChan chan bool, errChan chan error) {
defer close(stdoutChan)
defer close(stderrChan)
defer close(done)
defer close(doneChan)
defer close(errChan)
defer session.Close()
timeoutChan := time.After(time.Duration(timeout) * time.Second)
res := make(chan bool, 1)
@@ -202,32 +212,30 @@ func (ssh_conf *MakeConfig) Stream(command string, timeout int) (stdout chan str
select {
case <-res:
stdoutChan <- ""
stderrChan <- ""
done <- true
errChan <- session.Wait()
doneChan <- true
case <-timeoutChan:
stdoutChan <- ""
stderrChan <- "Run Command Timeout!"
done <- false
errChan <- nil
doneChan <- false
}
}(stdoutScanner, stderrScanner, stdoutChan, stderrChan, doneChan, errChan)
session.Close()
}(stdoutScanner, stderrScanner, stdoutChan, stderrChan, done)
return stdoutChan, stderrChan, done, err
return stdoutChan, stderrChan, doneChan, errChan, err
}
// Run command on remote machine and returns its stdout as a string
func (ssh_conf *MakeConfig) Run(command string, timeout int) (outStr string, errStr string, isTimeout bool, err error) {
stdoutChan, stderrChan, doneChan, err := ssh_conf.Stream(command, timeout)
stdoutChan, stderrChan, doneChan, errChan, err := ssh_conf.Stream(command, timeout)
if err != nil {
return outStr, errStr, isTimeout, err
}
// read from the output channel until the done signal is passed
stillGoing := true
for stillGoing {
loop:
for {
select {
case isTimeout = <-doneChan:
stillGoing = false
break loop
case outline := <-stdoutChan:
if outline != "" {
outStr += outline + "\n"
@@ -236,6 +244,7 @@ func (ssh_conf *MakeConfig) Run(command string, timeout int) (outStr string, err
if errline != "" {
errStr += errline + "\n"
}
case err = <-errChan:
}
}
// return the concatenation of all signals from the output channel
@@ -266,17 +275,20 @@ func (ssh_conf *MakeConfig) Scp(sourceFile string, etargetFile string) error {
}
go func() {
w, _ := session.StdinPipe()
w, err := session.StdinPipe()
if err != nil {
return
}
defer w.Close()
fmt.Fprintln(w, "C0644", srcStat.Size(), targetFile)
if srcStat.Size() > 0 {
io.Copy(w, src)
fmt.Fprint(w, "\x00")
w.Close()
} else {
fmt.Fprint(w, "\x00")
w.Close()
}
}()
+5 -5
View File
@@ -3,12 +3,12 @@
"ignore": "test",
"package": [
{
"checksumSHA1": "L3PugNJJOEpRmRbD+27LgTZC2E4=",
"checksumSHA1": "EcF7T9tPEMMJfuRdPBB3NdRUg4c=",
"path": "github.com/appleboy/easyssh-proxy",
"revision": "a13ed86767b8e8a24d8147a4909a702e7cf6b465",
"revisionTime": "2017-04-14T13:46:38Z",
"version": "1.1.2",
"versionExact": "1.1.2"
"revision": "33d87eae3a018c3312e32cc4eb4578d5a563aabd",
"revisionTime": "2017-05-16T07:22:25Z",
"version": "1.1.6",
"versionExact": "1.1.6"
},
{
"checksumSHA1": "dvabztWVQX8f6oMLRyv4dLH+TGY=",