OpenSSH 基於密鑰認證 跨多個主機密鑰共享

第一個主機:client.com (本地測試服務器,IP:172.16.100.1)算法

第二個主機:server1.com (生產環境服務器,IP:172.16.100.2)vim

第三個主機:server2.com(生產環境服務器,IP:172.16.100.3)bash

 

背景:從一個主機(client.com)登陸多個主機(server1.com 或server2.com)時,每次都須要輸入密碼方可登陸。而且登陸成功其中一個主機(server1.com)以後再登陸另外一個主機(server2.com)時也須要輸入密碼。服務器

實現目標:從一個主機多個主機時不須要輸入密碼登陸而且登陸的主機中再次登陸另外一個主機時也不須要輸入密碼。ssh

實現步驟測試

操做系統:CentOS 7spa

開包包操作系統

# yum groupinstall "Development Tools"
# yum -y install tree

 

1. 在每一個主機上使用rsa算法生成密鑰對,即非堆成密鑰 id_rsa和id_rsa.pub,在三個服務器分別執行以下代碼:.net

[root@client.com ~]# ssh-keygen -t rsa
[root@client.com ~]# tree /root/.ssh
/root/.ssh
├── id_rsa
├── id_rsa.pub
└── known_hosts

 

[root@server1.com ~]# ssh-keygen -t rsa
[root@server1.com ~]# tree /root/.ssh
/root/.ssh
├── id_rsa
├── id_rsa.pub
└── known_hosts

 

[root@server2.com ~]# ssh-keygen -t rsa
[root@server2.com ~]# tree /root/.ssh
/root/.ssh
├── id_rsa
├── id_rsa.pub
└── known_hosts

 

2. 刪除server1.com和server2.com主機的id_rsa和id_rsa.pub兩個文件,保留.ssh目錄 代理

[root@server1.com ~]# rm -rf /root/.ssh/{id_rsa,id_rsa.pub}
[root@server2.com ~]# rm -rf /root/.ssh/{id_rsa,id_rsa.pub}

 

3. 在全部的服務器分別設置ForwardAgent轉向代理選項

[root@client.com ~]# vim /etc/ssh/ssh_config
Host *
  ForwardAgent yes 
[root@server1.com ~]# vim /etc/ssh/ssh_config
Host *
  ForwardAgent yes 
[root@server2.com ~]# vim /etc/ssh/ssh_config
Host *
  ForwardAgent yes 

4. client.com主機上覆制公鑰文件內容到server1.com和server2.com的主機的/root/.ssh/authorized_keys(文件權限600)

[root@client.com ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub -p 22 root@172.16.100.2

而後輸入172.16.100.2的root帳號密碼
[root@client.com ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub -p 22 root@172.16.100.3

而後輸入172.16.100.3的root帳號密碼

查看生成的文件

[root@server1.com ~]# ls -l /root/.ssh/
total 4
-rw------- 1 root root 400 Oct 14 00:57 authorized_keys
[root@server2.com ~]# ls -l /root/.ssh/
total 4
-rw------- 1 root root 400 Oct 14 00:57 authorized_keys

 

 5. client.com主機上ssh-agent密鑰管理器運行ssh-agent之後,使用ssh-add將私鑰交給ssh-agent保管

[root@client.com ~]# eval $(ssh-agent -s )
Agent pid 3526
[root@client.com ~]# ssh-add bash && ssh-add
Identity added: /root/.ssh/id_rsa (/root/.ssh/id_rsa)

注意:/etc/profile.d下建一個ssh-agent.sh文件:

[root@client.com ~]# vim /etc/profile.d/ssh-agent.sh
#!/bin/sh
if [ -f ~/.agent.env ]; then
    . ~/.agent.env >/dev/null
    if ! kill -0 $SSH_AGENT_PID >/dev/null 2>&1; then
        echo "Stale agent file found. Spawning new agent..."
        eval `ssh-agent |tee ~/.agent.env`
        ssh-add bash && ssh-add
    fi
else
    echo "Starting ssh-agent..."
    eval `ssh-agent |tee ~/.agent.env`
    ssh-add bash && ssh-add
fi

 6. 測試登陸

[root@client.com ~]# ssh 172.16.100.2
[root@server1.com ~]# ssh 172.16.100.3
[root@server2.com ~]# 
相關文章
相關標籤/搜索