Last Updated: February 25, 2016
·
2.753K
· meistermeier

Utilize bash and expect for e.g. ssh stuff

Using expect to work right in a bash environment for automation can be a pain in the a**. Here are some commented snippets to get the right start:

SSH_USER="user"
SSH_PASS="pass"
SSH_HOST="1.2.3.4"
SSH_COMMAND="ls"

#start the expect fun
/usr/bin/expect << EOF
set timeout 120
spawn ssh $SSH_USER@$SSH_HOST {$SSH_COMMAND}
expect {
    "$SSH_HOST*assword" {
    send {$SSH_PASS}
    send "\n"
    }
    default {}
}
expect eof
EOF

Notice:
- timeout value depends on your command's execution time
- {..} in the send pass line escapes special characters like $
- if the user uses pub keys ignore ssh pass and jump into default
! It's easier and cleaner to use straight expect script where possible !