一、安装ansible 1.准备好repo源 从阿里云下载Centos的仓库源 wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo 从阿里云下载第三方epel源 (这里直接下载,未使用rpm -Uvh方式安装epel源) wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo 2.安装ansible yum -y install ansible

二、往远程机linux批量分发公钥 1.安装expect命令 公钥需要通过expect工具自动分发到被监管机上,由于centos7最小化安装没有自带expect命令,用下面命令安装: yum -y install expect 2.批量自动分发公钥到被监管机的脚本(不需要手动输入密码):

#!/bin/bash
#注:此脚本可能只适用于centos系统,其他可能不适用,因为scp的提示信息可能不一样
export password=123
#rm -rf /root/.ssh/known_hosts

function pub_key () {
#创建.ssh目录,有些系统可能没有.ssh目录
/usr/bin/expect -c "
	spawn ssh root@$1
	expect \"(yes/no)?\" {send \"yes\n\"}
	expect \"*assword:\" {send \"$2\n\"}
	expect \"#\" {send \"rm -rf /root/.ssh/authorized_keys\n\"}
	expect \"#\" {send \"mkdir /root/.ssh\n\"}
	expect \"#\" {send \"exit\n\"}
	expect eof
	"
#远程拷贝公钥文件
/usr/bin/expect -c "
	spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@$1
	expect \"*assword:\" {send \"$2\n\"}
	expect eof
	"
#远程机公钥文件重新改变权限
/usr/bin/expect -c "
	spawn ssh root@$1
	expect \"*assword:\" {send \"$2\n\"}
	expect \"#\" {send \"chmod 0400 /root/.ssh/authorized_keys\n\"}
	expect \"#\" {send \"exit\n\"}
	expect eof
	"
}

j=1
for i in $(cat iplist.txt);do
	rm -rf /root/.ssh/known_hosts
	echo 第 $j 台 ip 是 $i 正在分发公钥,请稍后...
	pub_key $i $password
	echo $i 已完成分发公钥 
	let j++
done

1.iplist.txt文件是和此脚本同目录下的IP列表文件,每行都是一个IP地址 2.这里假设机器密码都是123,其实生产环境的密码都是统一的;

三、ssh协议相关补充 1.ssh-copy-id,ssh root@xxx.xxx.xxx.xxx,scp等命令都属于ssh协议簇里命令;如果首次对某台远程机使用其中的命令,则会出现(yes/no):的提示;输入yes之后,以后再对此台机器使用ssh协议中的命令,则不会再提示(yes/no):,因为在/root/.ssh/目录下生成了known_hosts,记录了远程连接记录;

2.ssh协议免密远程连接:本地生成密钥对后,如果手动发送公钥到远程机,对方公钥文件名必须改名为authorized_keys;