linux ssh 密钥认证自动登录

简单讲就是先生成一套公钥--私钥,私钥自己拿着,公钥的内容添加到服务器上对应账号的.ssh/authorized_keys文件中。

 【服务端配置】

先配置Server,打开公钥认证。用root用户执行:

vim /etc/ssh/ssh_config

将以下两行配置打开注释:

RSAAuthentication yes

IdentityFile ~/.ssh/id_rsa

然后重启ssh服务:/etc/init.d/sshd restart

 

【客户端生成密钥】

假设要实现user0无密码登录remotehost,则先用user0登录客户端,然后执行ssh-keygen -t rsa

Generating public/private rsa key pair.

Enter file in which to save the key (/home/user0/.ssh/id_rsa):(缺省将公钥和私钥保存在当前登录用户的.ssh目录下,id_rsa是私钥,id_rsa.pub是公钥)

Created directory '/home/user0/.ssh'.

Enter passphrase (empty for no passphrase):(这里输入使用私钥时的密码,如果设置了密码则每次登录需要输入该密码,要实现无密码登录就不能设置此密码。但是如果不设置密码,私钥被非法拷贝以后就可以直接登录)

Enter same passphrase again:(重复输入一次密码)

Your identification has been saved in /home/user0/.ssh/id_rsa.

Your public key has been saved in /home/user0/.ssh/id_rsa.pub.

The key fingerprint is:

f1:e8:ae:a7:b3:f6:64:3f:30:34:1f:c5:07:ce:0f:bc myid@localhost

The key's randomart image is:

+--[ RSA 2048]----+

|   .o..          |

|   .   .         |

|  .   .          |

|   . . .         |

|    o = S        |

|     = +    o    |

|      . .  o...  |

|         .o o=.  |

|         .E*==.  |

+-----------------+

注意:如果passphrase为空,生成的私钥必须绝对禁止未授权的访问!

然后把私钥拷贝到客户端的~/.ssh目录下(可以使用其他账号),可以重命名。

 

【把公钥传到服务器上】

将客户端/home/user0/.ssh/id_rsa.pub拷贝到服务器的/home/user0/.ssh目录,并重命名为authorized_keys文件,注意设为其他人不可读写。

chmod 400 /home/user0/.ssh/id_rsa.pub

scp /home/user0/.ssh/id_rsa.pub user0@remotehost:/home/user0/.ssh/authorized_keys

如果服务器上authorized_keys文件已经存在,则添加到末尾:

$cat .ssh/id_rsa.pub >> ~/.ssh/authorized_keys

【使用私钥登录】

用ssh -i 选项指定私钥文件就可以使用密码登录了,此时要输入使用私钥的密码(不是服务端的账号密码)。

$ssh -i .ssh/id_rsa_50_72 [email protected]  (id_rsa_50_72是已经重命名的私钥文件,10.13.50.72是服务器IP)

Enter passphrase for key '.ssh/id_rsa_50_72': (输入使用私钥时的密码)

Last login: Wed Apr  9 16:13:23 2014 from 10.25.204.50(登录成功)

每次敲命令,都要指定私钥,是一个很繁琐的事情,所以我们可以把私钥的路径加入ssh客户端的默认配置里

修改/etc/ssh/ssh_config

#其实默认id_rsa就已经加入私钥的路径了,这里只是示例而已

IdentityFile ~/.ssh/id_rsa

#如果有其他的私钥,还要再加入其他私钥的路径

 IdentityFile ~/.ssh/blue_rsa

猜你喜欢

转载自samjavaeye.iteye.com/blog/1717432