SSH批量管理项-跳过确定、指定密码创建与分发密钥
P:可对远端服务器执行命令
前言
ssh秘钥认证+脚本批量管理,特点:简单、实用,但需要人工写脚本,类似实时复制的inotify工具。
2013以前这种方式很普遍,现在也在用。
MySQL高可用MHA集群,要求所有机器互相秘钥认证。大数据集群也需要。
一、基础
1.ssh-keygen
非交互式创建秘钥对
具体命令:ssh-keygen -f ~/.ssh/id_rsa -P '' -q
参数讲解:
(ssh-keygen --help查看)
ssh-keygen:密钥对创建工具
[-P old_passphrase] 密码
[-f output_keyfile] 输出的秘钥文件
[-q] 不输出信息
[-t dsa ] 指定秘钥类型。
2.ssh-copy-id
不需要提示yes/no分发秘钥
具体命令:ssh-copy-id -f -i ~/.ssh/id_rsa.pub -o StrictHostKeyChecking=no 172.16.1.8
参数讲解:
ssh-copy-id -f -i ~/.ssh/id_rsa.pub -o StrictHostKeyChecking=no root@172.16.1.8
ssh-copy-id [-f] [-i [identity_file]] [-p port] [[-o <ssh -o options>] ...] [user@]hostname
c参数说明:
-f: force mode 强制
[-i [identity_file]] 指定秘钥文件
[[-o <ssh -o options>] ...] 指定ssh参数选项。
3.sshpass工具命令介绍
指定密码非人工交互分发秘钥
(指定密码连接其他服务器执行命令的工具)
(sshpass -help 查看参数)
安装:yum install sshpass -y
sshpass -p123456 ssh-copy-id -f -i ~/.ssh/id_rsa.pub "-o StrictHostKeyChecking=no" 172.16.1.7
[root@web02 ~]# sshpass -help
Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters
sshpass -p123456 ssh-copy-id -f -i ~/.ssh/id_rsa.pub "-o StrictHostKeyChecking=no" 172.16.1.7
sshpass [-f|-d|-p|-e] [-hV] command parameters
参数讲解:
-p password Provide password as argument (security unwise) #指定用户密码操作
二、实践
1.一键配置实践
把web02(10.0.0.8)作为分发服务器:
web02(8)-->m01(61)
web02(8)-->web01(7)
命令介绍:
#创建密钥
ssh-keygen -f ~/.ssh/id_rsa -P '' -q
#不用输入yes分发密钥
ssh-copy-id -f -i ~/.ssh/id_rsa.pub "-o StrictHostKeyChecking=no" 172.16.1.7
#不用输入密码分发密钥(指定)
sshpass -p123456 ssh-copy-id -f -i ~/.ssh/id_rsa.pub "-o StrictHostKeyChecking=no" 172.16.1.7
脚本实现:
#!/bin/bash
#yum install sshpass -y
ssh-keygen -f ~/.ssh/id_rsa -P '' -q
for ip in 7 61
do
sshpass -p123456 ssh-copy-id -f -i ~/.ssh/id_rsa.pub "-o StrictHostKeyChecking=no" 172.16.1.$ip
done
#脚本命令内容可以直接复制在命令行执行,出现两个“Number of key(s) added: 1”成功
#test测试,在web02执行以下两条命令
#对远端服务器执行命令
ssh 172.16.1.7 "ifconfig eth0"
ssh 172.16.1.61 "ifconfig eth0"