简体   繁体   中英

Have remote shell evaluate expressions inside expect ssh script

I have to use expect and ssh for automating on a remote shell ( bash shell locally and remotely in my particular case). That is, I need to wrap ssh someuser@example.com "echo This is \\$(hostname)" inside an expect script.

Running the above "manual" script, I get the expected output: This is example.com , so the $(hostname) expression ( command substitution ) gets evaluated on the remote machine.

Now I wrapped that ssh-remote-shell command inside an expect here document :

#/bin/bash

expect <<- DONE
  spawn ssh someuser@example.com "echo This is \\$(hostname)"
DONE

The wrapped script returns [...] This is localhost instead. So the $(hostname) expression gets evaluated on my local machine, not on the remote machine.

I've tried different levels of backslash escaping, single quotes and double quotes, <<- DONE and << DONE , and moving $(hostname) to its own expect variable (ie, set someCommand "\\\\$hostname" , then referencing $someCommand ). But nothing helped.

How can I have the remote shell evaluate shell expressions in SSH expect scripts?

You are almost there.

#!/bin/bash
expect <<- DONE
 set timeout 120
 spawn ssh dinesh@remote-lab "echo This is \\\$(hostname)"
 expect {
         "password: $" {send "welcome\r";exp_continue}
         eof
 }
DONE

Output :

dinesh@myPC:~/stackoverflow$ ./abdull
spawn ssh dinesh@remote-lab echo This is $(hostname)
dinesh@remote-lab's password: 
This is remote-lab

Note : The spawn statement can also be written as

 spawn ssh dinesh@remote-lab {echo This is \$(hostname)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM