local.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 NewLocalNginx(nginx *models.Nginx) *LocalInstance {
  18. return &LocalInstance{nginx: nginx}
  19. }
  20. func (n *LocalInstance) Connect() error {
  21. return nil
  22. }
  23. func (n *LocalInstance) Close(onlySession bool) {
  24. }
  25. func (n *LocalInstance) SetNginx(nginx *models.Nginx) {
  26. n.nginx = nginx
  27. }
  28. func (n *LocalInstance) Run(cmd string) (string, error) {
  29. logs.Info("Run: ", cmd)
  30. command := exec.Command("/usr/bin/sh", "-c", cmd)
  31. out, err := command.CombinedOutput()
  32. if err != nil {
  33. logs.Warn("local run cmd fail", err, string(out))
  34. msg := fmt.Sprintf("%s;\n%s", err.Error(), string(out))
  35. return string(out), errors.New(msg)
  36. }
  37. logs.Info("Run resp", string(out))
  38. return string(out), nil
  39. }
  40. // SendFile Local 就是copy文件了
  41. func (n *LocalInstance) SendFile(src string, remote string) error {
  42. srcFile, err := os.Open(src)
  43. if err != nil {
  44. return err
  45. }
  46. defer srcFile.Close()
  47. base := filepath.Base(remote)
  48. if !utils.IsExist(base) {
  49. err = os.MkdirAll(base, 0777)
  50. }
  51. if err != nil {
  52. return err
  53. }
  54. dst, err := os.OpenFile(remote, os.O_CREATE|os.O_WRONLY, 0777)
  55. if err != nil {
  56. return err
  57. }
  58. defer dst.Close()
  59. _, err = io.Copy(dst, srcFile)
  60. return err
  61. }