ssh

package
v0.0.0-...-69b39bd Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2013 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Overview

Package ssh implements an SSH client and server.

SSH is a transport security protocol, an authentication protocol and a family of application protocols. The most typical application level protocol is a remote shell and this is specifically implemented. However, the multiplexed nature of SSH is exposed to users that wish to support others.

References:

[PROTOCOL.certkeys]: http://www.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys
[PROTOCOL.agent]:    http://www.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.agent
[SSH-PARAMETERS]:    http://www.iana.org/assignments/ssh-parameters/ssh-parameters.xml#ssh-parameters-1

Index

Examples

Constants

View Source
const (
	CertAlgoRSAv01      = "ssh-rsa-cert-v01@openssh.com"
	CertAlgoDSAv01      = "ssh-dss-cert-v01@openssh.com"
	CertAlgoECDSA256v01 = "ecdsa-sha2-nistp256-cert-v01@openssh.com"
	CertAlgoECDSA384v01 = "ecdsa-sha2-nistp384-cert-v01@openssh.com"
	CertAlgoECDSA521v01 = "ecdsa-sha2-nistp521-cert-v01@openssh.com"
)

These constants from [PROTOCOL.certkeys] represent the algorithm names for certificate types supported by this package.

View Source
const (
	UserCert = 1
	HostCert = 2
)

Certificate types are used to specify whether a certificate is for identification of a user or a host. Current identities are defined in [PROTOCOL.certkeys].

View Source
const (
	KeyAlgoRSA      = "ssh-rsa"
	KeyAlgoDSA      = "ssh-dss"
	KeyAlgoECDSA256 = "ecdsa-sha2-nistp256"
	KeyAlgoECDSA384 = "ecdsa-sha2-nistp384"
	KeyAlgoECDSA521 = "ecdsa-sha2-nistp521"
)

These constants represent the algorithm names for key types supported by this package.

View Source
const (
	VINTR         = 1
	VQUIT         = 2
	VERASE        = 3
	VKILL         = 4
	VEOF          = 5
	VEOL          = 6
	VEOL2         = 7
	VSTART        = 8
	VSTOP         = 9
	VSUSP         = 10
	VDSUSP        = 11
	VREPRINT      = 12
	VWERASE       = 13
	VLNEXT        = 14
	VFLUSH        = 15
	VSWTCH        = 16
	VSTATUS       = 17
	VDISCARD      = 18
	IGNPAR        = 30
	PARMRK        = 31
	INPCK         = 32
	ISTRIP        = 33
	INLCR         = 34
	IGNCR         = 35
	ICRNL         = 36
	IUCLC         = 37
	IXON          = 38
	IXANY         = 39
	IXOFF         = 40
	IMAXBEL       = 41
	ISIG          = 50
	ICANON        = 51
	XCASE         = 52
	ECHO          = 53
	ECHOE         = 54
	ECHOK         = 55
	ECHONL        = 56
	NOFLSH        = 57
	TOSTOP        = 58
	IEXTEN        = 59
	ECHOCTL       = 60
	ECHOKE        = 61
	PENDIN        = 62
	OPOST         = 70
	OLCUC         = 71
	ONLCR         = 72
	OCRNL         = 73
	ONOCR         = 74
	ONLRET        = 75
	CS7           = 90
	CS8           = 91
	PARENB        = 92
	PARODD        = 93
	TTY_OP_ISPEED = 128
	TTY_OP_OSPEED = 129
)

POSIX terminal mode flags as listed in RFC 4254 Section 8.

Variables

View Source
var DefaultCipherOrder = []string{
	"aes128-ctr", "aes192-ctr", "aes256-ctr",
	"arcfour256", "arcfour128",
}

Specifies a default set of ciphers and a preference order. This is based on OpenSSH's default client preference order, minus algorithms that are not implemented.

View Source
var DefaultMACOrder = []string{"hmac-sha1", "hmac-sha1-96"}

Specifies a default set of MAC algorithms and a preference order. This is based on RFC 4253, section 6.4, with the removal of the hmac-md5 variants as they have reached the end of their useful life.

Functions

func MarshalAuthorizedKey

func MarshalAuthorizedKey(key PublicKey) []byte

MarshalAuthorizedKey returns a byte stream suitable for inclusion in an OpenSSH authorized_keys file following the format specified in the sshd(8) manual page.

func MarshalPublicKey

