Repository navigation
Expand file tree
/
Copy pathssh.go
More file actions
1635 lines (1483 loc) · 44.4 KB
/
Copy pathssh.go
File metadata and controls
1635 lines (1483 loc) · 44.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/pkg/sftp"
"github.com/wailsapp/wails/v2/pkg/runtime"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
)
type SessionData struct {
Client *ssh.Client
Session *ssh.Session
SFTP *sftp.Client
Stdin io.WriteCloser
HistoryStream *commandHistoryStream
RemoteHistoryActive bool
keepaliveStop chan struct{} // 关闭后通知 keepalive 协程退出
}
type SSHManager struct {
ctx context.Context
app *App // reference to App for WebSocket output delivery
sessions map[string]*SessionData
probeDeployed map[string]bool // tracks which sessions have probe.sh deployed
portForwards map[string][]*forwardEntry // sessionId -> active forwards
mu sync.Mutex
}
func NewSSHManager() *SSHManager {
return &SSHManager{
sessions: make(map[string]*SessionData),
probeDeployed: make(map[string]bool),
}
}
// removeHostKey removes all known_hosts entries for a given hostname
func removeHostKey(path string, hostname string) {
data, err := os.ReadFile(path)
if err != nil {
return
}
lines := strings.Split(string(data), "\n")
var out []string
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
out = append(out, line)
continue
}
fields := strings.Fields(line)
if len(fields) >= 2 {
names := strings.Split(fields[0], ",")
match := false
for _, name := range names {
if name == hostname {
match = true
break
}
}
if match {
continue
}
}
out = append(out, line)
}
os.WriteFile(path, []byte(strings.Join(out, "\n")+"\n"), 0600)
}
// buildAuthMethods 根据连接配置构造 SSH 认证方式(Connect 与一次性 exec 共用)
func buildAuthMethods(conn Connection) ([]ssh.AuthMethod, error) {
var authMethods []ssh.AuthMethod
if conn.AuthMethod == "password" {
authMethods = append(authMethods, ssh.Password(conn.Password))
authMethods = append(authMethods, ssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
answers = make([]string, len(questions))
for i := range answers {
answers[i] = conn.Password
}
return answers, nil
}))
} else if conn.AuthMethod == "privateKey" {
var signer ssh.Signer
var err error
if conn.Passphrase != "" {
signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(conn.PrivateKey), []byte(conn.Passphrase))
} else {
signer, err = ssh.ParsePrivateKey([]byte(conn.PrivateKey))
}
if err != nil {
return nil, fmt.Errorf("invalid private key: %v", err)
}
authMethods = append(authMethods, ssh.PublicKeys(signer))
}
return authMethods, nil
}
// buildHostKeyCallback 构造 host key 校验回调:已知密钥校验、未知主机自动记录、
// 变更密钥移除旧记录并提示(ssh-hostkey-changed 事件)
func (m *SSHManager) buildHostKeyCallback() ssh.HostKeyCallback {
knownHostsPath := filepath.Join(os.Getenv("USERPROFILE"), ".ssh", "known_hosts")
os.MkdirAll(filepath.Dir(knownHostsPath), 0700)
if _, err := os.Stat(knownHostsPath); os.IsNotExist(err) {
os.WriteFile(knownHostsPath, []byte(""), 0600)
}
hostKeyCallback, err := knownhosts.New(knownHostsPath)
if err != nil {
hostKeyCallback = ssh.InsecureIgnoreHostKey()
}
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
err := hostKeyCallback(hostname, remote, key)
if err == nil {
return nil
}
var keyErr *knownhosts.KeyError
if errors.As(err, &keyErr) {
if len(keyErr.Want) == 0 {
// 未知主机 → 自动信任
f, fErr := os.OpenFile(knownHostsPath, os.O_APPEND|os.O_WRONLY, 0600)
if fErr == nil {
defer f.Close()
line := knownhosts.Line([]string{hostname}, key)
f.WriteString(line + "\n")
}
return nil
} else {
// 主机密钥已变更(如重装系统)→ 移除旧记录并自动信任新密钥
removeHostKey(knownHostsPath, hostname)
f, fErr := os.OpenFile(knownHostsPath, os.O_APPEND|os.O_WRONLY, 0600)
if fErr == nil {
defer f.Close()
line := knownhosts.Line([]string{hostname}, key)
f.WriteString(line + "\n")
}
if m.ctx != nil {
runtime.EventsEmit(m.ctx, "ssh-hostkey-changed", hostname)
}
return nil
}
}
return err
}
}
func (m *SSHManager) Connect(sessionId string, conn Connection) error {
// 注意:整个拨号流程(SSH 握手 10s 超时 + SFTP + shell 探测)不持有 m.mu。
// 若在锁内执行,新连接建立期间所有已有会话的输入/输出/文件操作都会被冻结。
// m.mu 只保护 sessions/portForwards 等 map 的读写。
// Setup auth methods
authMethods, err := buildAuthMethods(conn)
if err != nil {
return err
}
hostKeyCb := m.buildHostKeyCallback()
config := &ssh.ClientConfig{
User: conn.Username,
Auth: authMethods,
HostKeyCallback: hostKeyCb,
Timeout: 10 * time.Second,
HostKeyAlgorithms: []string{
"ssh-ed25519",
"ecdsa-sha2-nistp256",
"ecdsa-sha2-nistp384",
"ecdsa-sha2-nistp521",
"rsa-sha2-512",
"rsa-sha2-256",
"ssh-rsa",
"ssh-dss",
},
}
target := fmt.Sprintf("%s:%d", strings.TrimSpace(conn.Host), conn.Port)
client, err := ssh.Dial("tcp", target, config)
if err != nil {
return err
}
// Create SFTP client
sftpClient, err := sftp.NewClient(client)
if err != nil {
client.Close()
return fmt.Errorf("failed to start SFTP: %v", err)
}
// Create SSH Session for PTY
session, err := client.NewSession()
if err != nil {
sftpClient.Close()
client.Close()
return err
}
modes := ssh.TerminalModes{
ssh.TTY_OP_ISPEED: 115200,
ssh.TTY_OP_OSPEED: 115200,
}
if err := session.RequestPty("xterm-256color", 24, 80, modes); err != nil {
session.Close()
sftpClient.Close()
client.Close()
return err
}
stdin, err := session.StdinPipe()
if err != nil {
session.Close()
sftpClient.Close()
client.Close()
return err
}
stdout, err := session.StdoutPipe()
if err != nil {
session.Close()
sftpClient.Close()
client.Close()
return err
}
stderr, err := session.StderrPipe()
if err != nil {
session.Close()
sftpClient.Close()
client.Close()
return err
}
shellPath := detectRemoteShell(client)
launchCmd, remoteHistoryActive := buildShellLaunchCommand(shellPath)
// Start shell
if remoteHistoryActive {
err = session.Start(launchCmd)
} else {
err = session.Shell()
}
if err != nil {
session.Close()
sftpClient.Close()
client.Close()
return err
}
var historyStream *commandHistoryStream
if remoteHistoryActive {
historyStream = newCommandHistoryStream()
}
// 同一 sessionId 重复连接时拒绝并释放新资源,避免覆盖导致旧连接泄漏
keepaliveStop := make(chan struct{})
m.mu.Lock()
if _, exists := m.sessions[sessionId]; exists {
m.mu.Unlock()
session.Close()
sftpClient.Close()
client.Close()
return fmt.Errorf("session already connected")
}
m.sessions[sessionId] = &SessionData{
Client: client,
Session: session,
SFTP: sftpClient,
Stdin: stdin,
HistoryStream: historyStream,
RemoteHistoryActive: remoteHistoryActive,
keepaliveStop: keepaliveStop,
}
m.mu.Unlock()
// 启动 keepalive 探测:检测 NAT 掉线/拔线等半开连接(无 keepalive 时
// client.Wait() 会永久阻塞,UI 永远收不到断开事件)
go m.keepaliveLoop(client, keepaliveStop)
// 启动读取 stdout/stderr
go m.pipeOutput(sessionId, stdout, historyStream)
go m.pipeOutput(sessionId, stderr, nil)
// 启动后台连接意外断开监控协程:
// 关键:当用户在终端内执行 exit / logout,或者远端进程终止时,session.Wait() 会立即返回!
// 如果只等待 client.Wait(),由于 SFTP 或其他通道(如端口转发、并发连接通道)依然可能未被关闭,
// client 内部的 TCP 连接不会立刻关闭,导致前端必须等待数十秒甚至更久才能感知断开。
go func() {
sessionDone := make(chan struct{})
go func() {
_ = session.Wait()
close(sessionDone)
}()
clientDone := make(chan struct{})
go func() {
_ = client.Wait()
close(clientDone)
}()
select {
case <-sessionDone:
case <-clientDone:
}
// 检测是否已被主动移除,若未被移除,说明是远端退出或意外断开
m.mu.Lock()
_, exists := m.sessions[sessionId]
m.mu.Unlock()
if exists {
m.CloseSessionResources(sessionId)
if m.ctx != nil {
runtime.EventsEmit(m.ctx, "ssh-disconnected", sessionId)
}
}
}()
return nil
}
// keepaliveLoop 周期性发送 SSH keepalive 全局请求,探测半开连接(NAT 掉线、
// 拔线等)。服务器会回 REQUEST_FAILURE(accepted=false 但 err=nil),即连接存活;
// 传输层故障或 15s 内无回包则视为死链,主动关闭 client,使 client.Wait() 返回
// 并走常规的意外断开清理流程(触发 ssh-disconnected 事件)。
func (m *SSHManager) keepaliveLoop(client *ssh.Client, stop chan struct{}) {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
reply := make(chan error, 1)
go func() {
_, _, err := client.SendRequest("keepalive@openssh.com", true, nil)
reply <- err
}()
select {
case err := <-reply:
if err != nil {
client.Close()
return
}
case <-time.After(15 * time.Second):
client.Close()
return
}
case <-stop:
return
}
}
}
func (m *SSHManager) pipeOutput(sessionId string, r io.Reader, historyStream *commandHistoryStream) {
buf := make([]byte, 32768)
// 直接读取并通过 WebSocket 发送,不再批处理缓冲
// WebSocket 过 TCP loopback 延迟极低,无需批处理
for {
n, err := r.Read(buf)
if n > 0 {
data := make([]byte, n)
copy(data, buf[:n])
if historyStream != nil {
visible, commands := historyStream.Process(data)
data = visible
for _, command := range commands {
if command == "" || m.ctx == nil {
continue
}
runtime.EventsEmit(m.ctx, "ssh-command-executed", map[string]string{
"sessionId": sessionId,
"command": command,
"time": time.Now().Format(time.RFC3339),
"source": "remote",
})
}
}
if len(data) == 0 {
if err != nil {
return
}
continue
}
if m.app != nil {
m.app.WriteWsOutput(sessionId, data)
} else if m.ctx != nil {
// fallback: WebSocket 未初始化时用 Events
runtime.EventsEmit(m.ctx, "terminal-data-"+sessionId, string(data))
}
}
if err != nil {
return
}
}
}
// stopPortForwardsLocked 停止并移除会话的所有端口转发(调用方必须持有 m.mu)。
// 会话死亡后若不清理,本地监听器会继续接受 TCP 连接并在 Dial 时静默失败。
func (m *SSHManager) stopPortForwardsLocked(sessionId string) {
for _, e := range m.portForwards[sessionId] {
close(e.cancel)
e.listener.Close()
}
delete(m.portForwards, sessionId)
}
// teardownSessionLocked 关闭会话资源并从注册表移除(调用方必须持有 m.mu)。
// 必须删除 map 条目:意外断开后若残留条目,僵尸会话会永远占位且后续
// 操作(ListDir/WriteBytes 等)作用在死连接上。
func (m *SSHManager) teardownSessionLocked(sessionId string, s *SessionData) {
if m.ctx != nil {
runtime.EventsOff(m.ctx, "terminal-input-"+sessionId)
}
m.stopPortForwardsLocked(sessionId)
if s.Stdin != nil {
s.Stdin.Close()
}
if s.Session != nil {
s.Session.Close()
}
if s.SFTP != nil {
s.SFTP.Close()
}
if s.Client != nil {
s.Client.Close()
}
if s.keepaliveStop != nil {
close(s.keepaliveStop)
}
delete(m.sessions, sessionId)
}
func (m *SSHManager) Disconnect(sessionId string) {
m.mu.Lock()
defer m.mu.Unlock()
if s, ok := m.sessions[sessionId]; ok {
m.teardownSessionLocked(sessionId, s)
}
}
func (m *SSHManager) CloseSessionResources(sessionId string) {
m.mu.Lock()
defer m.mu.Unlock()
if s, ok := m.sessions[sessionId]; ok {
m.teardownSessionLocked(sessionId, s)
}
}
func (m *SSHManager) GetTerminalCwd(sessionId string) (string, error) {
m.mu.Lock()
s, ok := m.sessions[sessionId]
m.mu.Unlock()
if !ok {
return "", fmt.Errorf("session not found")
}
if s.Client == nil {
return "", fmt.Errorf("client connection is nil")
}
localAddr := s.Client.LocalAddr().String()
parts := strings.Split(localAddr, ":")
if len(parts) < 2 {
return "", fmt.Errorf("invalid local address format")
}
port := parts[len(parts)-1]
cmd := fmt.Sprintf(`PORT=%s
# 查找该端口对应的 sshd 进程 PID
SSHD_PID=""
for tool in "ss -ntp" "netstat -ntp" "lsof -ti :$PORT" "fuser $PORT/tcp 2>/dev/null"; do
case "$tool" in
ss*) SSHD_PID=$(ss -ntp 2>/dev/null | grep ":$PORT " | grep -oE 'pid=[0-9]+' | cut -d= -f2 | head -n1) ;;
netstat*) SSHD_PID=$(netstat -ntp 2>/dev/null | grep ":$PORT " | grep -oE '[0-9]+/sshd' | cut -d/ -f1 | head -n1) ;;
lsof*) SSHD_PID=$(lsof -ti :$PORT 2>/dev/null | head -n1) ;;
fuser*) SSHD_PID=$(fuser $PORT/tcp 2>/dev/null | tr -d ' ') ;;
esac
[ -n "$SSHD_PID" ] && break
done
CWD="/"
if [ -n "$SSHD_PID" ]; then
# 尝试找到 sshd 下第一个 shell 子进程
SHELL_PID=$(pgrep -P "$SSHD_PID" 2>/dev/null | head -n1)
if [ -n "$SHELL_PID" ]; then
CWD=$(readlink /proc/$SHELL_PID/cwd 2>/dev/null)
fi
# 回退:直接用 sshd 的 cwd(通常为 HOME)
[ -z "$CWD" ] && CWD=$(readlink /proc/$SSHD_PID/cwd 2>/dev/null)
fi
# 最后回退:尝试从 /etc/passwd 找 HOME
[ -z "$CWD" ] && CWD=$(getent passwd $USER 2>/dev/null | cut -d: -f6)
echo "${CWD:-/}"`, port)
out, err := m.executeCmd(s, cmd)
if err != nil {
return "", err
}
cwd := strings.TrimSpace(out)
if cwd == "" {
cwd = "/"
}
return cwd, nil
}
// WriteBytes sends raw bytes to the SSH PTY stdin (used by WebSocket handler)
func (m *SSHManager) WriteBytes(sessionId string, data []byte) {
m.mu.Lock()
s, ok := m.sessions[sessionId]
m.mu.Unlock()
if ok && s.Stdin != nil {
_, _ = s.Stdin.Write(data)
}
}
func (m *SSHManager) Resize(sessionId string, cols, rows int) {
m.mu.Lock()
s, ok := m.sessions[sessionId]
m.mu.Unlock()
if ok {
s.Session.WindowChange(rows, cols)
}
}
// executeCmd executes a command on a separate temporary session to avoid blocking the main PTY
func (m *SSHManager) executeCmd(s *SessionData, cmd string) (string, error) {
if s.Client == nil {
return "", fmt.Errorf("ssh client is nil")
}
session, err := s.Client.NewSession()
if err != nil {
return "", err
}
defer session.Close()
var stdoutBuf bytes.Buffer
session.Stdout = &stdoutBuf
done := make(chan error, 1)
go func() {
done <- session.Run(cmd)
}()
select {
case err = <-done:
return stdoutBuf.String(), err
case <-time.After(5 * time.Second):
session.Close()
return "", fmt.Errorf("command execution timed out")
}
}
// execOnce 建立一次性 SSH 连接执行单条命令并返回输出(不创建持久会话),
// 用于脚本页对尚未连接的服务器发送指令
func (m *SSHManager) execOnce(conn Connection, cmd string) (string, error) {
authMethods, err := buildAuthMethods(conn)
if err != nil {
return "", err
}
config := &ssh.ClientConfig{
User: conn.Username,
Auth: authMethods,
HostKeyCallback: m.buildHostKeyCallback(),
Timeout: 10 * time.Second,
}
target := fmt.Sprintf("%s:%d", strings.TrimSpace(conn.Host), conn.Port)
client, err := ssh.Dial("tcp", target, config)
if err != nil {
return "", err
}
defer client.Close()
session, err := client.NewSession()
if err != nil {
return "", err
}
defer session.Close()
var stdoutBuf, stderrBuf bytes.Buffer
session.Stdout = &stdoutBuf
session.Stderr = &stderrBuf
err = session.Run(cmd)
out := stdoutBuf.String()
if err != nil {
return out, fmt.Errorf("%v: %s", err, strings.TrimSpace(stderrBuf.String()))
}
return out, nil
}
func parseStatCpus(lines []string) map[string][]uint64 {
res := make(map[string][]uint64)
for _, l := range lines {
if !strings.HasPrefix(l, "cpu") {
continue
}
parts := strings.Fields(l)
if len(parts) < 5 {
continue
}
vals := make([]uint64, len(parts)-1)
for i := 1; i < len(parts); i++ {
v, _ := strconv.ParseUint(parts[i], 10, 64)
vals[i-1] = v
}
res[parts[0]] = vals
}
return res
}
func parseNetDev(lines []string) map[string][]uint64 {
res := make(map[string][]uint64)
for _, l := range lines {
if !strings.Contains(l, ":") {
continue
}
parts := strings.Split(l, ":")
name := strings.TrimSpace(parts[0])
if name == "lo" {
continue
}
fields := strings.Fields(parts[1])
if len(fields) < 9 {
continue
}
rx, _ := strconv.ParseUint(fields[0], 10, 64)
tx, _ := strconv.ParseUint(fields[8], 10, 64)
res[name] = []uint64{rx, tx}
}
return res
}
func parseDiskStats(lines []string) map[string][]uint64 {
res := make(map[string][]uint64)
for _, l := range lines {
fields := strings.Fields(l)
if len(fields) < 10 {
continue
}
name := fields[2]
if strings.HasPrefix(name, "loop") || strings.HasPrefix(name, "ram") {
continue
}
readSectors, _ := strconv.ParseUint(fields[5], 10, 64)
writeSectors, _ := strconv.ParseUint(fields[9], 10, 64)
res[name] = []uint64{readSectors, writeSectors}
}
return res
}
const probeScript = `#!/bin/sh
# AetherSSH Probe Script - auto generated, do not edit
# Collects metrics via /proc - no external dependencies required
cat /proc/uptime
echo ---MEM---
grep -E '^MemTotal:|^MemFree:|^Buffers:|^Cached:|^SReclaimable:|^SwapTotal:|^SwapFree:' /proc/meminfo
echo ---DF---
df -k | grep -vE '^tmpfs|^udev|^devtmpfs|Filesystem'
echo ---OS---
grep PRETTY_NAME /etc/os-release 2>/dev/null || echo 'PRETTY_NAME="Linux"'
grep ^VERSION_ID= /etc/os-release 2>/dev/null
echo ---TZ---
cat /etc/timezone 2>/dev/null || date +'%Z'
echo ---HOSTNAME---
hostname
echo ---IP---
ip route get 1.1.1.1 2>/dev/null | grep -oE 'src [0-9.]+' | awk '{print $2}' || hostname -I 2>/dev/null | awk '{print $1}'
echo ---CPU1---
grep '^cpu' /proc/stat
echo ---NET1---
cat /proc/net/dev
echo ---DISKIO1---
cat /proc/diskstats
sleep 1
echo ---CPU2---
grep '^cpu' /proc/stat
echo ---NET2---
cat /proc/net/dev
echo ---DISKIO2---
cat /proc/diskstats
echo ---PROC---
ps -eo pid,pcpu,rss,comm --sort=-pcpu 2>/dev/null | head -21
echo ---DONE---
`
// deployProbeScript writes probe.sh to ~/.aether/ on the remote server via SFTP.
// It is idempotent: if already deployed for this session it returns immediately.
func (m *SSHManager) deployProbeScript(s *SessionData, sessionId string) error {
m.mu.Lock()
already := m.probeDeployed[sessionId]
m.mu.Unlock()
if already {
return nil
}
// Ensure ~/.aether directory exists
// 目录权限 0700:防止同机其他用户读取/篡改探针脚本(脚本仅当前用户需要执行)
if err := s.SFTP.MkdirAll(".aether"); err != nil {
// Non-fatal: fall back to /tmp/.aether
_ = s.SFTP.MkdirAll("/tmp/.aether")
_ = s.SFTP.Chmod("/tmp/.aether", 0700)
} else {
_ = s.SFTP.Chmod(".aether", 0700)
}
// Write the script file
scriptPath := ".aether/probe.sh"
f, err := s.SFTP.Create(scriptPath)
if err != nil {
scriptPath = "/tmp/.aether/probe.sh"
f, err = s.SFTP.Create(scriptPath)
if err != nil {
return fmt.Errorf("cannot write probe script: %v", err)
}
}
_, err = f.Write([]byte(probeScript))
f.Close()
if err != nil {
return err
}
// 脚本权限 0700:仅属主可读可执行,防止同机其他用户篡改探针内容
_ = s.SFTP.Chmod(scriptPath, 0700)
m.mu.Lock()
m.probeDeployed[sessionId] = true
m.mu.Unlock()
return nil
}
func (m *SSHManager) GetSystemInfo(sessionId string) (map[string]interface{}, error) {
m.mu.Lock()
s, ok := m.sessions[sessionId]
m.mu.Unlock()
if !ok {
return nil, fmt.Errorf("session not found")
}
// Deploy probe script to ~/.aether/probe.sh (once per session, idempotent)
_ = m.deployProbeScript(s, sessionId)
// Execute the deployed script
out, err := m.executeCmd(s, `sh -c 'f=~/.aether/probe.sh; [ -f "$f" ] && sh "$f" || sh /tmp/.aether/probe.sh'`)
if err != nil || len(strings.TrimSpace(out)) == 0 {
return nil, fmt.Errorf("probe script execution failed")
}
// ── Split on ---CPU2--- to get two halves ──────────────────────────
halves := strings.SplitN(out, "---CPU2---", 2)
if len(halves) < 2 {
return nil, fmt.Errorf("unexpected output format")
}
part1 := halves[0]
part2 := halves[1] // everything after ---CPU2---
lines1 := strings.Split(part1, "\n")
lines2 := strings.Split(part2, "\n")
// ── Helper: extract a named section from a line slice ─────────────
extractSection := func(lines []string, startMarker, endMarker string) []string {
var out []string
// BUG FIX: if startMarker is empty, strings.Contains(l,"") is always true
// causing every line to be skipped via `continue`. Fix: start collecting immediately.
inside := (startMarker == "")
for _, l := range lines {
if startMarker != "" && strings.Contains(l, startMarker) {
inside = true
continue
}
if endMarker != "" && strings.Contains(l, endMarker) {
break
}
if inside {
out = append(out, l)
}
}
return out
}
// ── Parse uptime ──────────────────────────────────────────────────
uptimeStr := "0 小时"
if len(lines1) > 0 {
var uptimeVal float64
fmt.Sscanf(strings.TrimSpace(lines1[0]), "%f", &uptimeVal)
days := int(uptimeVal / 86400)
hours := int((uptimeVal - float64(days*86400)) / 3600)
mins := int((uptimeVal - float64(days*86400) - float64(hours*3600)) / 60)
if days > 0 {
uptimeStr = fmt.Sprintf("%d 天 %d 小时", days, hours)
} else if hours > 0 {
uptimeStr = fmt.Sprintf("%d 小时 %d 分", hours, mins)
} else {
uptimeStr = fmt.Sprintf("%d 分钟", mins)
}
}
// ── Parse memory ──────────────────────────────────────────────────
var memTotal, memFree, memBuffers, memCached, memSReclaimable uint64
for _, l := range lines1 {
switch {
case strings.HasPrefix(l, "MemTotal:"):
fmt.Sscanf(l, "MemTotal: %d", &memTotal)
case strings.HasPrefix(l, "MemFree:"):
fmt.Sscanf(l, "MemFree: %d", &memFree)
case strings.HasPrefix(l, "Buffers:"):
fmt.Sscanf(l, "Buffers: %d", &memBuffers)
case strings.HasPrefix(l, "Cached:"):
fmt.Sscanf(l, "Cached: %d", &memCached)
case strings.HasPrefix(l, "SReclaimable:"):
fmt.Sscanf(l, "SReclaimable: %d", &memSReclaimable)
}
}
memTotalMB := float64(memTotal) / 1024.0
memFreeMB := float64(memFree) / 1024.0
memCacheMB := float64(memBuffers+memCached+memSReclaimable) / 1024.0
memUsedMB := memTotalMB - memFreeMB - memCacheMB
if memUsedMB < 0 {
memUsedMB = 0
}
// ── Parse df (all partitions) ─────────────────────────────────────
dfLines := extractSection(lines1, "---DF---", "---OS---")
var diskTotalKB, diskUsedKB uint64
var diskPercent float64
diskDevice := "disk"
type partition struct {
Mount string
Size string
Avail string
UsedPct int
}
var partitions []partition
for _, l := range dfLines {
fields := strings.Fields(l)
if len(fields) < 6 {
continue
}
totalKB, _ := strconv.ParseUint(fields[1], 10, 64)
usedKB, _ := strconv.ParseUint(fields[2], 10, 64)
availKB, _ := strconv.ParseUint(fields[3], 10, 64)
pctStr := strings.TrimSuffix(fields[4], "%")
pct, _ := strconv.Atoi(pctStr)
mount := fields[5]
if mount == "/" {
diskDevice = filepath.Base(fields[0])
diskTotalKB = totalKB
diskUsedKB = usedKB
if totalKB > 0 {
diskPercent = float64(usedKB) / float64(totalKB) * 100.0
}
}
formatGB := func(kb uint64) string {
gb := float64(kb) / (1024.0 * 1024.0)
if gb < 1 {
return fmt.Sprintf("%.0fM", float64(kb)/1024.0)
}
return fmt.Sprintf("%.1fG", gb)
}
partitions = append(partitions, partition{
Mount: mount,
Size: formatGB(totalKB),
Avail: formatGB(availKB),
UsedPct: pct,
})
_ = usedKB
}
diskTotalGB := float64(diskTotalKB) / (1024.0 * 1024.0)
diskUsedGB := float64(diskUsedKB) / (1024.0 * 1024.0)
// ── Parse OS / timezone / hostname ───────────────────────────────
osName := "Linux"
for _, l := range extractSection(lines1, "---OS---", "---TZ---") {
if strings.HasPrefix(l, "PRETTY_NAME=") {
osName = strings.Trim(strings.TrimPrefix(l, "PRETTY_NAME="), "\"")
}
}
tzStr := "UTC"
for _, l := range extractSection(lines1, "---TZ---", "---HOSTNAME---") {
t := strings.TrimSpace(l)
if t != "" {
tzStr = t
break
}
}
hostname := ""
for _, l := range extractSection(lines1, "---HOSTNAME---", "---IP---") {
t := strings.TrimSpace(l)
if t != "" {
hostname = t
break
}
}
ipAddr := ""
for _, l := range extractSection(lines1, "---IP---", "---CPU1---") {
t := strings.TrimSpace(l)
if t != "" {
ipAddr = t
break
}
}
// ── Parse CPU (/proc/stat delta, XTerminal method) ────────────────
cpuLines1 := extractSection(lines1, "---CPU1---", "---NET1---")
cpuLines2 := extractSection(lines2, "", "---NET2---") // empty startMarker = collect from beginning
parseStat := func(lines []string) map[string][]uint64 {
res := make(map[string][]uint64)
for _, l := range lines {
if !strings.HasPrefix(l, "cpu") {
continue
}
parts := strings.Fields(l)
if len(parts) < 5 {
continue
}
// /proc/stat fields: user nice system idle iowait irq softirq steal ...
getU := func(i int) uint64 {
if i+1 < len(parts) {
v, _ := strconv.ParseUint(parts[i+1], 10, 64)
return v
}
return 0
}
userN := getU(0) + getU(1) // user + nice
sysN := getU(2) + getU(5) + getU(6) + getU(7) // system + irq + softirq + steal
idleN := getU(3) + getU(4) // idle + iowait
total := userN + sysN + idleN
res[parts[0]] = []uint64{userN, sysN, idleN, total}
}
return res
}
cpus1 := parseStat(cpuLines1)
cpus2 := parseStat(cpuLines2)
computeUsage := func(name string) float64 {
v1, ok1 := cpus1[name]
v2, ok2 := cpus2[name]
if !ok1 || !ok2 || len(v1) < 4 || len(v2) < 4 {
return 0
}
// v = [user+nice, system+irq+softirq+steal, idle+iowait, total]
dTotal := float64(v2[3]) - float64(v1[3])
dIdle := float64(v2[2]) - float64(v1[2])
if dTotal <= 0 {
return 0
}
usage := 100.0 * (1.0 - dIdle/dTotal)
if usage < 0 {
return 0
}
if usage > 100 {
return 100
}
return usage
}
cpuTotalUsage := computeUsage("cpu")
// Collect core names, sort them (cpu0, cpu1, cpu2...)
var coreNames []string
for name := range cpus2 {
if name != "cpu" && strings.HasPrefix(name, "cpu") {
coreNames = append(coreNames, name)
}
}
sort.Strings(coreNames)
var cpuCoreUsages []float64
for _, name := range coreNames {
cpuCoreUsages = append(cpuCoreUsages, computeUsage(name))
}
// ── Parse Network ─────────────────────────────────────────────────
parseNetDev2 := func(lines []string) map[string][]uint64 {
res := make(map[string][]uint64)
for _, l := range lines {
if !strings.Contains(l, ":") {
continue
}
parts := strings.SplitN(l, ":", 2)
name := strings.TrimSpace(parts[0])
if name == "lo" {
continue
}
fields := strings.Fields(parts[1])
if len(fields) < 9 {
continue