client.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package ssh
  2. import (
  3. "net"
  4. libio "github.com/fatedier/golib/io"
  5. "golang.org/x/crypto/ssh"
  6. )
  7. type TunnelClient struct {
  8. localAddr string
  9. sshServer string
  10. commands string
  11. sshConn *ssh.Client
  12. ln net.Listener
  13. }
  14. func NewTunnelClient(localAddr string, sshServer string, commands string) *TunnelClient {
  15. return &TunnelClient{
  16. localAddr: localAddr,
  17. sshServer: sshServer,
  18. commands: commands,
  19. }
  20. }
  21. func (c *TunnelClient) Start() error {
  22. config := &ssh.ClientConfig{
  23. User: "v0",
  24. HostKeyCallback: func(string, net.Addr, ssh.PublicKey) error { return nil },
  25. }
  26. conn, err := ssh.Dial("tcp", c.sshServer, config)
  27. if err != nil {
  28. return err
  29. }
  30. c.sshConn = conn
  31. l, err := conn.Listen("tcp", "0.0.0.0:80")
  32. if err != nil {
  33. return err
  34. }
  35. c.ln = l
  36. ch, req, err := conn.OpenChannel("session", []byte(""))
  37. if err != nil {
  38. return err
  39. }
  40. defer ch.Close()
  41. go ssh.DiscardRequests(req)
  42. type command struct {
  43. Cmd string
  44. }
  45. _, err = ch.SendRequest("exec", false, ssh.Marshal(command{Cmd: c.commands}))
  46. if err != nil {
  47. return err
  48. }
  49. go c.serveListener()
  50. return nil
  51. }
  52. func (c *TunnelClient) Close() {
  53. if c.sshConn != nil {
  54. _ = c.sshConn.Close()
  55. }
  56. if c.ln != nil {
  57. _ = c.ln.Close()
  58. }
  59. }
  60. func (c *TunnelClient) serveListener() {
  61. for {
  62. conn, err := c.ln.Accept()
  63. if err != nil {
  64. return
  65. }
  66. go c.hanldeConn(conn)
  67. }
  68. }
  69. func (c *TunnelClient) hanldeConn(conn net.Conn) {
  70. defer conn.Close()
  71. local, err := net.Dial("tcp", c.localAddr)
  72. if err != nil {
  73. return
  74. }
  75. _, _, _ = libio.Join(local, conn)
  76. }