func MarshalPublicKey(key PublicKey) []byte

MarshalPublicKey serializes a supported key or certificate for use by the SSH wire protocol. It can be used for comparison with the pubkey argument of ServerConfig's PublicKeyCallback as well as for generating an authorized_keys or host_keys file.

Types

type AgentClient

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

AgentClient provides a means to communicate with an ssh agent process based on the protocol described in [PROTOCOL.agent]?rev=1.6.

func NewAgentClient

func NewAgentClient(rw io.ReadWriter) *AgentClient

NewAgentClient creates and returns a new *AgentClient using the passed in io.ReadWriter as a connection to a ssh agent.

func (*AgentClient) RequestIdentities

func (ac *AgentClient) RequestIdentities() ([]*AgentKey, error)

RequestIdentities queries the agent for protocol 2 keys as defined in [PROTOCOL.agent] section 2.5.2.

func (*AgentClient) SignRequest

func (ac *AgentClient) SignRequest(key PublicKey, data []byte) ([]byte, error)

SignRequest requests the signing of data by the agent using a protocol 2 key as defined in [PROTOCOL.agent] section 2.6.2.

type AgentKey

type AgentKey struct {
	Comment string
	// contains filtered or unexported fields
}

AgentKey represents a protocol 2 key as defined in [PROTOCOL.agent], section 2.5.2.

func (*AgentKey) Key

func (ak *AgentKey) Key() (PublicKey, error)

Key returns an agent's public key as one of the supported key or certificate types.

func (*AgentKey) String

func (ak *AgentKey) String() string

String returns the storage form of an agent key with the format, base64 encoded serialized key, and the comment if it is not empty.

type Channel

type Channel interface {
	// Accept accepts the channel creation request.
	Accept() error
	// Reject rejects the channel creation request. After calling this, no
	// other methods on the Channel may be called. If they are then the
	// peer is likely to signal a protocol error and drop the connection.
	Reject(reason RejectionReason, message string) error

	// Read may return a ChannelRequest as an error.
	Read(data []byte) (int, error)
	Write(data []byte) (int, error)
	Close() error

	// Stderr returns an io.Writer that writes to this channel with the
	// extended data type set to stderr.
	Stderr() io.Writer

	// AckRequest either sends an ack or nack to the channel request.
	AckRequest(ok bool) error

	// ChannelType returns the type of the channel, as supplied by the
	// client.
	ChannelType() string
	// ExtraData returns the arbitrary payload for this channel, as supplied
	// by the client. This data is specific to the channel type.
	ExtraData() []byte
}

A Channel is an ordered, reliable, duplex stream that is multiplexed over an SSH connection. Channel.Read can return a ChannelRequest as an error.

type ChannelRequest

type ChannelRequest struct {
	Request   string
	WantReply bool
	Payload   []byte
}

ChannelRequest represents a request sent on a channel, outside of the normal stream of bytes. It may result from calling Read on a Channel.

func (ChannelRequest) Error

func (c ChannelRequest) Error() string

type ClientAuth

type ClientAuth interface {
	// contains filtered or unexported methods
}

A ClientAuth represents an instance of an RFC 4252 authentication method.

func ClientAuthAgent

func ClientAuthAgent(agent *AgentClient) ClientAuth

ClientAuthAgent returns a ClientAuth using public key authentication via an agent.

func ClientAuthKeyboardInteractive

func ClientAuthKeyboardInteractive(impl ClientKeyboardInteractive) ClientAuth

ClientAuthKeyboardInteractive returns a ClientAuth using a prompt/response sequence controlled by the server.

func ClientAuthKeyring

func ClientAuthKeyring(impl ClientKeyring) ClientAuth

ClientAuthKeyring returns a ClientAuth using public key authentication.

func ClientAuthPassword

func ClientAuthPassword(impl ClientPassword) ClientAuth

ClientAuthPassword returns a ClientAuth using password authentication.

type ClientConfig

type ClientConfig struct {
	// Rand provides the source of entropy for key exchange. If Rand is
	// nil, the cryptographic random reader in package crypto/rand will
	// be used.
	Rand io.Reader

	// The username to authenticate.
	User string

	// A slice of ClientAuth methods. Only the first instance
	// of a particular RFC 4252 method will be used during authentication.
	Auth []ClientAuth

	// HostKeyChecker, if not nil, is called during the cryptographic
	// handshake to validate the server's host key. A nil HostKeyChecker
	// implies that all host keys are accepted.
	HostKeyChecker HostKeyChecker

	// Cryptographic-related configuration.
	Crypto CryptoConfig

	// The identification string that will be used for the connection.
	// If empty, a reasonable default is used.
	ClientVersion string
}

