1

in expect script I can set any command or character to run it on remote machine but the sad thing is that expect cant send the same character as they defined in the expect script

for example

I want to run this line from expect script in order to change IP address from 10.10.10.10 to 1.1.1.1

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

but when I run the expect screen actually I see this line runing on the console:

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

pay attention that the backslash before Q and before E was Disappeared

so I wonder hoW to escape those characters from expect script?

so expect will run the same line on the console as following

   [root@localhost ~]# perl -i -pe 's/\Q10.10.10.10\E/1.1.1.1/' /etc/hosts
  • REMARK set a backslash "\" before backslash doesn’t help!!!

my script:

 #!/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" 

RESULTS ( after I run my script: )

   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 Answers2

2

I am not entirely sure why, but you need some extra escapes. Try this:

{send "perl -i -pe 's/\\\\\Q127.0.0.1\\\\\E/1.1.1.1/' /etc/hosts\r"}

I am not sure about the details but this has something to do with the script being run i) via the shell, ii) through expect and iii) through Perl. Probably each of these (or a combination) needs to have the \ escaped which is why you end up needing so many nested escapes.

Anyway, as @slm mentioned in his comment, you really don't need expect for this. Just set up password-less ssh and then simply run

ssh  192.9.200.10 perl -i -pe 's/\Q127.0.0.1\E/1.1.1.1/' /etc/hosts
terdon
  • 242,166
  • Yeah I think it has something to do with the fact that he's ssh ... to another host, you typically have t escape at least once for that, plus another time for the shell (hence my approach). – slm Aug 04 '13 at 18:11
1

Instead of doing expect you could do this with just vanilla ssh and a HEREDOC:

#!/bin/bash

ssh -T ssh root@192.9.200.10 <<\EOI
perl -i -pe 's/\Q10.10.10.10\E/1.1.1.1/' /etc/hosts
EOI

I'm not that up on ksh but this should easily be adapted to that if needed. Also I'm using a ssh key-pair to facilitate logging in remotely without needing to feed a password.

slm
  • 369,824