example_test.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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.
  4. package ssh_test
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "net"
  11. "net/http"
  12. "github.com/gogits/gogs/modules/crypto/ssh"
  13. "github.com/gogits/gogs/modules/crypto/ssh/terminal"
  14. )
  15. func ExampleNewServerConn() {
  16. // An SSH server is represented by a ServerConfig, which holds
  17. // certificate details and handles authentication of ServerConns.
  18. config := &ssh.ServerConfig{
  19. PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
  20. // Should use constant-time compare (or better, salt+hash) in
  21. // a production setting.
  22. if c.User() == "testuser" && string(pass) == "tiger" {
  23. return nil, nil
  24. }
  25. return nil, fmt.Errorf("password rejected for %q", c.User())
  26. },
  27. }
  28. privateBytes, err := ioutil.ReadFile("id_rsa")
  29. if err != nil {
  30. panic("Failed to load private key")
  31. }
  32. private, err := ssh.ParsePrivateKey(privateBytes)
  33. if err != nil {
  34. panic("Failed to parse private key")
  35. }
  36. config.AddHostKey(private)
  37. // Once a ServerConfig has been configured, connections can be
  38. // accepted.
  39. listener, err := net.Listen("tcp", "0.0.0.0:2022")
  40. if err != nil {
  41. panic("failed to listen for connection")
  42. }
  43. nConn, err := listener.Accept()
  44. if err != nil {
  45. panic("failed to accept incoming connection")
  46. }
  47. // Before use, a handshake must be performed on the incoming
  48. // net.Conn.
  49. _, chans, reqs, err := ssh.NewServerConn(nConn, config)
  50. if err != nil {
  51. panic("failed to handshake")
  52. }
  53. // The incoming Request channel must be serviced.
  54. go ssh.DiscardRequests(reqs)
  55. // Service the incoming Channel channel.
  56. for newChannel := range chans {
  57. // Channels have a type, depending on the application level
  58. // protocol intended. In the case of a shell, the type is
  59. // "session" and ServerShell may be used to present a simple
  60. // terminal interface.
  61. if newChannel.ChannelType() != "session" {
  62. newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
  63. continue
  64. }
  65. channel, requests, err := newChannel.Accept()
  66. if err != nil {
  67. panic("could not accept channel.")
  68. }
  69. // Sessions have out-of-band requests such as "shell",
  70. // "pty-req" and "env". Here we handle only the
  71. // "shell" request.
  72. go func(in <-chan *ssh.Request) {
  73. for req := range in {
  74. ok := false
  75. switch req.Type {
  76. case "shell":
  77. ok = true
  78. if len(req.Payload) > 0 {
  79. // We don't accept any
  80. // commands, only the
  81. // default shell.
  82. ok = false
  83. }
  84. }
  85. req.Reply(ok, nil)
  86. }
  87. }(requests)
  88. term := terminal.NewTerminal(channel, "> ")
  89. go func() {
  90. defer channel.Close()
  91. for {
  92. line, err := term.ReadLine()
  93. if err != nil {
  94. break
  95. }
  96. fmt.Println(line)
  97. }
  98. }()
  99. }
  100. }
  101. func ExampleDial() {
  102. // An SSH client is represented with a ClientConn. Currently only
  103. // the "password" authentication method is supported.
  104. //
  105. // To authenticate with the remote server you must pass at least one
  106. // implementation of AuthMethod via the Auth field in ClientConfig.
  107. config := &ssh.ClientConfig{
  108. User: "username",
  109. Auth: []ssh.AuthMethod{
  110. ssh.Password("yourpassword"),
  111. },
  112. }
  113. client, err := ssh.Dial("tcp", "yourserver.com:22", config)
  114. if err != nil {
  115. panic("Failed to dial: " + err.Error())
  116. }
  117. // Each ClientConn can support multiple interactive sessions,
  118. // represented by a Session.
  119. session, err := client.NewSession()
  120. if err != nil {
  121. panic("Failed to create session: " + err.Error())
  122. }
  123. defer session.Close()
  124. // Once a Session is created, you can execute a single command on
  125. // the remote side using the Run method.
  126. var b bytes.Buffer
  127. session.Stdout = &b
  128. if err := session.Run("/usr/bin/whoami"); err != nil {
  129. panic("Failed to run: " + err.Error())
  130. }
  131. fmt.Println(b.String())
  132. }
  133. func ExampleClient_Listen() {
  134. config := &ssh.ClientConfig{
  135. User: "username",
  136. Auth: []ssh.AuthMethod{
  137. ssh.Password("password"),
  138. },
  139. }
  140. // Dial your ssh server.
  141. conn, err := ssh.Dial("tcp", "localhost:22", config)
  142. if err != nil {
  143. log.Fatalf("unable to connect: %s", err)
  144. }
  145. defer conn.Close()
  146. // Request the remote side to open port 8080 on all interfaces.
  147. l, err := conn.Listen("tcp", "0.0.0.0:8080")
  148. if err != nil {
  149. log.Fatalf("unable to register tcp forward: %v", err)
  150. }
  151. defer l.Close()
  152. // Serve HTTP with your SSH server acting as a reverse proxy.
  153. http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
  154. fmt.Fprintf(resp, "Hello world!\n")
  155. }))
  156. }
  157. func ExampleSession_RequestPty() {
  158. // Create client config
  159. config := &ssh.ClientConfig{
  160. User: "username",
  161. Auth: []ssh.AuthMethod{
  162. ssh.Password("password"),
  163. },
  164. }
  165. // Connect to ssh server
  166. conn, err := ssh.Dial("tcp", "localhost:22", config)
  167. if err != nil {
  168. log.Fatalf("unable to connect: %s", err)
  169. }
  170. defer conn.Close()
  171. // Create a session
  172. session, err := conn.NewSession()
  173. if err != nil {
  174. log.Fatalf("unable to create session: %s", err)
  175. }
  176. defer session.Close()
  177. // Set up terminal modes
  178. modes := ssh.TerminalModes{
  179. ssh.ECHO: 0, // disable echoing
  180. ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
  181. ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
  182. }
  183. // Request pseudo terminal
  184. if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
  185. log.Fatalf("request for pseudo terminal failed: %s", err)
  186. }
  187. // Start remote shell
  188. if err := session.Shell(); err != nil {
  189. log.Fatalf("failed to start shell: %s", err)
  190. }
  191. }