A ClientConfig structure is used to configure a ClientConn. After one has been passed to an SSH function it must not be modified.

type ClientConn

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

ClientConn represents the client side of an SSH connection.

func Client

func Client(c net.Conn, config *ClientConfig) (*ClientConn, error)

Client returns a new SSH client connection using c as the underlying transport.

func Dial

func Dial(network, addr string, config *ClientConfig) (*ClientConn, error)

Dial connects to the given network address using net.Dial and then initiates a SSH handshake, returning the resulting client connection.

Example
// An SSH client is represented with a ClientConn. Currently only
// the "password" authentication method is supported.
//
// To authenticate with the remote server you must pass at least one
// implementation of ClientAuth via the Auth field in ClientConfig.
config := &ClientConfig{
	User: "username",
	Auth: []ClientAuth{
		// ClientAuthPassword wraps a ClientPassword implementation
		// in a type that implements ClientAuth.
		ClientAuthPassword(password("yourpassword")),
	},
}
client, err := Dial("tcp", "yourserver.com:22", config)
if err != nil {
	panic("Failed to dial: " + err.Error())
}

// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := client.NewSession()
if err != nil {
	panic("Failed to create session: " + err.Error())
}
defer session.Close()

// Once a Session is created, you can execute a single command on
// the remote side using the Run method.
var b bytes.Buffer
session.Stdout = &b
if err := session.Run("/usr/bin/whoami"); err != nil {
	panic("Failed to run: " + err.Error())
}
fmt.Println(b.String())
Output:

func (*ClientConn) Dial

func (c *ClientConn) Dial(n, addr string) (net.Conn, error)

Dial initiates a connection to the addr from the remote host. The resulting connection has a zero LocalAddr() and RemoteAddr().

func (*ClientConn) DialTCP

func (c *ClientConn) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error)

DialTCP connects to the remote address raddr on the network net, which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used as the local address for the connection.

func (*ClientConn) Listen

func (c *ClientConn) Listen(n, addr string) (net.Listener, error)

Listen requests the remote peer open a listening socket on addr. Incoming connections will be available by calling Accept on the returned net.Listener.

Example
config := &ClientConfig{
	User: "username",
	Auth: []ClientAuth{
		ClientAuthPassword(password("password")),
	},
}
// Dial your ssh server.
conn, err := Dial("tcp", "localhost:22", config)
if err != nil {
	log.Fatalf("unable to connect: %s", err)
}
defer conn.Close()

// Request the remote side to open port 8080 on all interfaces.
l, err := conn.Listen("tcp", "0.0.0.0:8080")
if err != nil {
	log.Fatalf("unable to register tcp forward: %v", err)
}
defer l.Close()

// Serve HTTP with your SSH server acting as a reverse proxy.
http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(resp, "Hello world!\n")
}))
Output:

func (*ClientConn) ListenTCP

func (c *ClientConn) ListenTCP(laddr *net.TCPAddr) (net.Listener, error)

ListenTCP requests the remote peer open a listening socket on laddr. Incoming connections will be available by calling Accept on the returned net.Listener.

func (*ClientConn) NewSession

func (c *ClientConn) NewSession() (*Session, error)

NewSession returns a new interactive session on the remote host.

type ClientKeyboardInteractive

type ClientKeyboardInteractive interface {
	// Challenge should print the questions, optionally disabling
	// echoing (eg. for passwords), and return all the answers.
	// Challenge may be called multiple times in a single
	// session. After successful authentication, the server may
	// send a challenge with no questions, for which the user and
	// instruction messages should be printed.  RFC 4256 section
	// 3.3 details how the UI should behave for both CLI and
	// GUI environments.
	Challenge(user, instruction string, questions []string, echos []bool) ([]string, error)
}

ClientKeyboardInteractive should prompt the user for the given questions.

type ClientKeyring

type ClientKeyring interface {
	// Key returns the i'th Publickey, or nil if no key exists at i.
	Key(i int) (key PublicKey, err error)

	// Sign returns a signature of the given data using the i'th key
	// and the supplied random source.
	Sign(i int, rand io.Reader, data []byte) (sig []byte, err error)
}

