ssh通过跳板机免密登陆

场景1 (A没有C的密码)

  • A 可以免密登陆 B
  • B 可以免密登陆 C
  • A 不能免密登陆 C

需要:A通过B(跳板机)免密登陆C

方法参考https://serverfault.com/questions/337274/ssh-from-a-through-b-to-c-using-private-key-on-b

eval `ssh-agent -s`

# 两个user可以不同,分别能免密登陆即可
# 私钥文件不是默认路径,可以在ssh-add后指定
ssh -o ProxyCommand='ssh -T -q -o "ForwardAgent yes" user@hostB:portB "ssh-add -t 1 && nc %h %p"' user@hostC:portC

参数的解释:

  • ssh -T -q indicates that it should not allocate a pseudo-TTY (-T) and be quiet (-q);
  • once on the jump host B, we add the key to the SSH keys of A through ssh-add;
  • which only works because we forwarded the SSH agent using -o ‘ForwardAgent yes’.
  • ssh-add -t 1 indicates that I want the key to be added only for the 1 second needed to authenticate to the final host C;
  • and finally, nc %h %p initiates a netcat connection to the final host %h at port %p (both which will be filled out by SSH based on the information in the ~/.ssh/config file).

如果频繁使用,可以写入~/.ssh/config:

Host B
 User myusername
 HostName b.mycompany.com

Host C
 User myusername
 HostName c.intranet.mycompany.com
 ProxyCommand ssh -T -q -o 'ForwardAgent yes' B 'ssh-add -t 1 && nc %h %p'

可能遇到问题

Could not open a connection to your authentication agent.

可能有两个原因

  1. ssh-agent未启动或环境变量未设置
# 查看进程是否启动,环境变量是否正确
ps -ef |grep ssh-agent
echo $SSH_AUTH_SOCK

# 可可重新启动
ssh-agent -s
# 复制输出的结果,手工执行导出两个环境变量
  1. B上未开启AgentForwarding
# 开启sshd配置
vim /etc/ssh/sshd_config
 
AllowAgentForwarding yes
 
 
# 重启ssh
systemctl restart sshd

场景2 (A与C网络不直达)

  • A 可以免密登陆 B
  • B 与C网络可达,不需要免密登陆C
  • A 与C网络不可达
  • C 有A的公钥,即C的~/.ssh/authorized_keys里有A的id_rsa.pub

需要A通过B(跳板机)免密登陆C

直接执行

ssh -J user@hostB:portB user@hostC:portC
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值