gosher

package module
v0.0.0-...-8551fc5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 27, 2015 License: MIT Imports: 11 Imported by: 0

README

Gosher

Gosher is an SSH library for Go. It supports synchronous execution, file download/upload on single host and asynchronous operations on multiple hosts.

Installation

To get gosher run:

go get github.com/lyuboraykov/gosher

This will download, compile and install the package in your $GOPATH directory. Alternatively, you can import the package like that:

import "github.com/lyuboraykov/gosher"

and use go get without parameters.

Documentation

You can read more about the interface here: Godoc

Usage

There are two clients in the package one is SshClient, used for synchronous operations on a single host and the other is MultipleHostsSshClient for async operations on multiple hosts.

Here is an example synchronous Hello World on a single host:

import "github.com/lyuboraykov/gosher"

// ...
client := gosher.NewSshClient("10.23.123.192", "root", gosher.PasswordAuthentication, "password")
response, err := client.Run("echo 'Hello World!'")
if err == nil {
   fmt.Println(response.StdOut.String())
}
else {
   fmt.Printf("There was an error while connecting to the server: %s \n", err.Error())
}

Here is a simple file upload:

import "github.com/lyuboraykov/gosher"

// ...
client := gosher.NewSshClient("10.23.123.192", "root", gosher.KeyAuthentication, "/home/user/.ssh/id_rsa")
response, err := client.Upload("somefile", "somelocation")
if err == nil {
   fmt.Println(response.StdOut.String())
}
else {
   fmt.Printf("There was an error while connecting to the server: %s \n", err.Error())
}

And here is a hello world on two hosts async:

receiveChannel := make(chan *SshResponse)
errorChannel := make(chan error)
host1 = gosher.NewHost("10.23.123.191", "root", PasswordAuthentication, "password", receiveChannel, errorChannel)
host2 = gosher.NewHost("10.23.123.192", "root", PasswordAuthentication, "password", receiveChannel, errorChannel)
client = NewMultipleHostsSshClient(&host1, &host2)
err := client.Run("echo 'Hello World'")
if err == nil {
   response1 := <-receiveChannel
   response2 := <-receiveChannel
   fmt.Println(response1.StdOut.String())
}

Now let's get more advanced and execute a function on a file on multiple hosts:

receiveChannel := make(chan *SshResponse, 2)
errorChannel := make(chan error, 2)
host1 := NewHost("10.23.123.191", "root", gosher.PasswordAuthentication, "password", receiveChannel, errorChannel)
host2 := NewHost("10.23.123.192", "root", goser.KeyAuthentication, "~/.ssh/id_rsa", receiveChannel, errorChannel)
host3 := NewHost("10.23.123.193", "root", gosher.PasswordAuthentication, "password", receiveChannel, errorChannel)
client := NewMultipleHostsSshClient(host1, host2, host3)
err := client.RunOnFile("/tmp/test_file" func(fileContent string) {
   return fileContent + " appended text"
   })
if err == nil {
   response1 := <-receiveChannel
   response2 := <-receiveChannel
   fmt.Println("Success!")
}

Features

All of these features are supported both on a single host and on multiple hosts

  • Execute Command Executes a simple shell command

  • Execute Script Executes a local script on remote machine

  • Upload/Download provides scp functionality

  • Execute on file executes a function on a remote file, can be used instead of awk/sed

Todo

Do a full test coverage.

License

This package is distributed under the MIT License:

The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Documentation

Overview

Package gosher provides types and methods for operations on remote machines via SSH e.g. execution of commands, download/upload of files

Index

Constants

