|
| 1 | +#!/usr/bin/env expect -f |
| 2 | + |
| 3 | +# 用法: |
| 4 | +# arthas_telnet.exp <host> <port> <commands_file> <timeout_seconds> <transcript_file> |
| 5 | +# |
| 6 | +# 说明: |
| 7 | +# - 通过 telnet 连接 Arthas,按行执行 commands_file 里的命令,最后执行 stop 并等待连接关闭。 |
| 8 | +# - 为避免 CI 卡死,每条命令都设置超时;超时会尝试发送 Ctrl+C 进行中断并继续。 |
| 9 | + |
| 10 | +proc usage {} { |
| 11 | + puts stderr "usage: arthas_telnet.exp <host> <port> <commands_file> <timeout_seconds> <transcript_file>" |
| 12 | + exit 1 |
| 13 | +} |
| 14 | + |
| 15 | +if {[llength $argv] < 5} { |
| 16 | + usage |
| 17 | +} |
| 18 | + |
| 19 | +set host [lindex $argv 0] |
| 20 | +set port [lindex $argv 1] |
| 21 | +set commands_file [lindex $argv 2] |
| 22 | +set timeout_seconds [lindex $argv 3] |
| 23 | +set transcript_file [lindex $argv 4] |
| 24 | + |
| 25 | +log_file -noappend $transcript_file |
| 26 | +set timeout $timeout_seconds |
| 27 | + |
| 28 | +spawn telnet $host $port |
| 29 | + |
| 30 | +# Arthas 默认 prompt 为 "$ "(可能带 ANSI 颜色),匹配子串即可。 |
| 31 | +set prompt_re {\$ } |
| 32 | + |
| 33 | +expect { |
| 34 | + -re $prompt_re {} |
| 35 | + timeout { |
| 36 | + puts stderr "ERROR: 等待 Arthas prompt 超时" |
| 37 | + exit 2 |
| 38 | + } |
| 39 | + eof { |
| 40 | + puts stderr "ERROR: 未出现 prompt 连接已关闭" |
| 41 | + exit 3 |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +set fp [open $commands_file r] |
| 46 | +while {[gets $fp line] >= 0} { |
| 47 | + set line [string trim $line] |
| 48 | + if {$line eq ""} { continue } |
| 49 | + if {[string match "#*" $line]} { continue } |
| 50 | + |
| 51 | + send -- "$line\r" |
| 52 | + |
| 53 | + expect { |
| 54 | + -re $prompt_re {} |
| 55 | + -re {Session has been terminated} { |
| 56 | + close $fp |
| 57 | + exit 0 |
| 58 | + } |
| 59 | + timeout { |
| 60 | + # 命令可能是持续输出/等待触发,尝试 Ctrl+C 打断后继续。 |
| 61 | + send -- "\003" |
| 62 | + expect { |
| 63 | + -re $prompt_re {} |
| 64 | + timeout { |
| 65 | + puts stderr "ERROR: 命令超时且 Ctrl+C 未恢复到 prompt: $line" |
| 66 | + close $fp |
| 67 | + exit 4 |
| 68 | + } |
| 69 | + eof { |
| 70 | + puts stderr "ERROR: Ctrl+C 后连接关闭: $line" |
| 71 | + close $fp |
| 72 | + exit 5 |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + eof { |
| 77 | + puts stderr "ERROR: 命令执行后连接关闭: $line" |
| 78 | + close $fp |
| 79 | + exit 6 |
| 80 | + } |
| 81 | + } |
| 82 | +} |
| 83 | +close $fp |
| 84 | + |
| 85 | +send -- "stop\r" |
| 86 | +expect { |
| 87 | + -re {Session has been terminated} {} |
| 88 | + eof {} |
| 89 | + timeout { |
| 90 | + puts stderr "ERROR: stop 超时" |
| 91 | + exit 7 |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +exit 0 |
| 96 | + |
0 commit comments