ClientKeyring implements access to a client key ring.

type ClientPassword

type ClientPassword interface {
	// Password returns the password to use for user.
	Password(user string) (password string, err error)
}

A ClientPassword implements access to a client's passwords.

type CryptoConfig

type CryptoConfig struct {
	// The allowed key exchanges algorithms. If unspecified then a
	// default set of algorithms is used.
	KeyExchanges []string

	// The allowed cipher algorithms. If unspecified then DefaultCipherOrder is
	// used.
	Ciphers []string

	// The allowed MAC algorithms. If unspecified then DefaultMACOrder is used.
	MACs []string
}

Cryptographic configuration common to both ServerConfig and ClientConfig.

type ExitError

type ExitError struct {
	Waitmsg
}

An ExitError reports unsuccessful completion of a remote command.

func (*ExitError) Error

func (e *ExitError) Error() string

type HostKeyChecker

type HostKeyChecker interface {
	// Check is called during the handshake to check server's
	// public key for unexpected changes. The hostKey argument is
	// in SSH wire format. It can be parsed using
	// ssh.ParsePublicKey. The address before DNS resolution is
	// passed in the addr argument, so the key can also be checked
	// against the hostname.
	Check(addr string, remote net.Addr, algorithm string, hostKey []byte) error
}

HostKeyChecker represents a database of known server host keys.

type Listener

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

A Listener implements a network listener (net.Listener) for SSH connections.

func Listen

func Listen(network, addr string, config *ServerConfig) (*Listener, error)

Listen creates an SSH listener accepting connections on the given network address using net.Listen.

Example
// An SSH server is represented by a ServerConfig, which holds
// certificate details and handles authentication of ServerConns.
config := &ServerConfig{
	PasswordCallback: func(conn *ServerConn, user, pass string) bool {
		return user == "testuser" && pass == "tiger"
	},
}

privateBytes, err := ioutil.ReadFile("id_rsa")
if err != nil {
	panic("Failed to load private key")
}

private, err := ParsePrivateKey(privateBytes)
if err != nil {
	panic("Failed to parse private key")
}

config.AddHostKey(private)

// Once a ServerConfig has been configured, connections can be
// accepted.
listener, err := Listen("tcp", "0.0.0.0:2022", config)
if err != nil {
	panic("failed to listen for connection")
}
sConn, err := listener.Accept()
if err != nil {
	panic("failed to accept incoming connection")
}
if err := sConn.Handshake(); err != nil {
	panic("failed to handshake")
}

// A ServerConn multiplexes several channels, which must
// themselves be Accepted.
for {
	// Accept reads from the connection, demultiplexes packets
	// to their corresponding channels and returns when a new
	// channel request is seen. Some goroutine must always be
	// calling Accept; otherwise no messages will be forwarded
	// to the channels.
	channel, err := sConn.Accept()
	if err != nil {
		panic("error from Accept")
	}

	// Channels have a type, depending on the application level
	// protocol intended. In the case of a shell, the type is
	// "session" and ServerShell may be used to present a simple
	// terminal interface.
	if channel.ChannelType() != "session" {
		channel.Reject(UnknownChannelType, "unknown channel type")
		continue
	}
	channel.Accept()

	term := terminal.NewTerminal(channel, "> ")
	serverTerm := &ServerTerminal{
		Term:    term,
		Channel: channel,
	}
	go func() {
		defer channel.Close()
		for {
			line, err := serverTerm.ReadLine()
			if err != nil {
				break
			}
			fmt.Println(line)
		}
	}()
}
Output:

func (*Listener) Accept

func (l *Listener) Accept() (*ServerConn, error)

Accept waits for and returns the next incoming SSH connection. The receiver should call Handshake() in another goroutine to avoid blocking the accepter.

func (*Listener) Addr

func (l *Listener) Addr() net.Addr

Addr returns the listener's network address.

func (*Listener) Close

func (l *Listener) Close() error

Close closes the listener.

type OpenSSHCertV01

type OpenSSHCertV01 struct {
	Nonce                   []byte
	Key                     PublicKey
	Serial                  uint64
	Type                    uint32
	KeyId                   string
	ValidPrincipals         []string
	ValidAfter, ValidBefore time.Time
	CriticalOptions         []tuple
	Extensions              []tuple
	Reserved                []byte
	SignatureKey            PublicKey
	Signature               *signature
}

