client.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package main
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "os"
  10. "os/exec"
  11. "os/signal"
  12. "runtime"
  13. "strings"
  14. "sync/atomic"
  15. "syscall"
  16. "time"
  17. "github.com/denisbrodbeck/machineid"
  18. "github.com/google/uuid"
  19. "github.com/peterh/liner"
  20. )
  21. const MODULE_NAME = "YFKJ_SSH_CLIENT"
  22. var (
  23. coupler *MQTTCoupler
  24. Version = "1.0.0.1"
  25. BuildTime = "unknown"
  26. ErrBrokerAddressEmpty = errors.New("mqtt server address is empty")
  27. ErrIMEINotAvailable = errors.New("device imei is not available")
  28. )
  29. func main() {
  30. if IsArgsParam("-h") {
  31. help()
  32. return
  33. }
  34. if IsArgsParam("-v") {
  35. fmt.Println("程序版本:", Version, "\n构建时间:", BuildTime)
  36. return
  37. }
  38. devIMEI := GetArgsParamStr("-c", "")
  39. if devIMEI == "" {
  40. help()
  41. return
  42. }
  43. if err := loadAppConfig(); err != nil {
  44. fmt.Printf("[%s] 错误: %v!!\n", MODULE_NAME, err)
  45. return
  46. }
  47. if CfgServers.MQTTSrv.Address == "" {
  48. fmt.Printf("[%s] 错误: %v!!\n", MODULE_NAME, ErrBrokerAddressEmpty)
  49. return
  50. }
  51. ctx, cancel := context.WithCancel(context.Background())
  52. coupler = &MQTTCoupler{
  53. ctx: ctx,
  54. cancel: cancel,
  55. broker: CfgServers.MQTTSrv.Address,
  56. username: CfgServers.MQTTSrv.Username,
  57. password: CfgServers.MQTTSrv.Password,
  58. clientID: uuid.New().String(),
  59. imei: devIMEI,
  60. cwd: "/",
  61. }
  62. id, err := machineid.ID()
  63. if err == nil {
  64. coupler.clientID = id
  65. }
  66. if err := coupler.init2(); err != nil {
  67. fmt.Printf("[%s] 错误: %v\n!!", MODULE_NAME, err)
  68. return
  69. }
  70. var pingState atomic.Bool
  71. heartbeatLoop(&pingState) // -启动-设备在线-心跳检测-
  72. for {
  73. if pingState.Load() { //// 等待成功连接上目标设备卍
  74. break
  75. }
  76. fmt.Printf("[%s] 正在尝试连接设备...\n", MODULE_NAME)
  77. time.Sleep(1 * time.Second)
  78. }
  79. term(&pingState) /////////////////// 启动终端模拟器卍
  80. }
  81. func term(pingState *atomic.Bool) {
  82. var executing atomic.Bool // 是否有正在执行中的命令
  83. var interrupted atomic.Bool // 用户是否按键取消了命令
  84. interruptLoop(&executing, &interrupted) // Ctrl+C卍
  85. printWelcome(pingState)
  86. line := liner.NewLiner()
  87. defer line.Close()
  88. line.SetCtrlCAborts(false)
  89. line.SetTabCompletionStyle(liner.TabCircular)
  90. historyFile := "history.txt"
  91. var history []string
  92. if f, err := os.Open(historyFile); err == nil {
  93. scanner := bufio.NewScanner(f)
  94. for scanner.Scan() {
  95. cmd := strings.TrimSpace(scanner.Text())
  96. if cmd != "" {
  97. history = append(history, cmd)
  98. line.AppendHistory(cmd)
  99. }
  100. }
  101. f.Close()
  102. }
  103. defer func() {
  104. if f, err := os.Create(historyFile); err == nil {
  105. line.WriteHistory(f)
  106. f.Close()
  107. }
  108. }()
  109. line.SetCompleter(func(input string) []string { // 补全
  110. var matches []string
  111. for _, cmd := range history {
  112. if strings.HasPrefix(cmd, input) {
  113. matches = append(matches, cmd)
  114. }
  115. }
  116. return matches
  117. })
  118. for {
  119. if !pingState.Load() {
  120. fmt.Printf("[%s] 目标设备连接丢失!!\n", MODULE_NAME)
  121. break
  122. }
  123. if interrupted.Swap(false) {
  124. fmt.Println("^C")
  125. }
  126. prompt := fmt.Sprintf("root@%s:%s# ", coupler.imei, coupler.cwd)
  127. input, err := line.Prompt(prompt) /// 等待用户输入指令
  128. if err == nil {
  129. goto inputOK
  130. }
  131. if err == io.EOF { ////////////////// Ctrl+D 按键处理
  132. _, _ = coupler.quit()
  133. fmt.Println("bye")
  134. break
  135. }
  136. fmt.Println("读取用户输入失败:", err)
  137. continue
  138. inputOK:
  139. input = strings.TrimSpace(input)
  140. if input == "" {
  141. continue
  142. }
  143. line.AppendHistory(input) ///// 保存用户输入的历史命令
  144. history = append(history, input) ///// 本次也立刻生效
  145. if input == "exit" || input == "quit" {
  146. _, _ = coupler.quit()
  147. break
  148. }
  149. if input == "clear" {
  150. clearScreen()
  151. continue
  152. }
  153. executing.Store(true)
  154. result, err := coupler.exec(input)
  155. executing.Store(false)
  156. if err != nil {
  157. fmt.Printf("执行错误: %v\n", err)
  158. continue
  159. }
  160. if result.Stdout != "" {
  161. fmt.Print(result.Stdout)
  162. }
  163. if result.Stderr != "" {
  164. fmt.Fprintln(os.Stderr, result.Stderr)
  165. }
  166. if result.ExitCode == 124 {
  167. fmt.Println("command timeout")
  168. }
  169. if result.Cwd != "" {
  170. coupler.cwd = result.Cwd
  171. }
  172. }
  173. }
  174. func help() {
  175. h := `
  176. -h 显示帮助提示
  177. -v 当前程序版本
  178. -c 连接目标设备(IMEI), 例如: -c 869523059113051
  179. `
  180. fmt.Println(h)
  181. }
  182. func interruptLoop(executing *atomic.Bool, interrupted *atomic.Bool) {
  183. sigCh := make(chan os.Signal, 1)
  184. signal.Notify(sigCh, syscall.SIGINT)
  185. go func() {
  186. for range sigCh {
  187. interrupted.Store(true)
  188. if executing.Load() {
  189. _, _ = coupler.stop()
  190. }
  191. }
  192. }()
  193. }
  194. func heartbeatLoop(pingState *atomic.Bool) {
  195. go func() {
  196. ticker := time.NewTicker(1 * time.Second)
  197. defer ticker.Stop()
  198. pingFailCount := 0
  199. pong := ""
  200. for range ticker.C {
  201. resp, err := coupler.ping()
  202. if err == nil && resp.Error == nil && resp.Result != nil &&
  203. json.Unmarshal(resp.Result, &pong) == nil && pong == "pong" {
  204. pingState.Store(true)
  205. pingFailCount = 0
  206. } else {
  207. pingFailCount++
  208. if pingFailCount >= 3 { ///// 连续3次ping失败, 可以认为设备离线
  209. pingState.Store(false)
  210. }
  211. } // end if
  212. } // end for
  213. }()
  214. }
  215. func printWelcome(pingState *atomic.Bool) {
  216. welcome := `
  217. _ _ _ _ _ _ _ _
  218. | \ | (_) | | | (_) | |
  219. | \| |_| |_ ___| |__ _| | | ___
  220. | . | | __/ __| '_ \| | | |/ _ \
  221. | |\ | | || (__| | | | | | | __/
  222. |_| \_|_|\__\___|_| |_|_|_|_|\___|
  223. ══════════════════════════════════
  224. 云飞科技RTU远程运维终端
  225. 提示: 输入'quit'命令, 退出终端
  226. ══════════════════════════════════
  227. `
  228. fmt.Println(welcome)
  229. fmt.Printf("客户端ID: %s\n", coupler.clientID)
  230. state := ""
  231. if pingState.Load() {
  232. state = "已连接 ✅"
  233. } else {
  234. state = "未连接 ❌"
  235. }
  236. fmt.Printf("设备状态: %s\n\n", state)
  237. }
  238. func clearScreen() {
  239. if runtime.GOOS == "windows" {
  240. cmd := exec.Command("cmd", "/c", "cls")
  241. cmd.Stdout = os.Stdout
  242. _ = cmd.Run()
  243. } else {
  244. cmd := exec.Command("clear")
  245. cmd.Stdout = os.Stdout
  246. _ = cmd.Run()
  247. }
  248. }