Linux – How to use password from environment variable in linux command

linuxssh

I want to run below command in a script (means I cannot run interactively in a terminal and therefore can enter password when prompted):

ssh -o StrictHostKeyChecking=no user@example.com 'echo mypassword |
sudo -kS ufw status

'

this will ssh into remote host and run command ufw status on remote host.

The command works fine but I need to be able to reference 'password' from environment variable named

SSHPASS = mypassword

which stores the password in order not to expose the password in the command. How to do that?

Best Answer

You can pass the variable containig the password to ssh via the sshpass command:

sshpass -p "$SSHPASS" ssh -o StrictHostKeyChecking=no user@example.com

That said, that's not much more secure than having the password in the script!

A better solution when you need to access servers via ssh in scripts would be moving to key based authentication.