Shell Script for logging into a ssh server

I once wrote an expect script to log in to a ssh server (like your case) and my script was something like this:

#!/usr/bin/expect

spawn ssh [email protected]
expect "password"
send "MyPassword\r"
interact

I think maybe the interact is missing in your script.


You're going about it the wrong way. What you want to do is generate a passwordless ssh-key pair and then (as long as the server supports RSA key authentication) you can get in without having to type a password for all. This is a security risk if your private key is stored somewhere that it could be stolen.

Follow these steps:

  1. mkdir -p ~/.ssh
  2. cd ~/.ssh
  3. ssh-keygen -type dsa -i mysshkeys
  4. Press Return when prompted for passphrase
  5. Press Return a second time to confirm.

There will now be two files in your ~/.ssh directory, mysshkey.pub and mysshkey. mysshkey.pub is your public key, this one is safe to put on remote servers. mysshkey is your private passwordless key, it is not safe to put on remote servers (or somewhere someone else could get a copy).

On the server you wish to SSH into:

  1. Login to the remote server
  2. mkdir -p ~/.ssh
  3. Copy and paste the contents of mysshkey.pub into ~/.ssh/authorized_keys
  4. Make sure that ~/.ssh/authorized_keys is chmod'd to 600

Now, to put it into action on your local machine you run the following command:

ssh -i ~/.ssh/mysshkey <remote_server_ip>

And you will be logged in without being prompted for a password.

This is a much preferable method of managing automated logins as you don't end up hard-coding your password multiple places that need to be updated if you ever change it.


On Debian-based distributions, the sshpass package provides an easier way of doing what you want. The package is available for many other popular distributions. You need to set it up first:

echo 'YourPassword' > passwordFile.txt
chmod 600 passwordFile.txt

Then invoke the SSH command from a script like this:

sshpass -f /path/to/passwordFile.txt /usr/bin/ssh -p 8484 [email protected]

This provides more flexibility, such as if you're using a different locale or need to change the password, than solutions using expect.