ssh

package
v0.0.0-...-fc8c377 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2016 License: LGPL-3.0 Imports: 29 Imported by: 0

Documentation

Overview

Package ssh contains utilities for dealing with SSH connections, key management, and so on. All SSH-based command executions in Juju should use the Command/ScpCommand functions in this package.

Index

Constants

View Source
const JujuCommentPrefix = "Juju:"

Any ssh key added to the authorised keys list by Juju will have this prefix. This allows Juju to know which keys have been added externally and any such keys will always be retained by Juju when updating the authorised keys file.

View Source
const PublicKeySuffix = ".pub"

PublicKeySuffix is the file extension for public key files.

Variables

View Source
var Cancelled = errors.New("command timed out")

Cancelled is an error indicating that a command timed out.

View Source
var KeyBits = 2048

KeyBits is used to determine the number of bits to use for the RSA keys created using the GenerateKey function.

Functions

func AddKeys

func AddKeys(user string, newKeys ...string) error

AddKeys adds the specified ssh keys to the authorized_keys file for user. Returns an error if there is an issue with *any* of the supplied keys.

func ClearClientKeys

func ClearClientKeys()

ClearClientKeys clears the client keys cached in memory.

func Copy

func Copy(args []string, options *Options) error

Copy is a short-cut for DefaultClient.Copy.

func CopyReader

func CopyReader(host, filename string, r io.Reader, options *Options) error

CopyReader sends the reader's data to a file on the remote host over SSH.

func DeleteKeys

func DeleteKeys(user string, keyIds ...string) error

DeleteKeys removes the specified ssh keys from the authorized ssh keys file for user. keyIds may be either key comments or fingerprints. Returns an error if there is an issue with *any* of the keys to delete.

func EnsureJujuComment

func EnsureJujuComment(key string) string

func ExecuteCommandOnMachine

func ExecuteCommandOnMachine(args ExecParams) (utilexec.ExecResponse, error)

ExecuteCommandOnMachine will execute the command passed through on the host specified. This is done using ssh, and passing the commands through /bin/bash. If the command is not finished within the timeout specified, an error is returned. Any output captured during that time is also returned in the remote response.

func GenerateKey

func GenerateKey(comment string) (private, public string, err error)

GenerateKey makes a 2048 bit RSA no-passphrase SSH capable key. The bit size is actually controlled by the KeyBits var. The private key returned is encoded to ASCII using the PKCS1 encoding. The public key is suitable to be added into an authorized_keys file, and has the comment passed in as the comment part of the key.

func KeyFingerprint

func KeyFingerprint(key string) (fingerprint, comment string, err error)

KeyFingerprint returns the fingerprint and comment for the specified key in authorized_key format. Fingerprints are generated according to RFC4716. See ttp://www.ietf.org/rfc/rfc4716.txt, section 4.

func ListKeys

func ListKeys(user string, mode ListMode) ([]string, error)

ListKeys returns either the full keys or key comments from the authorized ssh keys file for user.

func LoadClientKeys

func LoadClientKeys(dir string) error

LoadClientKeys loads the client SSH keys from the specified directory, and caches them as a process-wide global. If the directory does not exist, it is created; if the directory did not exist, or contains no keys, it is populated with a new key pair.

If the directory exists, then all pairs of files where one has the same name as the other + ".pub" will be loaded as private/public key pairs.

Calls to LoadClientKeys will clear the previously loaded keys, and recompute the keys.

func PrivateKeyFiles

func PrivateKeyFiles() []string

PrivateKeyFiles returns the filenames of private SSH keys loaded by LoadClientKeys.

func PublicKey

func PublicKey(privateKey []byte, comment string) (string, error)

PublicKey returns the public key for any private key. The public key is suitable to be added into an authorized_keys file, and has the comment passed in as the comment part of the key.

func PublicKeyFiles

func PublicKeyFiles() []string

PublicKeyFiles returns the filenames of public SSH keys loaded by LoadClientKeys.

func ReplaceKeys

func ReplaceKeys(user string, newKeys ...string) error

ReplaceKeys writes the specified ssh keys to the authorized_keys file for user, replacing any that are already there. Returns an error if there is an issue with *any* of the supplied keys.

func SplitAuthorisedKeys

func SplitAuthorisedKeys(keyData string) []string

SplitAuthorisedKeys extracts a key slice from the specified key data, by splitting the key data into lines and ignoring comments and blank lines.

Types

type AuthorisedKey

type AuthorisedKey struct {
	Type    string
	Key     []byte
	Comment string
}

func ParseAuthorisedKey

func ParseAuthorisedKey(line string) (*AuthorisedKey, error)

ParseAuthorisedKey parses a non-comment line from an authorized_keys file and returns the constituent parts. Based on description in "man sshd".

type Client

type Client interface {
	// Command returns a Command for executing a command
	// on the specified host. Each Command is executed
	// within its own SSH session.
	//
	// Host is specified in the format [user@]host.
	Command(host string, command []string, options *Options) *Cmd

	// Copy copies file(s) between local and remote host(s).
	// Paths are specified in the scp format, [[user@]host:]path. If
	// any extra arguments are specified in extraArgs, they are passed
	// verbatim.
	Copy(args []string, options *Options) error
}

Client is an interface for SSH clients to implement

var DefaultClient Client

DefaultClient is the default SSH client for the process.

If the OpenSSH client is found in $PATH, then it will be used for DefaultClient; otherwise, DefaultClient will use an embedded client based on go.crypto/ssh.

type Cmd

type Cmd struct {
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
	// contains filtered or unexported fields
}

Cmd represents a command to be (or being) executed on a remote host.

func Command

func Command(host string, command []string, options *Options) *Cmd

