example_test.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "code.google.com/p/go.crypto/ssh/terminal"
  12. )
  13. func ExampleListen() {
  14. // An SSH server is represented by a ServerConfig, which holds
  15. // certificate details and handles authentication of ServerConns.
  16. config := &ServerConfig{
  17. PasswordCallback: func(conn *ServerConn, user, pass string) bool {
  18. return user == "testuser" && pass == "tiger"
  19. },
  20. }
  21. pemBytes, err := ioutil.ReadFile("id_rsa")
  22. if err != nil {
  23. panic("Failed to load private key")
  24. }
  25. if err = config.SetRSAPrivateKey(pemBytes); err != nil {
  26. panic("Failed to parse private key")
  27. }
  28. // Once a ServerConfig has been configured, connections can be
  29. // accepted.
  30. listener, err := Listen("tcp", "0.0.0.0:2022", config)
  31. if err != nil {
  32. panic("failed to listen for connection")
  33. }
  34. sConn, err := listener.Accept()
  35. if err != nil {
  36. panic("failed to accept incoming connection")
  37. }
  38. if err := sConn.Handshake(); err != nil {
  39. panic("failed to handshake")
  40. }
  41. // A ServerConn multiplexes several channels, which must
  42. // themselves be Accepted.
  43. for {
  44. // Accept reads from the connection, demultiplexes packets
  45. // to their corresponding channels and returns when a new
  46. // channel request is seen. Some goroutine must always be
  47. // calling Accept; otherwise no messages will be forwarded
  48. // to the channels.
  49. channel, err := sConn.Accept()
  50. if err != nil {
  51. panic("error from Accept")
  52. }
  53. // Channels have a type, depending on the application level
  54. // protocol intended. In the case of a shell, the type is
  55. // "session" and ServerShell may be used to present a simple
  56. // terminal interface.
  57. if channel.ChannelType() != "session" {
  58. channel.Reject(UnknownChannelType, "unknown channel type")
  59. continue
  60. }
  61. channel.Accept()
  62. term := terminal.NewTerminal(channel, "> ")
  63. serverTerm := &ServerTerminal{
  64. Term: term,
  65. Channel: channel,
  66. }
  67. go func() {
  68. defer channel.Close()
  69. for {
  70. line, err := serverTerm.ReadLine()
  71. if err != nil {
  72. break
  73. }
  74. fmt.Println(line)
  75. }
  76. }()
  77. }
  78. }
  79. func ExampleDial() {
  80. // An SSH client is represented with a ClientConn. Currently only
  81. // the "password" authentication method is supported.
  82. //
  83. // To authenticate with the remote server you must pass at least one
  84. // implementation of ClientAuth via the Auth field in ClientConfig.
  85. config := &ClientConfig{
  86. User: "username",
  87. Auth: []ClientAuth{
  88. // ClientAuthPassword wraps a ClientPassword implementation
  89. // in a type that implements ClientAuth.
  90. ClientAuthPassword(password("yourpassword")),
  91. },
  92. }
  93. client, err := Dial("tcp", "yourserver.com:22", config)
  94. if err != nil {
  95. panic("Failed to dial: " + err.Error())
  96. }
  97. // Each ClientConn can support multiple interactive sessions,
  98. // represented by a Session.
  99. session, err := client.NewSession()
  100. if err != nil {
  101. panic("Failed to create session: " + err.Error())
  102. }
  103. defer session.Close()
  104. // Once a Session is created, you can execute a single command on
  105. // the remote side using the Run method.
  106. var b bytes.Buffer
  107. session.Stdout = &b
  108. if err := session.Run("/usr/bin/whoami"); err != nil {
  109. panic("Failed to run: " + err.Error())
  110. }
  111. fmt.Println(b.String())
  112. }
  113. func ExampleClientConn_Listen() {
  114. config := &ClientConfig{
  115. User: "username",
  116. Auth: []ClientAuth{
  117. ClientAuthPassword(password("password")),
  118. },
  119. }
  120. // Dial your ssh server.
  121. conn, err := Dial("tcp", "localhost:22", config)
  122. if err != nil {
  123. log.Fatalf("unable to connect: %s", err)
  124. }
  125. defer conn.Close()
  126. // Request the remote side to open port 8080 on all interfaces.
  127. l, err := conn.Listen("tcp", "0.0.0.0:8080")
  128. if err != nil {
  129. log.Fatalf("unable to register tcp forward: %v", err)
  130. }
  131. defer l.Close()
  132. // Serve HTTP with your SSH server acting as a reverse proxy.
  133. http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
  134. fmt.Fprintf(resp, "Hello world!\n")
  135. }))
  136. }