You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ssh_util.go 1.5 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package ssh
  2. import (
  3. "fmt"
  4. gossh "golang.org/x/crypto/ssh"
  5. "io"
  6. "log"
  7. "net"
  8. "os/exec"
  9. )
  10. // Cli 连接信息
  11. type Cli struct {
  12. User string
  13. Pwd string
  14. Addr string
  15. Client *gossh.Client
  16. Session *gossh.Session
  17. LastResult string
  18. }
  19. // Connect 连接对象
  20. func (c *Cli) Connect() (*Cli, error) {
  21. config := &gossh.ClientConfig{}
  22. config.SetDefaults()
  23. config.User = c.User
  24. config.Auth = []gossh.AuthMethod{gossh.Password(c.Pwd)}
  25. config.HostKeyCallback = func(hostname string, remote net.Addr, key gossh.PublicKey) error { return nil }
  26. client, err := gossh.Dial("tcp", c.Addr, config)
  27. if nil != err {
  28. return c, err
  29. }
  30. c.Client = client
  31. return c, nil
  32. }
  33. // Run 执行shell
  34. func (c Cli) Run(shell string) (string, error) {
  35. if c.Client == nil {
  36. if _, err := c.Connect(); err != nil {
  37. return "", err
  38. }
  39. }
  40. session, err := c.Client.NewSession()
  41. if err != nil {
  42. return "", err
  43. }
  44. // 关闭会话
  45. defer session.Close()
  46. buf, err := session.CombinedOutput(shell)
  47. c.LastResult = string(buf)
  48. return c.LastResult, err
  49. }
  50. func ExecCommand(strCommand string) string {
  51. cmd := exec.Command("/bin/bash", "-c", strCommand)
  52. stdout, _ := cmd.StdoutPipe()
  53. errReader, _ := cmd.StderrPipe()
  54. defer stdout.Close()
  55. if err := cmd.Start(); err != nil {
  56. log.Fatal(err)
  57. }
  58. cmdReader := io.MultiReader(stdout, errReader)
  59. outBytes, _ := io.ReadAll(cmdReader)
  60. if err := cmd.Wait(); err != nil {
  61. fmt.Println("err:", err.Error())
  62. }
  63. return string(outBytes)
  64. }

PCM is positioned as Software stack over Cloud, aiming to build the standards and ecology of heterogeneous cloud collaboration for JCC in a non intrusive and autonomous peer-to-peer manner.