Monday, March 18, 2013

sshpass VS expect, what to expect on ssh without password?

SSHPASS VS EXPECT, what to expect when you are expecting?

Some time ago I was in a middle of a script and I found myself trying to connect to a SFTP server to download some files. First of all I tried the powerful 'wget' but this program does not support ssh connections. So let's see what options we have:

  1. sftp (secure file transfer program)
  2. scp (secure copy (remote file copy program))

And to make it harder I don't have access to the remote SFTP server to exchange SSL certificates to connect without password. So here are the options to make a ssh connection with password:

  1. sshpass
  2. expect 

For the first one (sshpass) it did not worked too well. The reason may be the FreeBSD I was using at that moment. But here is an amazing link where you can use this program very easily.

So if you have no luck with sshpass (as I did), there is one more solution. Here is expect. Just let me show you the quick solution :

expect -c 'spawn scp user@remote_host:/the_file.zip /my/local/home; sleep 10; expect assword; send "password\n"; interact'

Let's see this in detail:

  1. The beginning of this command is to invoke the program " expect -c ".
  2. Then between single quotes (') the expect commands are specified.
  3.  "spawn" invokes our external program (sftp, ssh, scp, etc...) in my case 'spawn scp' and following the short-cut for ssh connections 'spawn myuser@remote_server:/path/file/i/want.ext /to/my/folder;'
  4. In my case the sftp server takes some time to respond to my request (it is a network issue so that's why I added this part). Let's wait at least 10 seconds for the server response 'sleep 10;'.
  5. At this point the scp command shows "BLAH BLAH server password:" or "BLAH BLAH password" or "BLAH Password:", this output may change in different unix distros. We tell expect to wait for the 'assword' text that will match with most of the responses showed before 'expect assword;'.
  6. Sends the password NOW!!!, 'password\n;'. And don't forget to set '\n;' because this is the 'return' key press.
  7. And continue every thing as usual ' interact '
Thanks for your time, and read more on this link.

No comments:

Post a Comment