ssh.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package cluster
  2. import (
  3. "bytes"
  4. "fmt"
  5. "log"
  6. "net"
  7. "golang.org/x/crypto/ssh"
  8. )
  9. func ssHConnect(user, password, host string, port int) (*ssh.Session, error) {
  10. var (
  11. auth []ssh.AuthMethod
  12. addr string
  13. clientConfig *ssh.ClientConfig
  14. client *ssh.Client
  15. session *ssh.Session
  16. err error
  17. )
  18. // get auth method
  19. auth = make([]ssh.AuthMethod, 0)
  20. auth = append(auth, ssh.Password(password))
  21. hostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  22. return nil
  23. }
  24. clientConfig = &ssh.ClientConfig{
  25. User: user,
  26. Auth: auth,
  27. // Timeout: 30 * time.Second,
  28. HostKeyCallback: hostKeyCallbk,
  29. }
  30. // connet to ssh
  31. addr = fmt.Sprintf("%s:%d", host, port)
  32. if client, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
  33. return nil, err
  34. }
  35. // create session
  36. if session, err = client.NewSession(); err != nil {
  37. return nil, err
  38. }
  39. return session, nil
  40. }
  41. // wget https://www.jianyu360.com/upload/extract_v3.tgz
  42. var sshstr = `
  43. #!/bin/bash
  44. cd /opt
  45. kill -9 $(pidof extract_fbs)
  46. rm -rf extract_fbs*
  47. wget http://172.17.162.36:9080/res/extract_fbs.tgz
  48. tar -xzvf extract_fbs.tgz
  49. cd /opt/extract_fbs
  50. chmod 777 extract_fbs
  51. nohup ./extract_fbs >/opt/extract_fbs/nohup 2>&1 &
  52. exit
  53. `
  54. func RunSsh(ip, password string, port int) {
  55. var stdOut, stdErr bytes.Buffer
  56. session, err := ssHConnect("root", password, ip, port)
  57. if err != nil {
  58. log.Println(err)
  59. }
  60. defer session.Close()
  61. session.Stdout = &stdOut
  62. session.Stderr = &stdErr
  63. //session.Run("wget https://www.jianyu360.com/upload/2017/04/22/201704221113374530.jpg")
  64. session.Run(sshstr)
  65. log.Println("ok")
  66. }