next up previous contents
Next: sshpass 傳送密碼 Up: SSH Server Previous: 安全機制   Contents

SSH 免密碼登入

  1. 在定時備份或批次遠端處理,往往需要免密碼登入遠端主機工作。為達此目的,首先必須在 client 端產生一組 key,包含公開金鑰(Public Key)與私密金鑰(Private Key),將公鑰送到要登入的主機,相互對應做免密碼的登入。key 的產生:
    [root@kvm8 ~]# ssh-keygen 
    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:
    c3:e9:25:65:00:c8:65:cb:e8:fe:4e:7e:ce:06:a4:9d root@kvm8.deyu.wang
    The key's randomart image is:
    +--[ RSA 2048]----+
    |   . o+..        |
    |    o+ . .       |
    |    . o   o      |
    |   .  .. +       |
    |    .+ .S .      |
    |   .. E. +       |
    |    . ...        |
    |     + .o        |
    |     .++o        |
    +-----------------+
    
  2. 將公開金鑰放到要登入的主機
    [root@kvm8 ~]# scp .ssh/id_rsa.pub kvm7.deyu.wang:.ssh/
    The authenticity of host 'kvm7.deyu.wang (192.168.122.7)' can't be established.
    RSA key fingerprint is 33:76:31:62:25:dd:eb:a6:1f:5a:54:10:b8:25:c3:66.
    Are you sure you want to continue connecting (yes/no)? yes
    Warning: Permanently added 'kvm7.deyu.wang,192.168.122.7' (RSA) to the list of known hosts.
    root@kvm7.deyu.wang's password: 
    id_rsa.pub                                    100%  401     0.4KB/s   00:00  
    
  3. ssh 登入欲免密碼登入的主機,這時還是要密碼。
    [root@kvm8 ~]# ssh kvm7.deyu.wang
    root@kvm7.deyu.wang's password: 
    Last login: Tue Feb  4 19:31:13 2014 from 192.168.122.1
    
  4. 系統預設處理放置公鑰的檔案為 authorized_keys,所以必須把剛剛傳送過來的公鑰累加到這個檔案中:
    [root@kvm7 ~]# cat .ssh/id_rsa.pub >> .ssh/authorized_keys
    
  5. 特別注意目錄 .ssh 及檔案 authorized_keys 的權限,若群組或其他人的權限過大,除了安全性有問題外,也有可能因 ssh 判斷要對應的金鑰不安全,而無法對應,也就是不能免密碼登入。
    [root@kvm7 ~]# chmod 700 .ssh/
    [root@kvm7 ~]# chmod 644 .ssh/authorized_keys 
    [root@kvm7 ~]# ll -d .ssh 
    drwx------. 2 root root 4096 Feb  4 19:36 .ssh
    [root@kvm7 ~]# ll .ssh/authorized_keys 
    -rw-r--r--. 1 root root 401 Feb  4 19:36 .ssh/authorized_keys
    
  6. 退出 kvm7.deyu.wang 回到 kvm8.deyu.wang。
    [root@kvm7 ~]# exit
    logout
    Connection to kvm7.deyu.wang closed.
    
  7. 再次登入 kvm7.deyu.wang 已不需要密碼。
    [root@kvm8 ~]# ssh kvm7.deyu.wang
    Last login: Tue Feb  4 19:32:57 2014 from 192.168.122.1
    



2017-10-24