Home Expect: how to spawn a command containing a backslash?
Reply: 1

Expect: how to spawn a command containing a backslash?

samwyse
1#
samwyse Published in 2017-11-08 14:41:53Z

I have the following script:

#!/bin/bash
echo -n "Enter user name: "
read USER
echo -n "Enter password: "
read -s PWD
cat $HOME/etc/switches.txt | while read IP SWITCH
do
  echo ${SWITCH}
  /usr/bin/expect <<EOD
# Change to 1 to Log to STDOUT
log_user 1
# Change to 1 to enable verbose debugging
exp_internal 1
# Set timeout for the script
set timeout 20
spawn ssh -l {$USER} -oCheckHostIP=no -oStrictHostKeyChecking=no -q $IP
match_max [expr 32 * 1024]
expect "Password:"
send $PWD
send "\n"
expect "#"
send "show fcip summary | grep TRNK\n"
EOD
  echo
done

When I run it, the backslash in the username disappears, giving these result:

Enter user name: corp\user
Enter password:
=== ss3303-m-esannw-m01a ===
spawn ssh -l corpuser -oCheckHostIP=no -oStrictHostKeyChecking=no -q 10.247.184.70
[...]

I suspect my problem is due in part to embedding my expect script inside a bash script. I've tried using $USER and "$USER" as well, with the same results. Using corp\\\\user (yes, four backslashes!) does work but is inconvenient. I'm seriously considering using sed or something to multiply the backslashes, but would love to hear other ideas.

glenn jackman
2#
glenn jackman Reply to 2017-11-08 15:12:09Z

You might have better luck passing the variables through the environment so expect can access them directly, instead of relying on the shell to substitute the values into the heredoc:

#!/bin/bash
read -p "Enter user name: " USER
read -sp "Enter password: " PWD
export USER PWD IP
while read IP SWITCH
do
    echo ${SWITCH}
    # the heredoc is single quoted below
    /usr/bin/expect <<'EOD'
        # Change to 1 to Log to STDOUT
        log_user 1
        # Change to 1 to enable verbose debugging
        exp_internal 1
        # Set timeout for the script
        set timeout 20
        match_max [expr {32 * 1024}]

        spawn ssh -l $env(USER) -oCheckHostIP=no -oStrictHostKeyChecking=no -q $env(IP)
        expect "Password:"
        send -- "$env(PWD)\r"
        expect "#"
        send "show fcip summary | grep TRNK\r"
        expect eof
EOD
    echo
done <$HOME/etc/switches.txt 

Notes:

  • the heredoc is single-quoted: the shell will not try to interpolate variables
  • exported the shell variables used in the expect code
  • use \r to "press enter" for the send command.
  • tidied up the input of the username and password
  • tidied up reading the text file
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.462764 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO