linuxbashshellssh

Provide password to ssh command inside bash script, Without the usage of public keys and Expect


I want to use SSH inside a script, but this script is not going to be executed on my machine.

In my implementation there are two limitations.

What are the possible options-solutions ?

How can i provide ssh with the requested password with an automated and secure way without adding extra dependencies?

Will it be possible to provide the password inside the script?

Thank you all in advance :)


Solution

  • First of all: Don't put secrets in clear text unless you know why it is a safe thing to do (i.e. you have assessed what damage can be done by an attacker knowing the secret).

    If you are ok with putting secrets in your script, you could ship an ssh key with it and execute in an ssh-agent shell:

    #!/usr/bin/env ssh-agent /usr/bin/env bash
    KEYFILE=`mktemp`
    cat << EOF > ${KEYFILE}
    -----BEGIN RSA PRIVATE KEY-----
    [.......]
    EOF
    ssh-add ${KEYFILE}
    
    # do your ssh things here...
    
    # Remove the key file.
    rm -f ${KEYFILE}
    

    A benefit of using ssh keys is that you can easily use forced commands to limit what the keyholder can do on the server.

    A more secure approach would be to let the script run ssh-keygen -f ~/.ssh/my-script-key to create a private key specific for this purpose, but then you would also need a routine for adding the public key to the server.