bash telnet 从期望中获取标准输出

问题描述

我需要从 telnet shell 获取数据集,为此我查看了 expect https://www2.lib.uchicago.edu/keith/tcl-course/topics/expect.html

这是我的期望脚本:

/usr/bin/expect -d <<  EOD
spawn telnet myhost
log_user 1
set timeout 10
expect "Login:"
send "user\n\r"
expect "Password:"
send "password\n\r"
expect "*$*"
send "AT\n\r"
expect "OK"
send "AT&CSR\n"
expect "OK"
send "AT!G=A6\n"
expect "OK"
send "AT^MI=0\n"
expect "OK"
send "AT^SX=0\n"
expect "OK"
send "AT^SR=0,1"
expect "*$*"
send "exit\r"

现在我可以连接到远程主机,发送命令,但无法读取结果,这里是一个shell结果:

> expect: does " " (spawn_id exp4) match glob pattern "*"? yes expect:
> set expect_out(0,string) " " expect: set expect_out(spawn_id) "exp4"
> expect: set expect_out(buffer) " " send: sending "AT\n\r" to { exp4 }
> 
> expect: does "" (spawn_id exp4) match glob pattern "OK"? no
> ********
> 
> OK
> 
> expect: does "********\r\n\r\nOK\r\n" (spawn_id exp4) match glob
> pattern "OK"? yes expect: set expect_out(0,string) "OK" expect: set
> expect_out(spawn_id) "exp4" expect: set expect_out(buffer)
> "********\r\n\r\nOK" send: sending "AT&CSR\n" to { exp4 }
> 
> expect: does "\r\n" (spawn_id exp4) match glob pattern "OK"? no AT
> 
> expect: does "\r\nAT\r\n" (spawn_id exp4) match glob pattern "OK"? no
> 
> OK
> 
> expect: does "\r\nAT\r\n\r\nOK\r\n" (spawn_id exp4) match glob pattern
> "OK"? yes expect: set expect_out(0,string) "OK" expect: set
> expect_out(spawn_id) "exp4" expect: set expect_out(buffer)
> "\r\nAT\r\n\r\nOK" send: sending "AT!G=A6\n" to { exp4 }
> 
> expect: does "\r\n" (spawn_id exp4) match glob pattern "OK"? no AT&CSR
> expect: does "\r\nAT&CSR" (spawn_id exp4) match glob pattern "OK"? no
> AT!G=A6 expect: does "\r\nAT&CSRAT!G=A6" (spawn_id exp4) match glob
> pattern "OK"? no expect: timed out send: sending "AT^MI=0\n" to { exp4
> }
> 
> expect: does "\r\nAT&CSRAT!G=A6" (spawn_id exp4) match glob pattern
> "OK"? no AT^MI=0

如果命令的结果与预期的不匹配,它会转到下一个命令,有没有办法捕获响应结果?

编辑:
我试图简化事情并添加交互,但没有运气:

 /usr/bin/expect -d <<  EOD
> spawn telnet myhost
> log_user 1
> interact"
> EOD
expect version 5.45.4
argv[0] = /usr/bin/expect  argv[1] = -d  
set argc 0
set argv0 "/usr/bin/expect"
set argv ""
executing commands from command file
spawn telnet myhost
parent: waiting for sync byte
parent: telling child to go ahead
parent: Now unsynchronized from child
spawn: returns {11306}
invalid command name "interact""
    while executing
"interact""

解决方法

你发送 AT 命令的方式是错误的。

根据ETSI specification 127.007,默认情况下AT命令以\r(IRA 13 - ASCII回车)字符[1]结束。有关更多详细信息,请参阅段落 “4.1 - 命令行”

为了解决您的问题,只需发送 AT\r 而不是 AT\n\rAT&CSR\r 而不是 AT&CSR\n 等等(后者是您重复的错误遵循 AT 命令)。否则 AT 解析器将无法正确识别您的命令。


[1]命令行终止字符可以通过ATS3命令自定义,语法如下:

ATS3=<value>

其中 <value> 是新命令行终止字符的十进制 ASCII 值(默认为 13)。