(九)expect批量公钥推送

(1)expect实现ssh非交互登录

注意:注释不能出现这脚本里面
spawn表示开启一个会话
:表示回车,exp_continue :表示没有出现这样,继续往下执行
interact :停留在对面终端

#!/usr/bin/expect 
spawn ssh root@192.168.111.101

expect {
        "yes/no" { send "yes
"; exp_continue }
        "password" { send "redhat
" }
}
interact

(2)expect实现批量公钥推送

#!/bin/bash
. /etc/init.d/functions
password=redhat    #被推送主机的密码
>ip.txt
#检查是否按照了expect软件
rpm -q expect &>/dev/null 
if [ $? -ne 0 ];then
	yum install expect -y 
	if [ $? -eq 0 ];then
		echo "install success!"
	else
		echo "install false!"
		exit 2
	fi
fi
#检查客户端是否生成了公钥和私钥
if [ ! -f ~/.ssh/id_rsa ];then
	ssh-keygen -P "" -f ~/.ssh/id_rsa
	if [ $? -eq 0 ];then
		echo "success!"
	else
		exit 2
	fi
fi
#检查客户端是否能ping通,如果能ping通就使用expect推送秘钥
for i in {2..254}
do
	{
	ip=192.168.111.$i
	ping -c1 -W1 $ip &>/dev/null
	if [ $? -eq 0 ];then
		/usr/bin/expect <<-EOF
		spawn ssh-copy-id $ip 
		set time_out 10
		expect  {
			"yes/no" { send "yes
"; exp_continue }
			"password" { send "$password
" }
		}
		expect eof
		EOF
		if [ $? -eq 0 ];then
			action "$ip" /bin/true
			echo $ip >> ip.txt
		else
			action "$ip" /bin/false
		fi
	fi
	}& 
done
wait
echo "finish......"

(3)for循环实现ssh远程修改配置文件

#!/bin/bash
for ip in $(cat ip.txt)
do
        {
        ping -c1 -W1 $ip &>/dev/null
        if [ $? -eq  0 ];then
                ssh $ip "sed -ri '/^#UseDNS/cUseDNS no' /etc/ssh/sshd_config"
                ssh $ip "sed -ri '/^GSSAPIAuthentication/cGSSAPIAuthentication no' /etc/ssh/sshd_config"
                ssh $ip "systemctl restart sshd_config"
                ssh $ip "sed -ri '/SELINUX/cSELINUX=disabled' /etc/sysconfig/selinux"
                ssh $ip "setenforce 0"
                ssh $ip "systemctl stop firewalld;systemctl disable filewalld"
        fi
        }&
done

(4)for循环远程批量修改root密码

#!/bin/bash
read -p "please input a New Passowrd:" password
for ip in $(cat ip.txt)
do
        {
        ping -c1 -W1 $ip &>/dev/null
        if [ $? -eq 0 ];then
                ssh $ip "echo $password | passwd --stdin root"
                if [ $? -eq 0 ];then
                        echo "$ip" >>ok_$(date +%F).txt
                else
                        echo "$ip" >>false_$(date +%F).txt
                fi
        else
                echo "$ip" >>false_$(date +%F).txt
        fi
        }&
done
原文地址:https://www.cnblogs.com/lovelinux199075/p/8908665.html