Provide password to ssh command inside bash script

2020-05-22 10:17发布

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.

  • I can not work outside shell's standards,therefore i can not use expect because i do not know if it will be available on this machine.
  • I can not expect that this machine will have public keys for the SSH.

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 :)

4条回答
闹够了就滚
2楼-- · 2020-05-22 11:01

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

查看更多
叛逆
3楼-- · 2020-05-22 11:04

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.

查看更多
做个烂人
4楼-- · 2020-05-22 11:11

Install sshpass, then launch the command:

sshpass -p "yourpassword" ssh -o StrictHostKeyChecking=no yourusername@hostname
查看更多
Explosion°爆炸
5楼-- · 2020-05-22 11:18

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?

查看更多
登录 后发表回答