1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
6 Package ssh implements an SSH client and server.
8 SSH is a transport security protocol, an authentication protocol and a
9 family of application protocols. The most typical application level
10 protocol is a remote shell and this is specifically implemented. However,
11 the multiplexed nature of SSH is exposed to users that wish to support
14 An SSH server is represented by a ServerConfig, which holds certificate
15 details and handles authentication of ServerConns.
17 config := new(ServerConfig)
18 config.PubKeyCallback = pubKeyAuth
19 config.PasswordCallback = passwordAuth
21 pemBytes, err := ioutil.ReadFile("id_rsa")
23 panic("Failed to load private key")
25 err = config.SetRSAPrivateKey(pemBytes)
27 panic("Failed to parse private key")
30 Once a ServerConfig has been configured, connections can be accepted.
32 listener := Listen("tcp", "0.0.0.0:2022", config)
33 sConn, err := listener.Accept()
35 panic("failed to accept incoming connection")
37 err = sConn.Handshake(conn)
39 panic("failed to handshake")
42 An SSH connection multiplexes several channels, which must be accepted themselves:
45 channel, err := sConn.Accept()
47 panic("error from Accept")
53 Accept reads from the connection, demultiplexes packets to their corresponding
54 channels and returns when a new channel request is seen. Some goroutine must
55 always be calling Accept; otherwise no messages will be forwarded to the
58 Channels have a type, depending on the application level protocol intended. In
59 the case of a shell, the type is "session" and ServerShell may be used to
60 present a simple terminal interface.
62 if channel.ChannelType() != "session" {
63 c.Reject(UnknownChannelType, "unknown channel type")
68 shell := NewServerShell(channel, "> ")
72 line, err := shell.ReadLine()
81 An SSH client is represented with a ClientConn. Currently only the "password"
82 authentication method is supported.
84 config := &ClientConfig{
88 client, err := Dial("yourserver.com:22", config)
90 Each ClientConn can support multiple interactive sessions, represented by a Session.
92 session, err := client.NewSession()
94 Once a Session is created, you can execute a single command on the remote side
95 using the Exec method.
97 if err := session.Exec("/usr/bin/whoami"); err != nil {
98 panic("Failed to exec: " + err.String())
100 reader := bufio.NewReader(session.Stdin)
101 line, _, _ := reader.ReadLine()