Command is a short-cut for DefaultClient.Command.

func (*Cmd) CombinedOutput

func (c *Cmd) CombinedOutput() ([]byte, error)

CombinedOutput runs the command, and returns the combined stdout/stderr output and result of executing the command.

func (*Cmd) Kill

func (c *Cmd) Kill() error

Kill kills the started command.

func (*Cmd) Output

func (c *Cmd) Output() ([]byte, error)

Output runs the command, and returns the stdout output and result of executing the command.

func (*Cmd) Run

func (c *Cmd) Run() error

Run runs the command, and returns the result as an error.

func (*Cmd) Start

func (c *Cmd) Start() error

Start starts the command running, but does not wait for it to complete. If the command could not be started, an error is returned.

func (*Cmd) StderrPipe

func (c *Cmd) StderrPipe() (io.ReadCloser, error)

StderrPipe creates a pipe and connects it to the command's stderr. The write end of the pipe is assigned to c.Stderr.

func (*Cmd) StdinPipe

func (c *Cmd) StdinPipe() (io.WriteCloser, error)

StdinPipe creates a pipe and connects it to the command's stdin. The read end of the pipe is assigned to c.Stdin.

func (*Cmd) StdoutPipe

func (c *Cmd) StdoutPipe() (io.ReadCloser, error)

StdoutPipe creates a pipe and connects it to the command's stdout. The write end of the pipe is assigned to c.Stdout.

func (*Cmd) Wait

func (c *Cmd) Wait() error

Wait waits for the started command to complete, and returns the result as an error.

type ExecParams

type ExecParams struct {
	IdentityFile string
	Host         string
	Command      string
	Timeout      time.Duration
}

ExecParams are used for the parameters for ExecuteCommandOnMachine.

type GoCryptoClient

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

GoCryptoClient is an implementation of Client that uses the embedded go.crypto/ssh SSH client.

GoCryptoClient is intentionally limited in the functionality that it enables, as it is currently intended to be used only for non-interactive command execution.

func NewGoCryptoClient

func NewGoCryptoClient(signers ...ssh.Signer) (*GoCryptoClient, error)

NewGoCryptoClient creates a new GoCryptoClient.

If no signers are specified, NewGoCryptoClient will use the private key generated by LoadClientKeys.

func (*GoCryptoClient) Command

func (c *GoCryptoClient) Command(host string, command []string, options *Options) *Cmd

Command implements Client.Command.

func (*GoCryptoClient) Copy

func (c *GoCryptoClient) Copy(args []string, options *Options) error

Copy implements Client.Copy.

Copy is currently unimplemented, and will always return an error.

type ListMode

type ListMode bool
var (
	FullKeys     ListMode = true
	Fingerprints ListMode = false
)

type OpenSSHClient

type OpenSSHClient struct{}

OpenSSHClient is an implementation of Client that uses the ssh and scp executables found in $PATH.

func NewOpenSSHClient

func NewOpenSSHClient() (*OpenSSHClient, error)

NewOpenSSHClient creates a new OpenSSHClient. If the ssh and scp programs cannot be found in $PATH, then an error is returned.

func (*OpenSSHClient) Command

func (c *OpenSSHClient) Command(host string, command []string, options *Options) *Cmd

Command implements Client.Command.

func (*OpenSSHClient) Copy

func (c *OpenSSHClient) Copy(args []string, userOptions *Options) error

Copy implements Client.Copy.

type Options

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

Options is a client-implementation independent SSH options set.

func (*Options) AllowPasswordAuthentication

func (o *Options) AllowPasswordAuthentication()

AllowPasswordAuthentication allows the SSH client to prompt the user for a password.

Password authentication is disallowed by default.

func (*Options) EnablePTY

func (o *Options) EnablePTY()

EnablePTY forces the allocation of a pseudo-TTY.

Forcing a pseudo-TTY is required, for example, for sudo prompts on the target host.

func (*Options) SetIdentities

func (o *Options) SetIdentities(identityFiles ...string)

SetIdentities sets a sequence of paths to private key/identity files to use when attempting login. Client implementations may attempt to use additional identities, but must give preference to the ones specified here.

func (*Options) SetKnownHostsFile

func (o *Options) SetKnownHostsFile(file string)

SetKnownHostsFile sets the host's fingerprint to be saved in the given file.

Host fingerprints are saved in ~/.ssh/known_hosts by default.

func (*Options) SetPort

func (o *Options) SetPort(port int)

SetPort sets the SSH server port to connect to.

func (*Options) SetProxyCommand

func (o *Options) SetProxyCommand(command ...string)

SetProxyCommand sets a command to execute to proxy traffic through.

type RunningCmd

type RunningCmd struct {
	// SSHCmd is the command the was started.
	SSHCmd *Cmd

	// Stdout and Stderr are the output streams the command is using.
	Stdout bytes.Buffer
	Stderr bytes.Buffer
}

RunningCmd represents a command that has been started.

func StartCommandOnMachine

func StartCommandOnMachine(params ExecParams) (*RunningCmd, error)

StartCommandOnMachine executes the command on the given host. The command is run in a Bash shell over an SSH connection. All output is captured. A RunningCmd is returned that may be used to wait for the command to finish running.

func (*RunningCmd) Wait

func (cmd *RunningCmd) Wait() (result utilexec.ExecResponse, _ error)

Wait waits for the command to complete and returns the result.

func (*RunningCmd) WaitWithCancel

func (cmd *RunningCmd) WaitWithCancel(cancel <-chan struct{}) (utilexec.ExecResponse, error)

WaitWithCancel waits for the command to complete and returns the result. If cancel is closed before the result was returned, then it takes longer than the provided timeout then Cancelled is returned.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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