问题
I've setup ssh keys form server A to server B and I can login to server B without a password. I'm trying to setup a reverse ssh tunnel in a bash script. From the command line if I do
ssh -N -R 1234:localhost:22 user@mydomain.co.uk -p 22
form server A it works as expected i.e no password required, however if I use it in a script
#!/bin/bash
/usr/bin/ssh -N -R 1234:localhost:22 user@mydomain.co.uk -p 22
I get asked for the password
user@mydomain.co.uk's password:
How do I make it so it uses the keys?
回答1:
You need to let ssh
know where it should search for the keys, if they are not in standard location and not passphrase protected. The easiest thing is by specifying -i
switch directly to ssh
:
/usr/bin/ssh -i /path/to/key -N -R 1234:localhost:22 user@mydomain.co.uk -p 22
Or cleaner way in your ~/.ssh/config
like this:
Host mydomain.co.uk
IdentityFile /path/to/key
But make sure the script is run with your user context, so the script will see the configuration file.
If you have keys in standard location (~/.ssh/id_rsa
), your code should work just fine. Although it should work if you have your keys stored in ssh-agent
, which you can verify using ssh-add -L
before starting the script. ssh-agent
also solve the problem, if he keys are passphrase protected.
来源:https://stackoverflow.com/questions/33848254/using-ssh-keys-in-bash-script