Linux – Bash Script – Expect does not send password that ends with $!. Also need improvement to report connection timed out

bashexpectlinuxscriptingshell-scripting

Update: Password issue is fixed and connection timed out message was fixed too.

Adding \ before $! worked. Example: *password\$!

set passwds { *password\$! @tempP@ss %Test4%}

For connection timed out, added the below code after "s password:" line

timeout { puts stdout "$server_address : connection timed out"}

This script does not report if the connection times out. It just jumps to the next IP. If it reported connection timed out, then i could grep and find all the IP's easily and do something.

I want this part of the code to report if connection failed

ssh -t root@$server_address "$*"

Also this script fails to send passwords that ends with $!.
The password is *password$! but it sends it as *password

Expect debug with exp_internal 1:

expect: set expect_out(0,string) "\r\nPermission denied, please try again.\r\r\nroot@10.10.10.10's password: "
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) "\r\nPermission denied, please try again.\r\r\nroot@10.10.10.10's password: "
send: sending "*password\r" to { exp4 }
expect: continuing expect

Here is the code:

#!/bin/bash
(( $# != 1 )) && { echo >&2 "Usage: $0 \"[COMMAND]\""; exit 1; }
servers_addresses=(10.10.10.10)
for server_address in ${servers_addresses[@]}; do
        expect <<EOF
set passwds { *password$! @tempP@ss %Test4%}
set i 0
spawn ssh -t root@$server_address "$*"
expect {
    "Are you sure you want to continue connecting (yes/no)?" { send "yes\r"; exp_continue }
    "s password:" { send "[lindex \$passwords_ssh \$x]\r"; incr x; exp_continue }
    eof
}
EOF
done

Best Answer

Variables get expanded if used in double "" quotes, and Bash treats everything starting with $ as a variable.

Use single quotes '' instead.

ssh will end with an exit code <> 0 if an error occurred. This is stored in $?