每次登陸linux時須要輸入一大串密碼(有時還會等很長時間才能輸入密碼,文章最後有解決方法),密碼設的過短,安全性不高,長了很難記憶而且輸入麻煩。
使用密鑰登陸,不只能夠省去了密碼輸入的步驟,並且提升了服務器的安全性。linux
(本文永久地址:http://woymk.blog.51cto.com/10000269/1919130)安全
1. 產生密鑰服務器
執行ssh-keygen -t rsadom
[root@xxx ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): <==設置密鑰名字,用默認名直接回車
Enter passphrase (empty for no passphrase): <==設置密鑰的密碼,空爲不設置
Enter same passphrase again: <==再輸入一遍密鑰的密碼
Your identification has been saved in /root/.ssh/id_rsa.<== 私鑰
Your public key has been saved in /root/.ssh/id_rsa.pub.<== 公鑰
The key fingerprint is:
27:d9:f9:a1:c2:d0:c7:39:86:0f:58:53:ae:64:c7:f5 root@xxx
The key's randomart p_w_picpath is:
+--[ RSA 2048]----+
| . . |
| + . . |
| = + E |
| * O o |
| o S X . |
| o B + . |
| o o . |
| . |
| |
+-----------------+
ssh
2. 把密鑰複製到遠程主機ide
1) 使用ssh-copy-id命令複製3d
執行ssh-copy-id -i .ssh/id_rsa.pub root@遠程主機名或iprest
[root@xxx ~]# ssh-copy-id -i .ssh/id_rsa.pub root@192.168.1.2
The authenticity of host '192.168.1.2 (192.168.1.2)' can't be established.
RSA key fingerprint is 68:94:ee:45:f8:58:6f:1c:e9:c6:4c:5b:11:bc:50:e6.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.2' (RSA) to the list of known hosts.
root@192.168.1.2's password:
Now try logging into the machine, with "ssh 'root@192.168.1.2'", and check in:blog
.ssh/authorized_keysip
to make sure we haven't added extra keys that you weren't expecting.
ssh-copy-id會對遠程主機用戶家目錄中的.ssh, 和.ssh/authorized_keys自動設置合適的權限。
2) 使用scp命令複製
也能夠用scp命令把文件id_rsa.pub複製到遠程主機,須要設置相應文件和目錄權限
在遠程主機上執行
cd ~
mkdir .ssh
chmod 700 .ssh
cd .ssh
scp root@192.168.1.1:~/.ssh/id_rsa.pub authorized_keys
chmod 600 authorized_keys
3. 登陸遠程主機
1) 直接登陸遠程主機
執行ssh 192.168.1.2
[root@xxx ~]# ssh 192.168.1.2
Last login: Sun Apr 23 17:03:39 2017 from 192.168.1.1
[root@xxx2 ~]#
2) 使用putty登錄遠程主機
運行puttygen
點[Load]打開私鑰文件id_rsa
點[Save private key]保存
運行putty,輸入遠程主機ip
點左邊樹形菜單中的[SSH->Auth],輸入剛剛保存的私鑰文件
點樹形菜單中的[Connection->Data],輸入登錄遠程主機的用戶名root
點樹形菜單中的[Session],在Host Name(or IP address)下面的空白處填上遠程主機的ip和端口號,
在Saved Sessions裏給遠程主機起個名字,點[Save]保存一下,方便下次使用。
最後點[Open]就能夠登錄了。
4. 關閉密碼驗證登陸
關閉密碼驗證後,將沒法使用密碼登錄,大大提升了服務器的安全性
在遠程服務器上操做:
vi /etc/ssh/sshd_config
找到PasswordAuthentication將其值改成no
PasswordAuthentication no
保存後重啓ssh服務
service sshd restart
ssh登錄很慢的解決辦法:
只要在sshd_config中修改兩個參數便可
vi /etc/ssh/sshd_config
1. 禁用DNS反向解析
找到
UseDNS
改爲
UseDNS no
2. 禁用基於GSSAPI的用戶認證
服務器端啓用了GSSAPI,登錄的時候客戶端須要對服務器端的IP地址進行反解析,若是服務器的IP地址沒有配置PTR記錄,那麼就容易在這裏卡住了。
找到GSSAPIAuthentication
改爲
GSSAPIAuthentication no
保存後重啓ssh服務service sshd restart