View Source
const (
	PasswordAuthentication = iota
	KeyAuthentication
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Host

type Host struct {
	Client        *SshClient
	ResultChannel chan *SshResponse
	ErrorChannel  chan error
}

Host - remote machine definition type. Use with the multipleHostsSshClient with asynchronous execution. ResultChannel - the channel via which the SshResponse of the operations will be passed. ErrorChannel - the channel via which the error of the operations will be passed.

func NewHost

func NewHost(address string, user string, authenticationType int, authentication string,
	resultChannel chan *SshResponse, errorChannel chan error) (*Host, error)

Constructor method for the Host type

type MultipleHostsSshClient

type MultipleHostsSshClient struct {
	Hosts []*Host
}

func NewMultipleHostsSshClient

func NewMultipleHostsSshClient(hosts ...*Host) *MultipleHostsSshClient

Constructor method for MultipleHostsSshClient Use this client when dealing with multiple hosts asynchronously.

func (*MultipleHostsSshClient) Download

func (msc *MultipleHostsSshClient) Download(remotePath string, localPath string)

Downloads files/folders from all hosts of the MultipleHostsSshClient's list. They will be suffixed with the index of the host they are downloaded from

func (*MultipleHostsSshClient) Run

func (msc *MultipleHostsSshClient) Run(command string)

Executes shell command on all hosts in a separate goroutine for each. The result from execution is passed via the hosts' channels

func (*MultipleHostsSshClient) RunOnFile

func (msc *MultipleHostsSshClient) RunOnFile(filePath string,
	alterContentsFunction func(fileContent string) string)

Executes an function on a remote text file on all hosts. Can be used as an alternative of executing sed or awk on the remote machine. alterContentsFunction - the function to be executed, the content of the file as string will be passed to it and it should return the modified content.

func (*MultipleHostsSshClient) RunScript

func (msc *MultipleHostsSshClient) RunScript(filePath string)

Executes shell script on all hosts in a separate goroutine for each. The result from execution is passed via the hosts' channels

func (*MultipleHostsSshClient) Upload

func (msc *MultipleHostsSshClient) Upload(localPath string, remotePath string)

Uploads a file/folder to all hosts of the MultipleHostsSshClient. The sshResponse is passed via the channels of the hosts

type SshClient

type SshClient struct {
	Port          int
	StickySession bool
	Address       string
	// contains filtered or unexported fields
}

Port - 22 by default StickySession - false by default, if true sessions won't be closed automatically and one would have to use CloseSession()

func NewSshClient

func NewSshClient(address string, user string, authenticationType int, authentication string) (*SshClient, error)

Initializes the SshClient. This client is meant for synchronous usage with a single host. authenticationType is the type of authentication used, can be PasswordAuthentication or KeyAuthentication. authentication is the password or the path to the path to the key accorrding to the authenticationType.

func (*SshClient) CloseSession

func (s *SshClient) CloseSession() error

Closes the session, use only with StickySession set to true

func (*SshClient) Download

func (s *SshClient) Download(remotePath string, localPath string) (*SshResponse, error)

Downloads file/folder from the remote machine. Can be used as an alternative to scp. Returns an SshResponse and an error if any has occured.

func (*SshClient) Run

func (s *SshClient) Run(command string) (*SshResponse, error)

Executes shell command on the remote machine synchronously. Returns an SshResponse and an error if any has occured.

func (*SshClient) RunOnFile

func (s *SshClient) RunOnFile(filePath string, alterContentsFunction func(fileContent string) string) (*SshResponse, error)

Executes an function on a remote text file. Can be used as an alternative of executing sed or awk on the remote machine. alterContentsFunction is the function to be executed, the content of the file as string will be passed to it and it should return the modified content. Returns SshResponse and an error if any has occured.

func (*SshClient) RunScript

func (s *SshClient) RunScript(scriptPath string) (*SshResponse, error)

Executes a shell script file on the remote machine. It is copied in the tmp folder and ran in a single session. chmod +x is applied before running. Returns an SshResponse and an error if any has occured

func (*SshClient) Upload

func (s *SshClient) Upload(localPath string, remotePath string) (*SshResponse, error)

Uploads file/folder to the remote machine. Returns an SshResponse and an error if any has occured.

type SshConnectionError

type SshConnectionError struct {
	// contains filtered or unexported fields
}

Standard error returned on all ssh operations This means there was an error with the connection or the command returned an error code different from 0.

func NewSshConnectionError

func NewSshConnectionError(errorMessage string) *SshConnectionError

func (*SshConnectionError) Error

func (se *SshConnectionError) Error() string

Returns the error message of the SshConnectionError

type SshResponse

type SshResponse struct {
	Address string
	StdOut  bytes.Buffer
	StdErr  bytes.Buffer
}

Standard response returned from ssh operations

func NewSshResponse

func NewSshResponse(host string, session *ssh.Session) *SshResponse

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL