1. 程式人生 > >ssh免密登陸

ssh免密登陸

ssh

ssh免密登陸

ssh無密碼登錄要使用公鑰與私鑰。linux下可以用用ssh-keygen生成公鑰/私鑰對,下面我以CentOS為例。

系統:CentOS7
主機:A(192.168.66.100);B(192.168.66.110)
為方面,用戶都為root

1、在A下生成公鑰/私鑰對
命令:
ssh-keygen -t rsa -P ‘’
-P表示密碼,-P ‘‘ 就表示空密碼,也可以不用-P參數,這樣就要三車回車,用-P就一次回車。
它在/root下生成.ssh目錄,其他用戶的話在對應的家目錄下(/home/用戶名),.ssh下有id_rsa和id_rsa.pub。

2、將把A機下的id_rsa.pub復制到B機下,在B機的.ssh/authorized_keys文件裏。

方式一:
ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
方式二:
使用scp將文件復制過去
scp .ssh/id_rsa.pub [email protected]:/root/id_rsa.pub
回車後輸入B的root密碼
[email protected] password:
id_rsa.pub 100% 223 0.2KB/s 00:00

3、B機把從A機復制的id_rsa.pub添加到.ssh/authorzied_keys文件裏。
[[email protected] ~]# cat id_rsa.pub >> .ssh/authorized_keys
[[email protected] ~]# cat id_rsa.pub >> .ssh/authorized_keys
authorized_keys的權限要是600。
[[email protected] ~]# chmod 600 .ssh/authorized_keys

4、A機登陸B機
[[email protected] ~]# ssh [email protected]
/* */
The authenticity of host ‘192.168.66.110 (192.168.66.110)‘ can‘t be established.
RSA key fingerprint is 00:a6:a8:87:eb:c7:40:10:39:cc:a0:eb:50:d9:6a:5b.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ‘192.168.66.110‘ (RSA) to the list of known hosts.
Last login: Thu Jul 3 09:53:18 2017 from root
[[email protected] ~]#
第一次登錄是時要你輸入yes。

5、現在A機可以無密碼登錄B機了。

小結:登錄的機子可有私鑰,被登錄的機子要有登錄機子的公鑰。這個公鑰/私鑰對一般在私鑰宿主機產生。上面是用rsa算法的公鑰/私鑰對,當然也可以用dsa(對應的文件是id_dsa,id_dsa.pub)

註意一:
CentOS默認公鑰登陸關閉狀態需要開啟
修改配置文件:/etc/ssh/sshd_conf
命令:
vim /etc/ssh/sshd_conf
找到下面兩行註釋將前面的#去掉並將後面的no改為yes
RSAAuthentication yes
PubkeyAuthentication yes
重啟sshd服務:
systemctl restart sshd

註意二:
SSH出現 The authenticity of host xxx can‘t be established.
使用ssh連接遠程主機時加上“-o StrictHostKeyChecking=no”的選項,去掉對主機的驗證檢查。
ssh -o StrictHostKeyChecking=no 主機地址

問題一:上述操作完成後免密登陸失敗時,查看配置文件/etc/ssh/sshd_conf
命令:
vim /etc/ssh/sshd_conf
在配置文件中修改:
嚴苛模式:
StrictModes no

:wq保存退出
重啟sshd服務:
systemctl restart sshd

問題二:如果遇到權限不夠,無法修改讀取authorzied_keys文件中的內容
修改.ssh文件夾的權限為777
chmod -R 777 ~/.ssh

問題三:
SSH出現Agent admintted fauiler to sign using password!
使用 ssh-agent bash
ssh-add ~/.ssh/id_rsa

ssh免密登陸