Non-interactive ssh with expect

      1 Comment on Non-interactive ssh with expect

If you need a programmatic ssh login, i.e. in a shell script, the best way to make ssh non-interactive usually is a public-key authentication. This requires the public key to be stored on the host machine, which (admitted, in very rare cases) can be hard or impossible. One of those rare cases might be a chrooted environment on a webserver without write access to the ssh config file or the per-user ssh directory.

Unfortunately, most ssh clients don’t allow piping a clear text password from a file or varibale. One solution is to use the SSH_ASKPASS environment variable and a wrapper script but most recommendations suggest the use of expect.

Expect is basically a scripting language to make interactive applications non-interactive. It is often used to automate reactions to certain outputs from programs like ftp, ssh, scp and others.

A simple expect script to rsync a backup from one host to another could look like this

#!/usr/bin/expect
set timeout 600
spawn rsync -avhS user@host:/backups/ /backups/
expect {
   "password" {send "secret\n";}
}
expect {
   eof {exit 0;}
}

Note that expect eof is used here, because the alternative interact command is not compatible with cron scripts.

For a list of commands have a look at the expect man page or expect’s sourceforge page.

One thought on “Non-interactive ssh with expect

Leave a Reply

Your email address will not be published.