期望脚本捕获垃圾字符-需要删除

时间:2019-03-07 18:27:01

标签: expect

我正在尝试编写一个开关,以从hp开关中获取输出。源计算机是Ubuntu 18.04。交换机上的代码版本为16.04。我尝试将交换机的终端设置从默认的vty100更改为ansi,但没有区别。如何摆脱下面显示的其他特殊字符?

set timeout 20
spawn ssh -l manager 192.168.10.10
expect "manager@192.168.10.10's password:"
send "admin\n"
expect "Press any key to continue"
send "j\n"
log_file -a hp.log
send "show vlan 10\n"
expect "labswitch#"
send "conf\n"
send "hostname newswitch\n"
expect "newswitch#"
send "exit\n"
expect "newswitch#"
send "logout\n"

我通过日志文件和控制台中脚本的每个部分来输出这些额外的字符。需要从输出中删除这些字符。 ??

^[[?6l^[[1;30r^[[?7h^[[2J^[[1;1H^[[1920;1920H^[[6n^[[1;1HYour previous successful login (as manager) was on 2019-03-07 $ from 192.168.10.4
^[[1;30r^[[30;1H^[[30;1H^[[2K^[[30;1H^[[?25h^[[30;1H^[[30;1labswitch# ^[[30;1H^[[30;11H^[[30;1H^[[?25h^[[30;11H^[[1;0H^$ Status and Counters - VLAN Information - VLAN 10

  VLAN ID : 10
  Name : Server_Lab
  Status : Port-based
  Voice : No
  Jumbo : Yes
  Private VLAN : none
  Associated Primary VID : none
  Associated Secondary VIDs : none

  Port Information Mode     Unknown VLAN Status
  ---------------- -------- ------------ ----------
  11               Tagged   Learn        Up
  12               Tagged   Learn        Up


^[[1;30r^[[30;1H^[[30;1H^[[2K^[[30;1H^[[?25h^[[30;1H^[[30;1H

1 个答案:

答案 0 :(得分:1)

这些是ANSI Escape sequences

您应该可以使用以下方法将它们从日志文件中删除:

send "logout\r"    ;# idiomatically, use \r to "hit enter"
log_file           ;# turn off logging

# read the log file
set fid [open hp.log r]
set contents [read -nonewline $fid]
close $fid

# remove the escape sequences
regsub -all {\033\[(?:\?|\d+;)?\d+[[:alpha:]]} $contents {} stripped

# write the new contents
set fid [open hp.log w]
puts $fid $stripped
close $fid