client.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. interrupted: make(chan struct{}, 1),
  62. }
  63. id, err := machineid.ID()
  64. if err == nil {
  65. coupler.machineID = id
  66. }
  67. if err := coupler.init2(); err != nil {
  68. fmt.Printf("[%s] 错误: %v\n!!", MODULE_NAME, err)
  69. return
  70. }
  71. var pingState atomic.Bool
  72. heartbeatLoop(&pingState) // -启动-设备在线-心跳检测-
  73. for {
  74. if pingState.Load() { //// 等待成功连接上目标设备卍
  75. break
  76. }
  77. fmt.Printf("[%s] 正在尝试连接设备...\n", MODULE_NAME)
  78. time.Sleep(1 * time.Second)
  79. }
  80. term(&pingState) /////////////////// 启动终端模拟器卍
  81. }
  82. func term(pingState *atomic.Bool) {
  83. var executing atomic.Bool // 是否有正在执行中的命令
  84. var interrupted atomic.Bool // 用户是否按键取消了命令
  85. interruptLoop(pingState, &executing, &interrupted) // Ctrl+C卍
  86. printWelcome(pingState)
  87. line := liner.NewLiner()
  88. defer line.Close()
  89. line.SetCtrlCAborts(false)
  90. line.SetTabCompletionStyle(liner.TabCircular)
  91. historyFile := "history.txt"
  92. var history []string
  93. if f, err := os.Open(historyFile); err == nil {
  94. scanner := bufio.NewScanner(f)
  95. for scanner.Scan() {
  96. cmd := strings.TrimSpace(scanner.Text())
  97. if cmd != "" {
  98. history = append(history, cmd)
  99. line.AppendHistory(cmd)
  100. }
  101. }
  102. f.Close()
  103. }
  104. defer func() {
  105. if f, err := os.Create(historyFile); err == nil {
  106. line.WriteHistory(f)
  107. f.Close()
  108. }
  109. }()
  110. line.SetCompleter(func(input string) []string { // 补全
  111. var matches []string
  112. for _, cmd := range history {
  113. if strings.HasPrefix(cmd, input) {
  114. matches = append(matches, cmd)
  115. }
  116. }
  117. return matches
  118. })
  119. executing.Store(true)
  120. result, err := coupler.exec("pwd")
  121. executing.Store(false)
  122. if err == nil && result.Cwd != "" { /// 在进入前对齐路径
  123. coupler.cwd = result.Cwd
  124. }
  125. for {
  126. if !pingState.Load() {
  127. fmt.Printf("[%s] 目标设备连接丢失!!\n", MODULE_NAME)
  128. break
  129. }
  130. if interrupted.Swap(false) {
  131. fmt.Println("^C")
  132. }
  133. prompt := fmt.Sprintf("root@%s:%s# ", coupler.imei, coupler.cwd)
  134. input, err := line.Prompt(prompt) /// 等待用户输入指令
  135. if err == nil {
  136. goto inputOK
  137. }
  138. if err == io.EOF { ////////////////// Ctrl+D 按键处理
  139. _, _ = coupler.quit()
  140. fmt.Println("bye")
  141. break
  142. }
  143. fmt.Println(err)
  144. continue
  145. inputOK:
  146. input = strings.TrimSpace(input)
  147. if input == "" {
  148. continue
  149. }
  150. line.AppendHistory(input) ///// 保存用户输入的历史命令
  151. history = append(history, input) ///// 本次也立刻生效
  152. if input == "exit" || input == "quit" {
  153. _, _ = coupler.quit()
  154. fmt.Println("bye")
  155. break
  156. }
  157. if input == "clear" {
  158. clearScreen()
  159. continue
  160. }
  161. executing.Store(true)
  162. result, err := coupler.exec(input)
  163. executing.Store(false)
  164. if err != nil {
  165. fmt.Printf("%v\n", err)
  166. continue
  167. }
  168. if result.Stdout != "" {
  169. fmt.Print(result.Stdout)
  170. }
  171. if result.Stderr != "" {
  172. fmt.Fprintln(os.Stderr, result.Stderr)
  173. }
  174. if result.ExitCode == 124 {
  175. fmt.Println("command timeout")
  176. }
  177. if result.Cwd != "" {
  178. coupler.cwd = result.Cwd
  179. }
  180. }
  181. }
  182. func help() {
  183. h := `
  184. -h 显示帮助提示
  185. -v 当前程序版本
  186. -c 连接目标设备(IMEI), 例如: -c 869523059113051
  187. `
  188. fmt.Println(h)
  189. }
  190. func interruptLoop(pingState, executing, interrupted *atomic.Bool) {
  191. sigCh := make(chan os.Signal, 1)
  192. signal.Notify(sigCh, syscall.SIGINT)
  193. go func() {
  194. for range sigCh {
  195. interrupted.Store(true)
  196. if executing.Load() {
  197. select {
  198. case coupler.interrupted <- struct{}{}:
  199. default:
  200. }
  201. if pingState.Load() {
  202. go func() {
  203. _, _ = coupler.stop()
  204. }()
  205. } // end if2
  206. } //// end if1
  207. } ////// end for
  208. }()
  209. }
  210. func heartbeatLoop(pingState *atomic.Bool) {
  211. go func() {
  212. ticker := time.NewTicker(1 * time.Second)
  213. defer ticker.Stop()
  214. pingFailCount := 0
  215. pong := ""
  216. for range ticker.C {
  217. resp, err := coupler.ping()
  218. if err == nil && resp.Error == nil && resp.Result != nil &&
  219. json.Unmarshal(resp.Result, &pong) == nil && pong == "pong" {
  220. pingState.Store(true)
  221. pingFailCount = 0
  222. } else {
  223. pingFailCount++
  224. if pingFailCount >= 3 { ///// 连续3次ping失败, 可以认为设备离线
  225. pingState.Store(false)
  226. }
  227. } // end if
  228. } // end for
  229. }()
  230. }
  231. func printWelcome(pingState *atomic.Bool) {
  232. welcome := `
  233. ____ _ _ _____ _ _ _ _ _
  234. | _ \ | | | | / ____| | | | | || \ | |
  235. | |_) || |_| | ___ | | | | ___| | | || \| |
  236. | _ < | _ |/ _ \| | | |/ _ \ | | || . _ |
  237. | |_) || | | | __/| |____| | __/ |_| || |\ |
  238. |____/ |_| |_|\___| \_____|_|\___|\___/ |_| \_|
  239. ================================================
  240. 欢迎使用云飞科技RTU设备远程运维终端
  241. 提示: 输入"quit"命令或按下"Ctrl+D"键, 可退出终端
  242. ================================================
  243. `
  244. fmt.Println(welcome)
  245. fmt.Printf("客户端ID: %s\n", coupler.machineID)
  246. state := ""
  247. if pingState.Load() {
  248. state = "√ 已连接"
  249. } else {
  250. state = "x 未连接"
  251. }
  252. fmt.Printf("设备状态: %s\n\n", state)
  253. }
  254. func clearScreen() {
  255. if runtime.GOOS == "windows" {
  256. cmd := exec.Command("cmd", "/c", "cls")
  257. cmd.Stdout = os.Stdout
  258. _ = cmd.Run()
  259. } else {
  260. cmd := exec.Command("clear")
  261. cmd.Stdout = os.Stdout
  262. _ = cmd.Run()
  263. }
  264. }