Specify private key in SSH as string

2020-02-20 07:06发布

I can connect to a server via SSH using the -i option to specify the private key:

ssh -i ~/.ssh/id_dsa user@hostname

I am creating a script that takes the id_dsa text from the database but I am not sure how I can give that string to SSH. I would need something like:

ssh --option $STRING user@hostname

Where $STRING contains the value of id_dsa. I need to know the --option if there is one.

标签: bash ssh
3条回答
地球回转人心会变
2楼-- · 2020-02-20 07:59

There is no such switch - as it would leak sensitive information. If there were, anyone could get your private key by doing a simple ps command.

EDIT: (because of theg added details in comment)

You really should store the key in to a temporary file. Make sure you set the permissions correctly before writing to the file, if you do not use command like mktemp to create the temporary file.

Make sure you run the broker (or agent in case of OpenSSH) process and load the key using <whatever command you use to fetch it form the database> | ssh-add -

查看更多
放荡不羁爱自由
3楼-- · 2020-02-20 08:02

Try the following:

echo $KEY | ssh -i /dev/stdin username@host command

The key doesn't appear from a PS statement, but because stdin is redirected it's only useful for single commands or tunnels.

查看更多
Lonely孤独者°
4楼-- · 2020-02-20 08:11

Passing cryptokey as a string is not advisable but for the sake of the question, I would say I came across the same situation where I need to pass key as a string in a script. I could use key stored in a file too but the nature of the script is to make it very flexible, containing everything in itself was a requirement. so I used to assign variable and pass it and echo it as follows :

#!/bin/bash
KEY="${ YOUR SSH KEY HERE INSIDE }"
echo "${KEY}" | ssh -q -i /dev/stdin username@IP 'hostnamectl'
exit 0

Notes: -q suppress all warnings

By the way , the catch here in above script, since we are using echo it will print the ssh key which is again not recommended , to hide that you can use grep to grep some anything which will not be printed for sure but still stdin will have the value from the echo. So the final cmd can be modified as follows :

#!/bin/bash
KEY="${ YOUR SSH KEY HERE INSIDE }"
echo "${KEY}" | grep -qw "less" | ssh -q -i /dev/stdin username@IP 'hostnamectl'
exit 0

This worked for me.

查看更多
登录 后发表回答