在 bash 脚本中使用 ssh 密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33848254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:55:56  来源:igfitidea点击:

using ssh keys in bash script

bashsshkeytunnel

提问by Lurch

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

我已经设置了从服务器 A 到服务器 B 的 ssh 密钥,我可以在没有密码的情况下登录到服务器 B。我正在尝试在 bash 脚本中设置反向 ssh 隧道。如果我这样做,从命令行

ssh -N -R 1234:localhost:22 [email protected] -p 22

form server A it works as expected i.e no password required, however if I use it in a script

表单服务器 A 它按预期工作,即不需要密码,但是如果我在脚本中使用它

#!/bin/bash
/usr/bin/ssh -N -R 1234:localhost:22 [email protected] -p 22

I get asked for the password

我被要求输入密码

[email protected]'s password:

How do I make it so it uses the keys?

我如何使它使用密钥?

回答by Jakuje

You need to let sshknow where it should search for the keys, if they are not in standard location and not passphrase protected. The easiest thing is by specifying -iswitch directly to ssh:

ssh如果密钥不在标准位置且不受密码保护,您需要知道应该在哪里搜索密钥。最简单的方法是-i直接指定switch 到ssh

/usr/bin/ssh -i /path/to/key -N -R 1234:localhost:22 [email protected] -p 22

Or cleaner way in your ~/.ssh/configlike this:

或者~/.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.

但请确保脚本与您的用户上下文一起运行,因此脚本将看到配置文件。

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 -Lbefore starting the script. ssh-agentalso solve the problem, if he keys are passphrase protected.

如果您在标准位置 ( ~/.ssh/id_rsa)有密钥,您的代码应该可以正常工作。尽管如果您将密钥存储在 中它应该可以工作ssh-agent,您可以ssh-add -L在启动脚本之前验证使用它。ssh-agent如果他的密钥受密码保护,也可以解决问题。