I have an expect script embedded in a bash script:
#! /bin/bash
# this function runs a command like 'ssh' and provides the password
function with_password {
expect << END
spawn $2
expect *assword:*
send -- $1
interact
wait
END
}
# run "long_running_command" on the remote server
with_password my_password "ssh my_user@some-server long_running_command"
# rsync some data to the remote server
with_password my_password "rsync /some/dir my_user@some-server:/remote/dir"
# run some other random command
with_password my_password "ssh my_user@some-server some_other_command"
The problem is that sometimes the script will hang while waiting for a spawned command. If I
leave the wait
command out of the expect script, the command will continue to run on the remote
server, but the bash script will continue, and I have no way of knowing when it finishes.
Why does my expect script seem to be randomly hanging?
The
interact
command in theexpect
here-doc was the problem. I needed to wait for EOF instead:The
interact
command seem to work sometimes when the ssh/rsync command closed the input at the correct time (maybe?), but it wasn't reliable.What about using passwordless logins with ssh keys?
You can create your keys with
ssh-keygen
then put your public key on the remote end:~/.ssh/authorized_keys
.You can even create keys with passphrase (if you want to add some kind of security) which you can load in your shell with
ssh-agent bash
enter you pass once, and it will keep your unlocked key in the memory for later password promptless logins.You are missing the final here doc delimiter.