An OpenSSHCertV01 represents an OpenSSH certificate as defined in [PROTOCOL.certkeys]?rev=1.8.

func (*OpenSSHCertV01) Marshal

func (cert *OpenSSHCertV01) Marshal() []byte

func (*OpenSSHCertV01) PrivateKeyAlgo

func (c *OpenSSHCertV01) PrivateKeyAlgo() string

func (*OpenSSHCertV01) PublicKeyAlgo

func (c *OpenSSHCertV01) PublicKeyAlgo() string

func (*OpenSSHCertV01) Verify

func (c *OpenSSHCertV01) Verify(data []byte, sig []byte) bool

type ParseError

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

ParseError results from a malformed SSH message.

func (ParseError) Error

func (p ParseError) Error() string

type PublicKey

type PublicKey interface {
	// PrivateKeyAlgo returns the name of the encryption system.
	PrivateKeyAlgo() string

	// PublicKeyAlgo returns the algorithm for the public key,
	// which may be different from PrivateKeyAlgo for certificates.
	PublicKeyAlgo() string

	// Marshal returns the serialized key data in SSH wire format,
	// without the name prefix.  Callers should typically use
	// MarshalPublicKey().
	Marshal() []byte

	// Verify that sig is a signature on the given data using this
	// key. This function will hash the data appropriately first.
	Verify(data []byte, sigBlob []byte) bool
}

PublicKey is an abstraction of different types of public keys.

func NewPublicKey

func NewPublicKey(k interface{}) (PublicKey, error)

NewPublicKey takes a pointer to rsa, dsa or ecdsa PublicKey and returns a corresponding ssh PublicKey instance. EC keys should use P256, P384 or P521.

func ParseAuthorizedKey

func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, ok bool)

ParseAuthorizedKeys parses a public key from an authorized_keys file used in OpenSSH according to the sshd(8) manual page.

func ParsePublicKey

func ParsePublicKey(in []byte) (out PublicKey, rest []byte, ok bool)

ParsePublicKey parses an SSH public key formatted for use in the SSH wire protocol according to RFC 4253, section 6.6.

type RejectionReason

type RejectionReason uint32

RejectionReason is an enumeration used when rejecting channel creation requests. See RFC 4254, section 5.1.

const (
	Prohibited RejectionReason = iota + 1
	ConnectionFailed
	UnknownChannelType
	ResourceShortage
)

func (RejectionReason) String

func (r RejectionReason) String() string

String converts the rejection reason to human readable form.

type ServerConfig

type ServerConfig struct {

	// Rand provides the source of entropy for key exchange. If Rand is
	// nil, the cryptographic random reader in package crypto/rand will
	// be used.
	Rand io.Reader

	// NoClientAuth is true if clients are allowed to connect without
	// authenticating.
	NoClientAuth bool

	// PasswordCallback, if non-nil, is called when a user attempts to
	// authenticate using a password. It may be called concurrently from
	// several goroutines.
	PasswordCallback func(conn *ServerConn, user, password string) bool

	// PublicKeyCallback, if non-nil, is called when a client attempts public
	// key authentication. It must return true if the given public key is
	// valid for the given user.
	PublicKeyCallback func(conn *ServerConn, user, algo string, pubkey []byte) bool

	// KeyboardInteractiveCallback, if non-nil, is called when
	// keyboard-interactive authentication is selected (RFC
	// 4256). The client object's Challenge function should be
	// used to query the user. The callback may offer multiple
	// Challenge rounds. To avoid information leaks, the client
	// should be presented a challenge even if the user is
	// unknown.
	KeyboardInteractiveCallback func(conn *ServerConn, user string, client ClientKeyboardInteractive) bool

	// Cryptographic-related configuration.
	Crypto CryptoConfig
	// contains filtered or unexported fields
}

func (*ServerConfig) AddHostKey

func (s *ServerConfig) AddHostKey(key Signer)

AddHostKey adds a private key as a host key. If an existing host key exists with the same algorithm, it is overwritten.

func (*ServerConfig) SetRSAPrivateKey

func (s *ServerConfig) SetRSAPrivateKey(pemBytes []byte) error

SetRSAPrivateKey sets the private key for a Server. A Server must have a private key configured in order to accept connections. The private key must be in the form of a PEM encoded, PKCS#1, RSA private key. The file "id_rsa" typically contains such a key.

