utils: github.com/juju/utils/ssh Index | Files | Directories

package ssh

import "github.com/juju/utils/ssh"

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

Package Files

authorisedkeys.go clientkeys.go fingerprint.go generate.go run.go ssh.go ssh_gocrypto.go ssh_openssh.go stream.go stream_wrapper_unix.go

Constants

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.

const PublicKeySuffix = ".pub"

PublicKeySuffix is the file extension for public key files.

Variables

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

Cancelled is an error indicating that a command timed out.

var KeyBits = 2048

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

func AddKeys Uses

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 Uses

func ClearClientKeys()

ClearClientKeys clears the client keys cached in memory.

func Copy Uses

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

Copy is a short-cut for DefaultClient.Copy.

func CopyReader Uses

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 Uses

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 Uses

func EnsureJujuComment(key string) string

func ExecuteCommandOnMachine Uses

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 Uses

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 GoCryptoKnownHostsFile Uses

func GoCryptoKnownHostsFile() string

GoCryptoKnownHostsFile returns the known_hosts file used by the golang.org/x/crypto/ssh-based client by default.

func KeyFingerprint Uses

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 Uses

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 Uses

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 Uses

func PrivateKeyFiles() []string

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

func PublicKey Uses

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 Uses

func PublicKeyFiles() []string

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

func ReplaceKeys Uses

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 SetGoCryptoKnownHostsFile Uses

func SetGoCryptoKnownHostsFile(file string)

SetGoCryptoKnownHostsFile returns the known_hosts file used by the golang.org/x/crypto/ssh-based client.

func SplitAuthorisedKeys Uses

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.

func StripCRReader Uses

func StripCRReader(reader io.Reader) io.Reader

StripCRReader returns a new io.Reader wrapper that strips carriage returns.

func WrapStdin Uses

func WrapStdin(reader io.Reader) io.Reader

WrapStdin returns the original stdin stream on nix platforms.

type AuthorisedKey Uses

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

func ParseAuthorisedKey Uses

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 Uses

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 Uses

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 Uses

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

Command is a short-cut for DefaultClient.Command.

func (*Cmd) CombinedOutput Uses

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 Uses

func (c *Cmd) Kill() error

Kill kills the started command.

func (*Cmd) Output Uses

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

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

func (*Cmd) Run Uses

func (c *Cmd) Run() error

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

func (*Cmd) Start Uses

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 Uses

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 Uses

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 Uses

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 Uses

func (c *Cmd) Wait() error

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

type ExecParams Uses

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

ExecParams are used for the parameters for ExecuteCommandOnMachine.

type GoCryptoClient Uses

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 Uses

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 Uses

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

Command implements Client.Command.

func (*GoCryptoClient) Copy Uses

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 Uses

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

type OpenSSHClient Uses

type OpenSSHClient struct{}

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

func NewOpenSSHClient Uses

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 Uses

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

Command implements Client.Command.

func (*OpenSSHClient) Copy Uses

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

Copy implements Client.Copy.

type Options Uses

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

Options is a client-implementation independent SSH options set.

func (*Options) AllowPasswordAuthentication Uses

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 Uses

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) SetHostKeyAlgorithms Uses

func (o *Options) SetHostKeyAlgorithms(algos ...string)

SetHostKeyAlgorithms sets the host key types that the client will accept from the server, in order of preference. If not specified, the client implementation may choose its own defaults.

func (*Options) SetIdentities Uses

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 Uses

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 Uses

func (o *Options) SetPort(port int)

SetPort sets the SSH server port to connect to.

func (*Options) SetProxyCommand Uses

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

SetProxyCommand sets a command to execute to proxy traffic through.

func (*Options) SetStrictHostKeyChecking Uses

func (o *Options) SetStrictHostKeyChecking(value StrictHostChecksOption)

SetStrictHostKeyChecking sets the desired host key checking behaviour. It takes one of the StrictHostChecksOption constants. See also EnableStrictHostKeyChecking.

type RunningCmd Uses

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 Uses

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 Uses

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

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

func (*RunningCmd) WaitWithCancel Uses

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.

type StrictHostChecksOption Uses

type StrictHostChecksOption int

StrictHostChecksOption defines the possible values taken by Option.SetStrictHostKeyChecking().

const (
    // StrictHostChecksDefault configures the default,
    // implementation-specific, behaviour.
    //
    // For the OpenSSH implementation, this elides the
    // StrictHostKeyChecking option, which means the
    // user's personal configuration will be used.
    //
    // For the go.crypto implementation, the default is
    // the equivalent of "ask".
    StrictHostChecksDefault StrictHostChecksOption = iota

    // StrictHostChecksNo disables strict host key checking.
    StrictHostChecksNo

    // StrictHostChecksYes enabled strict host key checking
    // enabled. Target hosts must appear in known_hosts file or
    // connections will fail.
    StrictHostChecksYes

    // StrictHostChecksAsk will cause openssh to ask the user about
    // hosts that don't appear in known_hosts file.
    StrictHostChecksAsk
)

Directories

PathSynopsis
testing

Package ssh imports 31 packages (graph) and is imported by 451 packages. Updated 2018-08-27. Refresh now. Tools for package owners.