运维之道 | SSH 自动化集群管理、自动化脚本管理

一、主机规划

主机 IP
管理主机 192.168.182.10
被管理主机 - 1 192.168.182.11
被管理主机 - 2 192.168.182.12

二、SSH 集群管理

1、使用ssh命令,查询被管理主机当前时间(需要手动输入密码
[root@localhost ~]# ssh -l root 192.168.182.11 date
root@192.168.182.11's password: 
20200205日 星期三 19:19:01 CST

[root@localhost ~]# ssh -l root 192.168.182.12 date
root@192.168.182.12's password: 
20200205日 星期三 19:19:07 CST
2、生成ssh-keygen密钥,免密登录
  • 管理主机生成密钥对(ssh-keygen
[root@localhost ~]# 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:
SHA256:2oL59QLNUNyK/ylwHD0nvd5/YcJZH0PiXknnJqDm6IE root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
|       . .       |
|        o . .. o.|
|       o o o..+.o|
|      o o * o..*o|
|       BS= +o.+o+|
|     oEoO . .= o.|
|    o o=oo o .o .|
|     . o+.o . . .|
|      .  o.    .o|
+----[SHA256]-----+
  • 管理主机密钥对存放位置
[root@localhost ~]# cd /root/.ssh/
[root@localhost .ssh]# ls
id_rsa(私钥)  id_rsa.pub(公钥)  known_hosts
  • 将密钥发送至被控制主机
[root@localhost .ssh]# for i in {0,1,2}; do ssh-copy-id -i 192.168.1.1$i ; done
  • 被管理主机公钥存放位置
[root@test .ssh]# pwd
/root/.ssh
[root@test .ssh]# ls
authorized_keys(公钥密码)
  • 此时查询被管理主机不需要输入密码
[root@localhost ~]# ssh -l root 192.168.182.10 date
20200205日 星期三 19:39:33 CST
[root@localhost ~]# ssh -l root 192.168.182.11 date
20200205日 星期三 19:39:37 CST
[root@localhost ~]# ssh -l root 192.168.182.12 date 
20200205日 星期三 19:39:43 CST

3、使用ssh脚本集群管理
  • 编写被管理主机清单
[root@localhost ~]# cat ip_list.txt 
192.168.182.10
192.168.182.11
192.168.182.12
  • 编写ssh自动化集群管理脚本
[root@localhost ~]# vim auto_for_ssh.sh

#!/bin/bash
#auto remote exec command
############################

IP_FILES="/root/ip_list.txt"				///被管理主机清单文本
COMMAND="$*"								///命令行的命令

for IP in `cat $IP_FILES`					///抓取被管理主机清单文本中的IP地址
do
        echo -e "\033[32mThe $IP remote command follow results:\033[0m"  	///提示符
        ssh -l root $IP "$COMMAND"			///ssh命令执行集群管理
        echo 								///空行
done
  • 执行ssh自动化集群管理脚本 + 命令
[root@localhost ~]# sh auto_for_ssh.sh date
The 192.168.182.10 remote command follow results:
20200205日 星期三 19:53:18 CST

The 192.168.182.11 remote command follow results:
20200205日 星期三 19:53:18 CST

The 192.168.182.12 remote command follow results:
20200205日 星期三 19:53:19 CST
发布了118 篇原创文章 · 获赞 13 · 访问量 9398

猜你喜欢

转载自blog.csdn.net/VillianTsang/article/details/104187032