type ServerConn

type ServerConn struct {

	// User holds the successfully authenticated user name.
	// It is empty if no authentication is used.  It is populated before
	// any authentication callback is called and not assigned to after that.
	User string

	// ClientVersion is the client's version, populated after
	// Handshake is called. It should not be modified.
	ClientVersion []byte
	// contains filtered or unexported fields
}

A ServerConn represents an incoming connection.

func Server

func Server(c net.Conn, config *ServerConfig) *ServerConn

Server returns a new SSH server connection using c as the underlying transport.

func (*ServerConn) Accept

func (s *ServerConn) Accept() (Channel, error)

Accept reads and processes messages on a ServerConn. It must be called in order to demultiplex messages to any resulting Channels.

func (*ServerConn) Handshake

func (s *ServerConn) Handshake() error

Handshake performs an SSH transport and client authentication on the given ServerConn.

type ServerTerminal

type ServerTerminal struct {
	Term    Terminal
	Channel Channel
}

ServerTerminal contains the state for running a terminal that is capable of reading lines of input.

func (*ServerTerminal) ReadLine

func (ss *ServerTerminal) ReadLine() (line string, err error)

ReadLine returns a line of input from the terminal.

func (*ServerTerminal) Write

func (ss *ServerTerminal) Write(buf []byte) (n int, err error)

type Session

type Session struct {
	// Stdin specifies the remote process's standard input.
	// If Stdin is nil, the remote process reads from an empty
	// bytes.Buffer.
	Stdin io.Reader

	// Stdout and Stderr specify the remote process's standard
	// output and error.
	//
	// If either is nil, Run connects the corresponding file
	// descriptor to an instance of ioutil.Discard. There is a
	// fixed amount of buffering that is shared for the two streams.
	// If either blocks it may eventually cause the remote
	// command to block.
	Stdout io.Writer
	Stderr io.Writer
	// contains filtered or unexported fields
}

A Session represents a connection to a remote command or shell.

func (Session) Close

func (c Session) Close() error

Close signals the intent to close the channel.

func (*Session) CombinedOutput

func (s *Session) CombinedOutput(cmd string) ([]byte, error)

CombinedOutput runs cmd on the remote host and returns its combined standard output and standard error.

func (*Session) Output

func (s *Session) Output(cmd string) ([]byte, error)

Output runs cmd on the remote host and returns its standard output.

func (*Session) RequestPty

func (s *Session) RequestPty(term string, h, w int, termmodes TerminalModes) error

RequestPty requests the association of a pty with the session on the remote host.

Example
// Create client config
config := &ClientConfig{
	User: "username",
	Auth: []ClientAuth{
		ClientAuthPassword(password("password")),
	},
}
// Connect to ssh server
conn, err := Dial("tcp", "localhost:22", config)
if err != nil {
	log.Fatalf("unable to connect: %s", err)
}
defer conn.Close()
// Create a session
session, err := conn.NewSession()
if err != nil {
	log.Fatalf("unable to create session: %s", err)
}
defer session.Close()
// Set up terminal modes
modes := TerminalModes{
	ECHO:          0,     // disable echoing
	TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
	TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
// Request pseudo terminal
if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
	log.Fatalf("request for pseudo terminal failed: %s", err)
}
// Start remote shell
if err := session.Shell(); err != nil {
	log.Fatalf("failed to start shell: %s", err)
}
Output:

func (*Session) RequestSubsystem

func (s *Session) RequestSubsystem(subsystem string) error

RequestSubsystem requests the association of a subsystem with the session on the remote host. A subsystem is a predefined command that runs in the background when the ssh session is initiated

func (*Session) Run

func (s *Session) Run(cmd string) error

Run runs cmd on the remote host. Typically, the remote server passes cmd to the shell for interpretation. A Session only accepts one call to Run, Start, Shell, Output, or CombinedOutput.

The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

If the command fails to run or doesn't complete successfully, the error is of type *ExitError. Other error types may be returned for I/O problems.

func (*Session) Setenv

func (s *Session) Setenv(name, value string) error

Setenv sets an environment variable that will be applied to any command executed by Shell or Run.

func (*Session) Shell

func (s *Session) Shell() error

Shell starts a login shell on the remote host. A Session only accepts one call to Run, Start, Shell, Output, or CombinedOutput.

func (*Session) Signal

func (s *Session) Signal(sig Signal) error

