在Linux系统运维中,我们可能会遇到这样的问题:当我们用客户端PUTTY利用key验证分别登录到主机A,主机B,主机C的时候,都不用输入密码,直接由key验证可以成功登录,那么我想从主机A登录到主机B,再从主机B登录到主机C的时候,要怎么做才能实现直接用key验证,而不用被要求输入密码呢?

这个时候我们需要在主机A和PUTTY上开启key转发功能,见下图:

213922785.png

钥匙生成和分发


1.在主机A上生成密钥对


[root@ws128 ~]# ssh-keygen(默认算法为RSA,2048位)

Generating public/privatersa key pair.

Enter file in which tosave the key (/root/.ssh/id_rsa):

Enter passphrase (emptyfor no passphrase):(输入私钥密码)

Enter same passphraseagain:

Your identification hasbeen saved in /root/.ssh/id_rsa.

Your public key has beensaved in /root/.ssh/id_rsa.pub.

The key fingerprint is:

c7:67:a8:4e:1b:e6:a2:43:ef:59:a0:10:48:67:f8:f2root@ws128.example.com


2.将生成的公钥分别安装到主机B、主机C上

[root@ws128 ~]# ssh-copy-id -i .ssh/id_rsa.pubroot@192.168.80.129

[root@ws128 ~]# ssh-copy-id -i .ssh/id_rsa.pub root@192.168.80.130


3.将私钥文件拷贝到终端,由于Linux的ssh-keygen生成的私钥文件PUTTY不识别,所以要用pttygen软件做一次转换,打开puttygen软件导入私钥,然后另存为PPK格式。

214321542.png


私钥转发配置


1.PUTTY配置,开启私钥转发,指定私钥文件,如图:

214544564.png

2.在主机A上开启SSH代理

[root@ws128 .ssh]# eval`ssh-agent`

Agent pid 3850

[root@ws128 .ssh]# ssh-add

Enter passphrase for/root/.ssh/id_rsa:

Identity added: /root/.ssh/id_rsa(/root/.ssh/id_rsa)

脚本实现

Vim /root/sshagent.sh

#!/usr/bin/expect

spawn ssh-add

expect "passphrase"

send "redhat\r"

expect eof

exit

Vim /root/.bashrc

Eval `ssh-agent`

/root/sshagent.sh



3.在主机A上设置SSH代理转发

[root@ws128 .ssh]# vim /etc/ssh/ssh_config

ForwardAgent yes

ForwardX11 yes


验证

1.在主机A上用SSH登录到主机B,然后在主机B上看能不能不用密码直接登录到主机C,如果可以,则配置成功。