使用SSH密钥在bash脚本 [英] using ssh keys in bash script
问题描述
我设置SSH密钥形成一个服务器到服务器B,我可以登录到服务器B没有密码。我试图建立一个bash脚本反向的SSH隧道。在命令行中如果我做
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
表格服务器A上它按预期工作即不需要密码,但如果我用它在脚本
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?
推荐答案
您需要让 SSH
知道它应搜索键,如果他们不标准位置,而不是口令保护。最简单的就是通过指定直接 -i
开关置于 SSH
:
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
还是以清洁的方式你的的〜/ .ssh / config中
是这样的:
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.
如果您在标准位置键(的〜/ .ssh / id_rsa
),您的code应该只是罚款。当然如果你有存储在的ssh-agent
你的钥匙,它可以验证使用它应该工作的ssh-添加-L
启动脚本之前。 的ssh-agent
也解决不了问题,如果他密钥的密码保护。
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.
这篇关于使用SSH密钥在bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!