场景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.
可能有两个原因
- ssh-agent未启动或环境变量未设置
 
# 查看进程是否启动,环境变量是否正确
ps -ef |grep ssh-agent
echo $SSH_AUTH_SOCK
# 可可重新启动
ssh-agent -s
# 复制输出的结果,手工执行导出两个环境变量
 
- 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










