Guest User

Untitled

a guest
Aug 24th, 2018
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "bufio"
  5. "bytes"
  6. "fmt"
  7. "log"
  8. "net"
  9. "os"
  10. "os/signal"
  11.  
  12. "golang.org/x/crypto/ssh"
  13. )
  14.  
  15. func main() {
  16. server := "host:port"
  17. user := "user"
  18. password := "password"
  19.  
  20. // Setup ssh config auth with username/password
  21. config := &ssh.ClientConfig{
  22. User: user,
  23. Auth: []ssh.AuthMethod{
  24. ssh.Password(password),
  25. },
  26. HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  27. return nil
  28. },
  29. }
  30.  
  31. // Connect to ssh server
  32. conn, err := ssh.Dial("tcp", server, config)
  33. if err != nil {
  34. panic("Failed to dail: " + err.Error())
  35. }
  36. fmt.Println("Connected")
  37.  
  38. // Create new ssh session
  39. session, err := conn.NewSession()
  40. if err != nil {
  41. panic("Failed to create session: " + err.Error())
  42. }
  43. fmt.Println("Create new session")
  44.  
  45. // For sending command ex: in.Write(cmd)
  46. in, _ := session.StdinPipe()
  47.  
  48. var b bytes.Buffer
  49. session.Stdout = &b
  50. session.Stdout = os.Stdout
  51.  
  52. // Start shell
  53. if err := session.Shell(); err != nil {
  54. log.Fatalf("failed to start shell: %s", err)
  55. }
  56.  
  57. // Ctrl-C for stop and disconnect ssh
  58. c := make(chan os.Signal, 1)
  59. signal.Notify(c, os.Interrupt)
  60. go func() {
  61. for {
  62. <-c
  63. fmt.Fprint(in, "\n")
  64. fmt.Println("\nDisconnecting...")
  65. session.Close()
  66. conn.Close()
  67. os.Exit(3)
  68. }
  69. }()
  70.  
  71. // Customize this for receive or send command
  72. for {
  73. reader := bufio.NewReader(os.Stdin)
  74. str, _ := reader.ReadString('\n')
  75. fmt.Fprint(in, str)
  76. // fmt.Println(b.String())
  77. }
  78. }
Add Comment
Please, Sign In to add comment