暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

多台Linux主机一键配置SSH互信

原创 键盘丐 2022-08-19
2341

概述

    在多台Linux主机上配置ssh互信步骤很繁琐,而且还要注意认证文件的权限,本文主要记录编写shell脚本,在其中一台主机上使用root用户执行,配置多台主机新建账号的互信。

环境准备

    将在4台CentOS 7的机器上创建postgres用户,并且使用此用户配置ssh互信。此脚本的执行需要在执行机器上拥有expect包,yum安装过程如下,也可以单独下载rpm包进行安装。

[root@node2 ~]# yum install expect
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
Resolving Dependencies
--> Running transaction check
---> Package expect.x86_64 0:5.45-14.el7_1 will be installed
--> Processing Dependency: libtcl8.5.so()(64bit) for package: expect-5.45-14.el7_1.x86_64
--> Running transaction check
---> Package tcl.x86_64 1:8.5.13-8.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=========================================================================================================================================================================================================
 Package                                        Arch                                           Version                                                Repository                                    Size
=========================================================================================================================================================================================================
Installing:
 expect                                         x86_64                                         5.45-14.el7_1                                          base                                         262 k
Installing for dependencies:
 tcl                                            x86_64                                         1:8.5.13-8.el7                                         base                                         1.9 M

Transaction Summary
=========================================================================================================================================================================================================
Install  1 Package (+1 Dependent package)

Total download size: 2.1 M
Installed size: 4.9 M
Is this ok [y/d/N]: y
Downloading packages:
(1/2): expect-5.45-14.el7_1.x86_64.rpm                                                                                                                                            | 262 kB  00:00:00     
(2/2): tcl-8.5.13-8.el7.x86_64.rpm                                                                                                                                                | 1.9 MB  00:00:00     
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                                    5.1 MB/s | 2.1 MB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : 1:tcl-8.5.13-8.el7.x86_64                                                                                                                                                             1/2 
  Installing : expect-5.45-14.el7_1.x86_64                                                                                                                                                           2/2 
  Verifying  : 1:tcl-8.5.13-8.el7.x86_64                                                                                                                                                             1/2 
  Verifying  : expect-5.45-14.el7_1.x86_64                                                                                                                                                           2/2 

Installed:
  expect.x86_64 0:5.45-14.el7_1                                                                                                                                                                          

Dependency Installed:
  tcl.x86_64 1:8.5.13-8.el7                                                                                                                                                                              

Complete!

脚本内容

    如下内容是配置互信脚本deployTrushSSH.sh的具体内容:

##############################################################################################################
##Author:键盘丐(deitylee)                                                                                  #
##Date:2022-08-03创建                                                                                        #
##FileName:deployTrustSSH.sh                                                                                 #
##使用方法:#
##1.在执行主机上需要安装expect插件                                                                           #                 
##2.修改ipArray,可以把所有主机IP放在数组中                                                                  #
##3.修改userName,为你需要创建和配置互信的操作系统账号                                                       #
##4.保持所有主机root密码一致,并修改rootPasswd值为root密码                                                   #
##############################################################################################################

#!/bin/bash
#定义变量
#设置需要配置的主机IP及主机名数组顺序相互对应
ipArray=("192.168.59.27" "192.168.59.28" "192.168.59.29" "192.168.59.32")  #IP数组
userName=postgres      #需创建的操作系统账号,并使用此账户配置互信
rootPasswd=111111      #主机root密码,所有主机root密码保持一致
#判断是否使用root用户执行脚本
if [ $UID -ne 0 ];
then
    echo "请使用root用户执行此脚本!"
    exit 5
fi

