Wednesday, July 11, 2012

SSH in scripts whit password using expect (not using keys)

To use ssh in scripts, its sure the most secure way to use ssh-keys. But some times that isn't possible. In that case the security focuset aprocach in ssh to not accept plain passwords in a other way than direkt keyboard imput is a pain in the ass. I tryed different aprochs to go around this like using sshpass or fd0ssh but it wasn't realy working for me. Using expect was working:

Install expect
sudo apt-get install expect
Then you can write a expect script like that
#!/usr/bin/expect -f

# Do not time out
set timeout -1

# Run the SSH comand (As example: open a tunnel for rsync)
spawn ssh -fNL localhost:1873:localhost:873 USER@EXAMPLE.com

# When the passwort prompt is displayed, type and send the password
expect "*?assword:" { send "PASSWORD\r"}

# We need to wayt a little bit
sleep 2
Or the same in a shell script:
#!/bin/sh
export "SSHPASS=PASSWORD"

/usr/bin/expect <<EOD
set timeout -1
spawn ssh -fNL localhost:1873:localhost:873 USER@EXAMPLE.com
expect "*?assword:" { send "$SSHPASS\r"}
sleep 2
EOD