using ssh keys in bash script

青春壹個敷衍的年華 提交于 2019-12-24 00:38:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!