linuxssh/scp使用公钥认证方式登陆

比如想要在192.168.41.76服务器上, 不输入用户密码即以root用户登陆192.168.41.75服务器.
 
1) 192.168.41.76上创建公钥和私钥
[192.168.41.76]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (//.ssh/id_rsa): //直接回车, 默认位置.ssh/id_rsa
Enter passphrase (empty for no passphrase): //直接回车, 没有密码
Enter same passphrase again: //直接回车, 没有密码
Your identification has been saved in //.ssh/id_rsa.
Your public key has been saved in //.ssh/id_rsa.pub.
The key fingerprint is:
f3:66:3d:23:9f:cf:78:0b:f8:58:8f:3d:ee:ba:55:99 root@dw_test1
[192.168.41.76]# ll ~/.ssh
-rw-------   1 root root 883 Jun 30 14:25 id_rsa
-rw-r--r--   1 root root 221 Jun 30 14:25 id_rsa.pub
说明:
-t rsa表示SSH生成RSA类型的密钥, 这是默认的行为. 也可以执行生成DSA类型的密钥. 这时查看.ssh文件夹发现多了两个文件, id_rsa为私钥, id_rsa.pub为公钥.

 
 
2) 确认192.168.41.75上是否有~/.ssh目录, 没有则先建立
[192.168.41.75]# ll ~/.ssh
[192.168.41.75]# mkdir ~/.ssh

 
 
[192.168.41.76]# scp ~/.ssh/id_rsa.pub root@192.168.41.75:~/
root@192.168.41.75's password: //输入远程服务器root登录密码

 
 
4) 192.168.41.75上追加id_rsa.pub内容到相应用户下的~/.ssh/authorized_keys文件里, 并删除id_rsa.pub文件
[192.168.41.75]# cat ~/id_rsa.pub >> ~/.ssh/authorized_keys
[192.168.41.75]# rm -f id_rsa.pub

 
 
5) 这样在192.168.41.76上就可以不输入密码直接以root用户登陆192.168.41.75了, 也多了一个known_hosts文件
[192.168.41.76]# ssh 192.168.41.75
[192.168.41.76]# ll ~/.ssh
-rw-r--r--   1 root root 221 2009-06-30 14:25:32.000000000 +0800 id_rsa.pub
-rw-------   1 root root 883 2009-06-30 14:25:32.000000000 +0800 id_rsa
-rw-r--r--   1 root root 223 2009-06-30 14:30:26.000000000 +0800 known_hosts

 
 
6) 注意
.ssh目录的权限必须是0700, .ssh/authorized_keys文件权限必须是0600, 否则公钥认证不会生效. 如果想直接进入192.168.41.75的其他用户, 则需要将公钥追加到其他用户的authorized_keys文件里.