【发布时间】:2020-06-13 03:28:50
【问题描述】:
我试图通过登录交换机来捕获“dir”命令的输出,但我无法这样做。我在 Bash 中使用 Expect。我正在使用 expect_out 在缓冲区中捕获该命令的输出并将其打印出来。实际上我想捕获输出并对其执行一些操作。
脚本:
#!/bin/bash
expect -c "
spawn telnet 1.1.1.1 2000
sleep 1
send \"\r\"
send \"\r\"
expect {
Prompt> { send \"dir\r\" }
}
set output $expect_out(buffer)
"
echo "$output"
输出:
spawn telnet 1.1.1.1 2000
Trying 1.1.1.1...
Connected to 1.1.1.1 (1.1.1.1).
Escape character is '^]'.
Prompt>
Prompt>
显示这些提示后,脚本就退出了。我该如何解决这个问题?
拆分后,我可以使用参数替换以及单引号。现在我面临不同的错误。
脚本:
expect -c "
spawn telnet $IP $PORT1
sleep 1
send \"\r\"
send \"\r\"
"
expect -c '
expect {
Prompt> { send \"dir\r\" }
set output $expect_out(buffer)
puts "$output"
}
'
输出:
spawn telnet 172.23.149.139 2033
can't read "expect_out(buffer)": no such variable
while executing
"expect {
Prompt> { send \"dir\r\" }
set output $expect_out(buffer)
puts "$output"
}
"
我根据建议将其更改为。但我仍然面临错误。
脚本:
output=$(expect -c '
spawn telnet '"$IP $PORT1"'
sleep 1
send '"\r"'
send '"\r"'
expect Prompt> { send '"dir\r"' }
expect '"\n"'
expect -indices Prompt>
puts '"[string range $expect_out(buffer) 0 [expr $expect_out(0,end) - 1]]"'
')
echo "======="
echo "$output"
echo "======="
输出:
syntax error in expression "(0,end) - 1"
while executing
"expr (0,end) - 1"
invoked from within
"string range (buffer) 0 [expr (0,end) - 1]"
invoked from within
"puts [string range (buffer) 0 [expr (0,end) - 1]]"
=======
spawn telnet 1.1.1.1 2000
Trying 1.1.1.1...
Connected to 1.1.1.1 (1.1.1.1).
Escape character is '^]'.
Prompt>
Prompt>
=======
因此为了规避错误,我改了行
puts '"[string range $expect_out(buffer) 0 [expr $expect_out(0,end) - 1]]"'
到
puts '"$expect_out(buffer)"'
然后我没有收到任何错误,但dir 的输出也没有被打印出来。比如:
Prompt>
Prompt> (buffer)
【问题讨论】:
-
格式提示:您应该为您的代码和输出块使用正确的代码格式(而不是在每行末尾使用两个尾随空格来强制换行/分段)。除了更健壮(它可以防止对代码的 Markdown 解释)之外,它通常更容易做到,因为您只需突出显示代码并按 Control-K。请参阅Editing Help(位于编辑文本区域右上角正上方的橙色问号)。