I wrote a script to auto login into a remote server. The login data is stored in a database.

/usr/bin/expect <<EOD
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no $SSHUser@$SSHHost
match_max 100000
expect "*?assword:*"
send -- "$SSHPass\r"
send -- "\r"
expect eof

This works, it logs in succesfully, but I can't interact. No keypresses are sent to the server.


Why Your Script Closes the Socket

Whenever an expect script reaches the end of the file, it closes all spawned processes and exits. In other words, it's currently behaving as-designed.

Keeping the Socket Open for Interaction

What's missing is using the interact command when you see a command prompt. For example, after sending your password:

expect {\$\s*} { interact }

In your particular use case, you could simply call interact immediately after sending your password without waiting for the prompt, but the example above is generally a better practice that allows you to handle other sorts of situations if you choose to do so.

Interact will allow you to do what you want: to interact with the SSH session. This will continue until you close the connection, and the spawned process exits.

See Also


  • I actually did try that, adding expect {\$\s*} { interact } but it does not work.
    – skerit
    Sep 11 '12 at 9:55
  • @skerit That's probably because stdin is already used by your here-document. Try putting the commands in a script instead of a here-document, e.g. expect -f '# your commands here'.
    – CodeGnome
    Sep 11 '12 at 10:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.