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

前端 未结 4 948
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 03:08

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.

相关标签:
4条回答
  • 2021-02-04 03:17

    For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:

    #!/bin/bash
    
    export SSHPASS="your-password"
    sshpass -e ssh -oBatchMode=no sshUser@remoteHost
    

    You might be interested in How to run the sftp command with a password from Bash script?

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-04 03:25

    Install sshpass, then launch the command:

    sshpass -p "yourpassword" ssh -o StrictHostKeyChecking=no yourusername@hostname
    
    0 讨论(0)
  • 2021-02-04 03:28

    AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program

    0 讨论(0)
提交回复
热议问题