How to use sshpass?

I need to use sshpass to launch a remote command through SSH from a Java code.

If I manually type in a console:

ssh -p 22 user@ipaddress mplayer '/media/data/myFavouriteSong.mp3'

works perfectly, but asks for password. So I tried running sshpass:

sshpass -p mypass ssh -p 22 user@ipaddress mplayer '/media/data/myFavouriteSong.mp3'
sshpass -p mypass ssh -l user@ipaddress mplayer '/media/data/myFavouriteSong.mp3'
sshpass -p mypass ssh -t user@ipaddress mplayer '/media/data/myFavouriteSong.mp3'
sshpass -p mypass ssh user@ipaddress echo 'OK'

and none of them work.


This may be caused by the host-key checks done by ssh. It looks like sshpass keeps silent on invalid host keys (no output on neither stderr nor stdout) and exists with status-code 6. At the time of this writing, this was revision 50, and the matching constant in the code is RETURN_HOST_KEY_UNKNOWN, which hints to that error.

Your error-code may differ and looking at the code linked above may give you some insight.

If your issue is an invalid host-key you should think twice about overriding the error with a CLI option. Your machine could be compromised or you may be subject to a MITM attack! If you are 100% certain that this is not the case and if you have no means to keep the verified host-keys up-to date, you can use a command like this:

sshpass -pfoobar ssh -o StrictHostKeyChecking=no user@host command_to_run

sshpass command works only if the password prompt ends in assword:.

If your password prompt is different you may have to adjust the source code of sshpass to recognize the prompt you have.

I have seen password prompts like Password for user@host: on some systems, maybe this is your problem.


I think you want something like:

sshpass -p yourpassword ssh user@ipaddress somecommand

For instance, this works for me:

sshpass -p mypassword ssh [email protected] touch foo