utils.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/rand"
  6. "os/exec"
  7. "strings"
  8. "syscall"
  9. "time"
  10. )
  11. func AccountShuffle(list []Account) {
  12. rand.Seed(time.Now().UnixNano())
  13. rand.Shuffle(len(list), func(i, j int) {
  14. list[i], list[j] = list[j], list[i]
  15. })
  16. }
  17. func CheckError(err error) {
  18. if err != nil {
  19. panic(err)
  20. }
  21. }
  22. // 运行Shell命令,设定超时时间(秒)
  23. func ShellCmdTimeout(timeout int, cmd string, args ...string) (stdout, stderr string, e error) {
  24. if len(cmd) == 0 {
  25. e = fmt.Errorf("cannot run a empty command")
  26. return
  27. }
  28. var out, err bytes.Buffer
  29. command := exec.Command(cmd, args...)
  30. command.Stdout = &out
  31. command.Stderr = &err
  32. command.Start()
  33. // 启动routine等待结束
  34. done := make(chan error)
  35. go func() { done <- command.Wait() }()
  36. // 启动routine持续打印输出
  37. // 设定超时时间,并select它
  38. after := time.After(time.Duration(timeout) * time.Second)
  39. select {
  40. case <-after:
  41. command.Process.Signal(syscall.SIGINT)
  42. time.Sleep(time.Second)
  43. command.Process.Kill()
  44. case <-done:
  45. }
  46. stdout = trimOutput(out)
  47. stderr = trimOutput(err)
  48. return
  49. }
  50. func trimOutput(buffer bytes.Buffer) string {
  51. return strings.TrimSpace(string(bytes.TrimRight(buffer.Bytes(), "\x00")))
  52. }