Jason Zhu
Jason Zhu

Reputation: 2294

Escape Password variable in expect script

Background: I am trying to write a expect script that will be used for testing special character passwords. One of the test cases that I am failing to get it to execute is having the special character "-" in front of password. For example : "-foo" Note: Assume that ssh key is out of the question Note: Assume bash shell is the shell that I am using

My Code: This is my connect function, courtesy of Wikipedia:

    proc connect {passwd} {
      expect {
        "yes/no" {
          send "yes\r"
        }
      }
      expect {
        "?assword:" {
            send "$passwd\r"
            expect {
              "sftp*" {
                return 0
              }
            }
        }
      }
      # timed out
      return 1

}

set user [lindex $argv 0]
set passwd [lindex $argv 1]
set host [lindex $argv 2]

spawn sftp $user@$host

puts '$passwd'\r
set rez [connect $passwd]

Within my bash script I have:

passwd="-foo"
./sftp_test $user $passwd $host

What I have tried: From what I understand the issue is that the shell is expanding the variable and thus the command is being interpreted as send -foo at which it says send has an invalid password.

I have tried using single quotes as a general solution to this but the password is being rejected (I suspect the single quotes are being preserved). send '$passwd'"\r"

The Question: Is there a way for me to escape the password in the send command so that I can use it for all permutations of special characters in a password (e.g. $foo and f$oo and -foo)?

Upvotes: 1

Views: 4314

Answers (2)

user2704404
user2704404

Reputation: 149

What if the character to be escaped is a $

I need to send the following command but expect keeps treating it as a variable:

    W $$RBLDSTS^VPRJ()

So when I use:

    send "W $$RBLDSTS^VPRJ()\r";

I get:

    can't read "RBLDSTS": no such variable

In this case I had to assign my command to a variable and escape the $ with \

    set command \$\$RBLDSTS^VPRJ()
    send "W $command\r";

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246774

What you need to do is this:

send -- "$passwd\r"

The -- indicates that any following words beginning with a dash are not to be treated as an option to the send command.

You might want to make this a habit and do it for every send command.

Upvotes: 1

Related Questions