如何从期望脚本中逃避异常/独特的角色?

时间:2013-08-04 15:55:46

标签: linux tcl ksh expect

在expect脚本中我可以设置任何命令或字符在远程机器上运行它 但令人遗憾的是,期望无法发送与期望脚本中定义的相同的字符

例如

我想从expect脚本运行此行,以便从 10.10.10.10 更改IP地址 到 1.1.1.1

    expect #  {send "perl -i -pe 's/\Q10.10.10.10\E/1.1.1.1/' /etc/hosts\r"}

但是当我运行expect屏幕时,实际上我看到这条线在控制台上运行:

   [root@localhost ~]# perl -i -pe 's/Q10.10.10.10E/1.1.1.1/' /etc/hosts

注意Q之前和E之前的反斜杠消失

所以我想知道如何从期望脚本中逃脱这些角色?

所以期望在控制台上运行与以下相同的行

   [root@localhost ~]# perl -i -pe 's/\Q10.10.10.10\E/1.1.1.1/' /etc/hosts
  • REMARK在反斜杠无效之前设置反斜杠“\”!

我的剧本:

 #!/bin/ksh

 #
  expect=`cat << EOF
  set timeout -1
  spawn  ssh  192.9.200.10 
   expect {
             ")?"   { send "yes\r"  ; exp_continue  }

             word:  {send secret1\r}
          }
   expect #  {send "perl -i -pe 's/\\Q10.10.10.10\\E/1.1.1.1/' /etc/hosts\r"}
   expect #    {send exit\r}
   expect eof
   EOF`


    expect -c  "$expect" 

结果(在我运行脚本之后:)

  spawn ssh 192.9.200.10 
  root@'192.9.200.10 s password: 
  Last login: Sun Aug  4 22:46:53 2013 from 192.9.200.10 
  [root@localhost ~]# perl -i -pe 's/Q10.10.10.10E/1.1.1.1/' /etc/hosts
      [root@localhost ~]# exit
      logout

      Connection to 192.9.200.10  closed.

2 个答案:

答案 0 :(得分:4)

使用不同的Tcl引号将起作用

expect #  {
    # send text verbatim here
    send {perl -i -pe 's/\Q10.10.10.10\E/1.1.1.1/' /etc/hosts}
    # interpret backslash sequence as carriage return here
    send "\r"
}

答案 1 :(得分:1)

使用\转义它或将整个内容括在{}

expect #  {send "perl -i -pe 's/\\Q10.10.10.10\\E/1.1.1.1/' /etc/hosts\r"}

(用{}括起整个内容会发送\r作为这2个字符,而不是行终止符,所以这里不合适。)

请参阅manual page about the Tcl Syntax

另一个说明:
你可以用Tcl做同样的事情,只要你不通过SSH发送命令