#循环先删除用户,再创建,并每台生产私钥公钥
for ((i=0;i<${#ipArray[*]};i++))
do
expect <<-EOF
    spawn ssh root@${ipArray[i]} userdel -r $userName  
    expect {
        "Are you sure you want to continue connecting (yes/no)?" { send "yes\n";exp_continue }
        "root@${ipArray[i]}'s password:" { send "$rootPasswd\n" }
    }
    spawn ssh root@${ipArray[i]} useradd $userName
    expect {
        "Are you sure you want to continue connecting (yes/no)?" { send "yes\n";exp_continue }
        "root@${ipArray[i]}'s password:" { send "$rootPasswd\n" }
    }
    spawn ssh root@${ipArray[i]} "echo '$userName' | passwd $userName --stdin"
    expect {
        "Are you sure you want to continue connecting (yes/no)?" { send "yes\n";exp_continue }
        "root@${ipArray[i]}'s password:" { send "$rootPasswd\n";exp_continue }
    }
    spawn ssh $userName@${ipArray[i]} "ssh-keygen -t rsa"
    expect {
        "$userName@${ipArray[i]}'s password:" { send "$userName\n";exp_continue }
        "Enter file in which to save the key (/home/$userName/.ssh/id_rsa):" {send "\n";exp_continue}
        "Enter passphrase (empty for no passphrase):" {send "\n";exp_continue}
        "Enter same passphrase again:" {send "\n";exp_continue}
    } 
  spawn scp $userName@${ipArray[i]}:/home/$userName/.ssh/id_rsa.pub /home/$userName/.ssh/id_rsa.pub.${ipArray[i]}
      expect {
        "yes/no" { send "yes\n";exp_continue }
        "password:" { send "$userName\n" }
    } 
expect eof
EOF
su - postgres <<AAAA
cat /home/$userName/.ssh/id_rsa.pub.${ipArray[i]} >> /home/$userName/.ssh/authorized_keys
rm -f /home/$userName/.ssh/id_rsa.pub.${ipArray[i]}
AAAA
done

#把每台的公钥复制到执行主机,并全部写入认证文件,修改认证文件权限为600 
for ((i=0;i<${#ipArray[*]};i++))
do
expect <<-EOF
  spawn scp /home/$userName/.ssh/authorized_keys $userName@${ipArray[i]}:/home/$userName/.ssh/authorized_keys
    expect {
        "yes/no" { send "yes\n";exp_continue }
        "password:" { send "$userName\n";exp_continue }
    }
  spawn ssh $userName@${ipArray[i]} "chmod 600 /home/$userName/.ssh/authorized_keys"
  expect {
        "yes/no" { send "yes\n";exp_continue }
        "password:" { send "$userName\n" }
    } 
expect eof
EOF
done

#在$userName账号下生成known_hosts文件
for ((i=0;i<${#ipArray[*]};i++))
do
su - $userName <<BBBB
expect <<-EOF
    spawn ssh ${ipArray[i]} exit
    expect {
           "yes/no" { send "yes\n" }
    } 
    expect eof
EOF
BBBB
done

###分发known_hosts文件
for ((i=0;i<${#ipArray[*]};i++))
do
su - $userName <<CCCC
scp /home/$userName/.ssh/known_hosts $userName@${ipArray[i]}:/home/$userName/.ssh/known_hosts
CCCC
done

脚本执行输出

[root@node2 tmp]# sh deployTrustSSH.sh 
spawn ssh root@192.168.59.27 userdel -r postgres
root@192.168.59.27's password: spawn ssh root@192.168.59.27 useradd postgres
root@192.168.59.27's password: spawn ssh root@192.168.59.27 echo 'postgres' | passwd postgres --stdin
root@192.168.59.27's password: 
Changing password for user postgres.
passwd: all authentication tokens updated successfully.
spawn ssh postgres@192.168.59.27 ssh-keygen -t rsa
postgres@192.168.59.27's password: 
Generating public/private rsa key pair.
Enter file in which to save the key (/home/postgres/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Created directory '/home/postgres/.ssh'.
Your identification has been saved in /home/postgres/.ssh/id_rsa.
Your public key has been saved in /home/postgres/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:llYhPlMnAIKG/zSwosUyWkt6N/7RoO0p6MfwTOHLd14 postgres@node2
The key's randomart image is:
+---[RSA 2048]----+
| . .. ..o.+ .    |
|. +  . . o +     |
| + o    + .      |
|+ B +    =       |
|oO = o. S        |
|+ + *o =         |
| . @.oo . E      |
|  . X..o..       |
| ... ++o.        |
+----[SHA256]-----+
spawn scp postgres@192.168.59.27:/home/postgres/.ssh/id_rsa.pub /home/postgres/.ssh/id_rsa.pub.192.168.59.27
postgres@192.168.59.27's password: 
id_rsa.pub                                                                                                                                                             100%  396    90.7KB/s   00:00    
Last failed login: Wed Aug  3 08:58:45 CST 2022 from node2 on ssh:notty
There were 45 failed login attempts since the last successful login.
spawn ssh root@192.168.59.28 userdel -r postgres
root@192.168.59.28's password: spawn ssh root@192.168.59.28 useradd postgres
root@192.168.59.28's password: spawn ssh root@192.168.59.28 echo 'postgres' | passwd postgres --stdin
root@192.168.59.28's password: 
Changing password for user postgres.
passwd: all authentication tokens updated successfully.
spawn ssh postgres@192.168.59.28 ssh-keygen -t rsa
postgres@192.168.59.28's password: 
Generating public/private rsa key pair.
Enter file in which to save the key (/home/postgres/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Created directory '/home/postgres/.ssh'.
Your identification has been saved in /home/postgres/.ssh/id_rsa.
Your public key has been saved in /home/postgres/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:uhQK1yyWwfTzN4mjitqHMFwuLAOT+TXPYo/EbmHnEbs postgres@node3
The key's randomart image is:
+---[RSA 2048]----+
|    .            |
|   o .           |
| o  o o          |
|=  .o=.o . .     |
|+o+o=++oS +      |
|=+.=Bo*+ o .     |
|.+.*.B+o         |
| ...=oE.         |
|..oo. .          |
+----[SHA256]-----+
spawn scp postgres@192.168.59.28:/home/postgres/.ssh/id_rsa.pub /home/postgres/.ssh/id_rsa.pub.192.168.59.28
postgres@192.168.59.28's password: 
id_rsa.pub                                                                                                                                                             100%  396   385.6KB/s   00:00    
Last login: Wed Aug  3 09:39:37 CST 2022
spawn ssh root@192.168.59.29 userdel -r postgres
root@192.168.59.29's password: spawn ssh root@192.168.59.29 useradd postgres
root@192.168.59.29's password: spawn ssh root@192.168.59.29 echo 'postgres' | passwd postgres --stdin
root@192.168.59.29's password: 
Changing password for user postgres.
passwd: all authentication tokens updated successfully.
spawn ssh postgres@192.168.59.29 ssh-keygen -t rsa
postgres@192.168.59.29's password: 
Generating public/private rsa key pair.
Enter file in which to save the key (/home/postgres/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Created directory '/home/postgres/.ssh'.
Your identification has been saved in /home/postgres/.ssh/id_rsa.
Your public key has been saved in /home/postgres/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:IimZwTBQBdRZsf9bA1ewTe5IidcWvlIL98w0lDnPAuI postgres@node4
The key's randomart image is:
+---[RSA 2048]----+
|=o++.oo.    . o.o|
| +  o  .  ...X.= |
|  o   .  ...*.Xo+|
|   + . .  Eo O.B+|
|  + o . S . + +.+|
|   . . . . o .   |
|          . o    |
|           o .   |
|          .      |
+----[SHA256]-----+
spawn scp postgres@192.168.59.29:/home/postgres/.ssh/id_rsa.pub /home/postgres/.ssh/id_rsa.pub.192.168.59.29
postgres@192.168.59.29's password: 
id_rsa.pub                                                                                                                                                             100%  396   318.6KB/s   00:00    
Last login: Wed Aug  3 09:39:38 CST 2022
spawn ssh root@192.168.59.32 userdel -r postgres
root@192.168.59.32's password: spawn ssh root@192.168.59.32 useradd postgres
root@192.168.59.32's password: spawn ssh root@192.168.59.32 echo 'postgres' | passwd postgres --stdin
root@192.168.59.32's password: 
Changing password for user postgres.
passwd: all authentication tokens updated successfully.
spawn ssh postgres@192.168.59.32 ssh-keygen -t rsa
postgres@192.168.59.32's password: 
Generating public/private rsa key pair.
Enter file in which to save the key (/home/postgres/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Created directory '/home/postgres/.ssh'.
Your identification has been saved in /home/postgres/.ssh/id_rsa.
Your public key has been saved in /home/postgres/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:v2XOkcGFbscc/SsNRIWJW3TLP1Qqjhr6ofIMNkTQ434 postgres@node5
The key's randomart image is:
+---[RSA 2048]----+
|  ..        oo+o.|
|   .o      ..=ooo|
|   ...      =.++.|
|   ..      *.=..o|
|   ..   S . *.+.o|
|   .. E. + . +o o|
|    +.. o . =. o |
|   ..+ o . * ..  |
|     o+ . . o    |
+----[SHA256]-----+
spawn scp postgres@192.168.59.32:/home/postgres/.ssh/id_rsa.pub /home/postgres/.ssh/id_rsa.pub.192.168.59.32
postgres@192.168.59.32's password: 
id_rsa.pub                                                                                                                                                             100%  396   368.8KB/s   00:00    
Last login: Wed Aug  3 09:39:38 CST 2022
spawn scp /home/postgres/.ssh/authorized_keys postgres@192.168.59.27:/home/postgres/.ssh/authorized_keys
postgres@192.168.59.27's password: 
authorized_keys                                                                                                                                                        100% 1584     2.0MB/s   00:00    
spawn ssh postgres@192.168.59.27 chmod 600 /home/postgres/.ssh/authorized_keys
postgres@192.168.59.27's password: 
spawn scp /home/postgres/.ssh/authorized_keys postgres@192.168.59.28:/home/postgres/.ssh/authorized_keys
postgres@192.168.59.28's password: 
authorized_keys                                                                                                                                                        100% 1584   870.5KB/s   00:00    
spawn ssh postgres@192.168.59.28 chmod 600 /home/postgres/.ssh/authorized_keys
postgres@192.168.59.28's password: 
spawn scp /home/postgres/.ssh/authorized_keys postgres@192.168.59.29:/home/postgres/.ssh/authorized_keys
postgres@192.168.59.29's password: 
authorized_keys                                                                                                                                                        100% 1584     1.4MB/s   00:00    
spawn ssh postgres@192.168.59.29 chmod 600 /home/postgres/.ssh/authorized_keys
postgres@192.168.59.29's password: 
spawn scp /home/postgres/.ssh/authorized_keys postgres@192.168.59.32:/home/postgres/.ssh/authorized_keys
postgres@192.168.59.32's password: 
authorized_keys                                                                                                                                                        100% 1584     1.1MB/s   00:00    
spawn ssh postgres@192.168.59.32 chmod 600 /home/postgres/.ssh/authorized_keys
postgres@192.168.59.32's password: 
Last login: Wed Aug  3 09:39:40 CST 2022
spawn ssh 192.168.59.27 exit
The authenticity of host '192.168.59.27 (192.168.59.27)' can't be established.
ECDSA key fingerprint is SHA256:utPCyUbj1X7yjN1r7emBpsim/PO2aREYDN71V1m/Srw.
ECDSA key fingerprint is MD5:ca:bf:c1:e4:5d:df:bc:13:d9:cb:63:f9:c0:52:41:c3.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.59.27' (ECDSA) to the list of known hosts.
Last login: Wed Aug  3 09:39:41 CST 2022
spawn ssh 192.168.59.28 exit
The authenticity of host '192.168.59.28 (192.168.59.28)' can't be established.
ECDSA key fingerprint is SHA256:utPCyUbj1X7yjN1r7emBpsim/PO2aREYDN71V1m/Srw.
ECDSA key fingerprint is MD5:ca:bf:c1:e4:5d:df:bc:13:d9:cb:63:f9:c0:52:41:c3.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.59.28' (ECDSA) to the list of known hosts.
Last login: Wed Aug  3 09:39:41 CST 2022
spawn ssh 192.168.59.29 exit
The authenticity of host '192.168.59.29 (192.168.59.29)' can't be established.
ECDSA key fingerprint is SHA256:utPCyUbj1X7yjN1r7emBpsim/PO2aREYDN71V1m/Srw.
ECDSA key fingerprint is MD5:ca:bf:c1:e4:5d:df:bc:13:d9:cb:63:f9:c0:52:41:c3.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.59.29' (ECDSA) to the list of known hosts.
Last login: Wed Aug  3 09:39:42 CST 2022
spawn ssh 192.168.59.32 exit
The authenticity of host '192.168.59.32 (192.168.59.32)' can't be established.
ECDSA key fingerprint is SHA256:utPCyUbj1X7yjN1r7emBpsim/PO2aREYDN71V1m/Srw.
ECDSA key fingerprint is MD5:ca:bf:c1:e4:5d:df:bc:13:d9:cb:63:f9:c0:52:41:c3.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.59.32' (ECDSA) to the list of known hosts.
Last login: Wed Aug  3 09:39:42 CST 2022
known_hosts                                                                                                                                                            100%  700   635.4KB/s   00:00    
Last login: Wed Aug  3 09:39:42 CST 2022
known_hosts                                                                                                                                                            100%  700   181.6KB/s   00:00    
Last login: Wed Aug  3 09:39:42 CST 2022
known_hosts                                                                                                                                                            100%  700   759.2KB/s   00:00    
Last login: Wed Aug  3 09:39:42 CST 2022
known_hosts                                                                                                                                                            100%  700   578.6KB/s   00:00    
[root@node2 tmp]#

验证互信

    在执行机器上验证登录

[root@node2 tmp]# su - postgres
Last login: Wed Aug  3 09:39:43 CST 2022
[postgres@node2 ~]$ ssh 192.168.59.27
Last login: Wed Aug  3 09:40:45 2022
[postgres@node2 ~]$ exit
logout
Connection to 192.168.59.27 closed.
[postgres@node2 ~]$ ssh 192.168.59.28
Last failed login: Wed Aug  3 08:52:19 CST 2022 on pts/0
There were 41 failed login attempts since the last successful login.
[postgres@node3 ~]$ exit
logout
Connection to 192.168.59.28 closed.
[postgres@node2 ~]$ ssh 192.168.59.29
Last failed login: Tue Aug  2 15:16:33 CST 2022 from 192.168.59.27 on ssh:notty
There were 37 failed login attempts since the last successful login.
[postgres@node4 ~]$ exit
logout
Connection to 192.168.59.29 closed.

    在另一台上验证登录

[root@node3 ~]# su - postgres
Last login: Wed Aug  3 09:40:59 CST 2022 from 192.168.59.27 on pts/1
[postgres@node3 ~]$ ssh 192.168.59.27
Last login: Wed Aug  3 09:40:54 2022 from node2
[postgres@node2 ~]$ exit
logout
Connection to 192.168.59.27 closed.
[postgres@node3 ~]$ ssh 192.168.59.32
Last failed login: Wed Aug  3 08:44:58 CST 2022 from node2 on ssh:notty
There were 112 failed login attempts since the last successful login.

总结

    deployTrushSSH.sh脚本需要root用户执行,一次执行可以根据配置在多台主机上创建新用户,并在此用户下配置ssh互信,脚本的输出可以根据自己需求修改,如有更简洁实现方法,请大家指教!




「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论