Linux/Security/Ssh in scripts

From Iveze
Jump to: navigation, search

There is no way to pass a password to ssh from within a shell script. Yet there are ways to still use ssh from a script.

Use case

Some servers need ssh access to another server from within a shell script to execute some commands on that other server. i.e. The backup server uses rsync over ssh. Or the ups server needs to shutdown other servers over ssh.

Authentication keys

Ssh can be made password-less to a certain server by exchanging authentication keys. In this manner the user on the connecting server becomes trusted by the user on the connected server.

Often the purpose is to make an automatically executed script (i.e. from cron) execute low level commands on the connected server. In such case you want the user root on the connecting server to be trusted by the user root on the connected server. This example uses user root. But any other user may be used.

Do the following as user root on the connecting server.

Generate the authentication keys for user root once. All questions should be answered blank.


Now the generated public key can be sent to any server where password-less connection is needed from root at this server.

ssh-copy-id -i ~/.ssh/ root@servernameOrIp

Test by connecting to the other server

ssh root@servernameOrIp

No password should be asked now.


A second option is to install sshpass, which makes it possible to pass a password to ssh. Whether it is secure to write passwords in a script is debatable.

Install from the non standard repository Epel.

yum install sshpass

Usage in shell scripts

sshpass -p 'password' ssh root@servernameOrIp '<commands>'