Signal sends the given signal to the remote process. sig is one of the SIG* constants.

func (*Session) Start

func (s *Session) Start(cmd string) error

Start runs cmd on the remote host. Typically, the remote server passes cmd to the shell for interpretation. A Session only accepts one call to Run, Start or Shell.

func (*Session) StderrPipe

func (s *Session) StderrPipe() (io.Reader, error)

StderrPipe returns a pipe that will be connected to the remote command's standard error when the command starts. There is a fixed amount of buffering that is shared between stdout and stderr streams. If the StderrPipe reader is not serviced fast enough it may eventually cause the remote command to block.

func (*Session) StdinPipe

func (s *Session) StdinPipe() (io.WriteCloser, error)

StdinPipe returns a pipe that will be connected to the remote command's standard input when the command starts.

func (*Session) StdoutPipe

func (s *Session) StdoutPipe() (io.Reader, error)

StdoutPipe returns a pipe that will be connected to the remote command's standard output when the command starts. There is a fixed amount of buffering that is shared between stdout and stderr streams. If the StdoutPipe reader is not serviced fast enough it may eventually cause the remote command to block.

func (*Session) Wait

func (s *Session) Wait() error

Wait waits for the remote command to exit.

The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

If the command fails to run or doesn't complete successfully, the error is of type *ExitError. Other error types may be returned for I/O problems.

type Signal

type Signal string
const (
	SIGABRT Signal = "ABRT"
	SIGALRM Signal = "ALRM"
	SIGFPE  Signal = "FPE"
	SIGHUP  Signal = "HUP"
	SIGILL  Signal = "ILL"
	SIGINT  Signal = "INT"
	SIGKILL Signal = "KILL"
	SIGPIPE Signal = "PIPE"
	SIGQUIT Signal = "QUIT"
	SIGSEGV Signal = "SEGV"
	SIGTERM Signal = "TERM"
	SIGUSR1 Signal = "USR1"
	SIGUSR2 Signal = "USR2"
)

POSIX signals as listed in RFC 4254 Section 6.10.

type Signer

type Signer interface {
	// PublicKey returns an associated PublicKey instance.
	PublicKey() PublicKey

	// Sign returns raw signature for the given data. This method
	// will apply the hash specified for the keytype to the data.
	Sign(rand io.Reader, data []byte) ([]byte, error)
}

A Signer is can create signatures that verify against a public key.

func NewSignerFromKey

func NewSignerFromKey(k interface{}) (Signer, error)

NewPrivateKey takes a pointer to rsa, dsa or ecdsa PrivateKey returns a corresponding Signer instance. EC keys should use P256, P384 or P521.

func ParsePrivateKey

func ParsePrivateKey(pemBytes []byte) (Signer, error)

ParsePublicKey parses a PEM encoded private key. It supports PKCS#1, RSA, DSA and ECDSA private keys.

type Terminal

type Terminal interface {
	ReadLine() (line string, err error)
	SetSize(x, y int)
	Write([]byte) (int, error)
}

A Terminal is capable of parsing and generating virtual terminal data from an SSH client.

type TerminalModes

type TerminalModes map[uint8]uint32

type UnexpectedMessageError

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

UnexpectedMessageError results when the SSH message that we received didn't match what we wanted.

func (UnexpectedMessageError) Error

func (u UnexpectedMessageError) Error() string

type Waitmsg

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

Waitmsg stores the information about an exited remote command as reported by Wait.

func (Waitmsg) ExitStatus

func (w Waitmsg) ExitStatus() int

ExitStatus returns the exit status of the remote command.

func (Waitmsg) Lang

func (w Waitmsg) Lang() string

Lang returns the language tag. See RFC 3066

func (Waitmsg) Msg

func (w Waitmsg) Msg() string

Msg returns the exit message given by the remote command

func (Waitmsg) Signal

func (w Waitmsg) Signal() string

Signal returns the exit signal of the remote command if it was terminated violently.

func (Waitmsg) String

func (w Waitmsg) String() string

Directories

Path Synopsis
Package terminal provides support functions for dealing with terminals, as commonly found on UNIX systems.
Package terminal provides support functions for dealing with terminals, as commonly found on UNIX systems.
This package contains integration tests for the code.google.com/p/go.crypto/ssh package.
This package contains integration tests for the code.google.com/p/go.crypto/ssh package.

Jump to

Keyboard shortcuts

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