local.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package nginx
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/astaxie/beego/logs"
  6. "io"
  7. "nginx-ui/server/models"
  8. "nginx-ui/server/utils"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. )
  13. // LocalInstance 本地实例
  14. type LocalInstance struct {
  15. nginx *models.Nginx
  16. }
  17. func (n *LocalInstance) Connect() error {
  18. return nil
  19. }
  20. func (n *LocalInstance) Close(onlySession bool) {
  21. }
  22. func (n *LocalInstance) SetNginx(nginx *models.Nginx) {
  23. n.nginx = nginx
  24. }
  25. func (n *LocalInstance) Run(cmd string) (string, error) {
  26. logs.Info("Run: ", cmd)
  27. command := exec.Command("/usr/bin/sh", "-c", cmd)
  28. out, err := command.CombinedOutput()
  29. if err != nil {
  30. logs.Warn("local run cmd fail", err, string(out))
  31. msg := fmt.Sprintf("%s;\n%s", err.Error(), string(out))
  32. return string(out), errors.New(msg)
  33. }
  34. logs.Info("Run resp", string(out))
  35. return string(out), nil
  36. }
  37. // SendFile Local 就是copy文件了
  38. func (n *LocalInstance) SendFile(src string, remote string) error {
  39. srcFile, err := os.Open(src)
  40. if err != nil {
  41. return err
  42. }
  43. defer srcFile.Close()
  44. base := filepath.Base(remote)
  45. if !utils.IsExist(base) {
  46. err = os.MkdirAll(base, 0777)
  47. }
  48. if err != nil {
  49. return err
  50. }
  51. dst, err := os.OpenFile(remote, os.O_CREATE|os.O_WRONLY, 0777)
  52. if err != nil {
  53. return err
  54. }
  55. defer dst.Close()
  56. _, err = io.Copy(dst, srcFile)
  57. return err
  58. }