client.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. break
  155. }
  156. if input == "clear" {
  157. clearScreen()
  158. continue
  159. }
  160. executing.Store(true)
  161. result, err := coupler.exec(input)
  162. executing.Store(false)
  163. if err != nil {
  164. fmt.Printf("执行错误: %v\n", err)
  165. continue
  166. }
  167. if result.Stdout != "" {
  168. fmt.Print(result.Stdout)
  169. }
  170. if result.Stderr != "" {
  171. fmt.Fprintln(os.Stderr, result.Stderr)
  172. }
  173. if result.ExitCode == 124 {
  174. fmt.Println("command timeout")
  175. }
  176. if result.Cwd != "" {
  177. coupler.cwd = result.Cwd
  178. }
  179. }
  180. }
  181. func help() {
  182. h := `
  183. -h 显示帮助提示
  184. -v 当前程序版本
  185. -c 连接目标设备(IMEI), 例如: -c 869523059113051
  186. `
  187. fmt.Println(h)
  188. }
  189. func interruptLoop(pingState, executing, interrupted *atomic.Bool) {
  190. sigCh := make(chan os.Signal, 1)
  191. signal.Notify(sigCh, syscall.SIGINT)
  192. go func() {
  193. for range sigCh {
  194. interrupted.Store(true)
  195. if executing.Load() && pingState.Load() {
  196. select {
  197. case coupler.interrupted <- struct{}{}:
  198. default:
  199. }
  200. _, _ = coupler.stop()
  201. }
  202. }
  203. }()
  204. }
  205. func heartbeatLoop(pingState *atomic.Bool) {
  206. go func() {
  207. ticker := time.NewTicker(1 * time.Second)
  208. defer ticker.Stop()
  209. pingFailCount := 0
  210. pong := ""
  211. for range ticker.C {
  212. resp, err := coupler.ping()
  213. if err == nil && resp.Error == nil && resp.Result != nil &&
  214. json.Unmarshal(resp.Result, &pong) == nil && pong == "pong" {
  215. pingState.Store(true)
  216. pingFailCount = 0
  217. } else {
  218. pingFailCount++
  219. if pingFailCount >= 3 { ///// 连续3次ping失败, 可以认为设备离线
  220. pingState.Store(false)
  221. }
  222. } // end if
  223. } // end for
  224. }()
  225. }
  226. func printWelcome(pingState *atomic.Bool) {
  227. welcome := `
  228. _ _ _ _ _ _ _ _
  229. | \ | (_) | | | (_) | |
  230. | \| |_| |_ ___| |__ _| | | ___
  231. | . | | __/ __| '_ \| | | |/ _ \
  232. | |\ | | || (__| | | | | | | __/
  233. |_| \_|_|\__\___|_| |_|_|_|_|\___|
  234. ══════════════════════════════════
  235. 云飞科技RTU远程运维终端
  236. 提示: 输入'quit'命令, 退出终端
  237. ══════════════════════════════════
  238. `
  239. fmt.Println(welcome)
  240. fmt.Printf("客户端ID: %s\n", coupler.machineID)
  241. state := ""
  242. if pingState.Load() {
  243. state = "已连接 ✅"
  244. } else {
  245. state = "未连接 ❌"
  246. }
  247. fmt.Printf("设备状态: %s\n\n", state)
  248. }
  249. func clearScreen() {
  250. if runtime.GOOS == "windows" {
  251. cmd := exec.Command("cmd", "/c", "cls")
  252. cmd.Stdout = os.Stdout
  253. _ = cmd.Run()
  254. } else {
  255. cmd := exec.Command("clear")
  256. cmd.Stdout = os.Stdout
  257. _ = cmd.Run()
  258. }
  259. }