Daoud Shaheen Daoud Shaheen - 1 month ago 15
Linux Question

Expect script return "missing close-bracket"

I wrote a bash script that get a password from an API and use "send" to set this password

un=admin
pw=$(get_json_value_from_file "$rsm_res_file" "password")
echo $pw
export HISTIGNORE="expect*";
expect -c "
spawn ssh -o UserKnownHostsFile=$ap_known_hosts_file -p $PORT $un@localhost
expect "*ogin*"
send \"$un\r\"
expect "*assword*"
send \"$pw\r\"
interact"


and it retuned the folowing exception:

missing close-bracket
while executing "send \"f40T[2[6g%^TsMLv\r\"
interact"


I think the problem with the special characters.

Answer

Your password includes a [ char which has special meaning. The [...] syntax in Tcl/Expect is command substitutin just like `...` or $(...) in Bash. To get a literal [ you have to use \[. For your scenario the easiest solution is to pass the password from Bash to Expect by using an env var. E.g.:

PASSWORD=$pw expect -c "
    spawn ssh -o UserKnownHostsFile=$ap_known_hosts_file -p $PORT  $un@localhost
    expect "*ogin*"
    send \"$un\r\"
    expect "*assword*"
    send \$env(PASSWORD)\r
    interact"

or

export PASSWORD=$pw
expect -c "
    spawn ssh -o UserKnownHostsFile=$ap_known_hosts_file -p $PORT  $un@localhost
    expect "*ogin*"
    send \"$un\r\"
    expect "*assword*"
    send \$env(PASSWORD)\r
    interact"
Comments