Centos7 shell下的expect 免交互实现

1.下载

yum install -y expect

2.使用

#!/usr/bin/expect
spawn +command
expect {
        "希望匹配到的元素" { send "希望输出的内容";exp_continue }
        "希望匹配到的元素" { send "希望输出的内容" };
}
interact

spawn expect 内部命令,启动一个shell程序。
expect 期望哪些内容
””内输入希望匹配到的问题 ,\r 表示回车
send后的””内输入当遇到匹配到的问题时需要交互执行的动作
exp_continue,跳过循环,就继续下一条语句。
interact 允许用户交互
3.示例
Eg1: 用expect脚本实现远程登录

#!/usr/bin/expect
spawn ssh root@192.168.80.170
expect {
	"password:" { send "liu13881044103\r"};
}
Interact

Eg1: expect+shell 实现批量推送密匙
ip.text:从机ip集合文件

192.168.80.170

keygen_expect.sh:主机执行文件

#!/bin/bash
if [ x"$1" = x ] ;then
	echo "ip文件不存在"
	exit
fi
/usr/bin/expect<<-EFO
spawn ssh-keygen -t rsa
expect {
	"Enter file in which to save the key (/root/.ssh/id_rsa):" { send "\r";exp_continue};
	"Overwrite (y/n)?" { send "y\r";exp_continue};
	"Enter passphrase (empty for no passphrase):" { send "\r";exp_continue};
	"Enter same passphrase again:" { send "\r";exp_continue};
}
EFO


while read ip;do
	ping -c1 -w1 $ip
	if [ $? -ne 0 ];then
		echo "ping $ip is error"
		continue
	fi 
	
	/usr/bin/expect<<-EFO
	spawn scp /root/.ssh/id_rsa.pub /root/install_keygen.sh root@$ip:/root/
	expect {
		"password:" { send "liu13881044103\r";exp_continue};
	}
	EFO
	/usr/bin/expect<<-EFO
        spawn ssh root@$ip "chmod a+x /root/install_keygen.sh; bash /root/install_keygen.sh"
        expect {
                "password:" { send "liu13881044103\r";exp_continue};
        }
	EFO
	echo "create $ip ssh-keygen successful"
	
done<$1

install_keygen.sh 从机执行文件

#!/bin/bash
[ -e /root/.ssh/authorized_keys ]
if [ $? -ne 0 ];then
        echo "/root/.ssh/authorized_keys not exist"
        [ -e id_rsa.pub ]
        if [ $? -ne 0 ];then
                echo "id_rsa.pub not exist"
                exit
        fi
        mkdir /root/.ssh &>/dev/null
        if [ $? -eq 0 ];then
                cat id_rsa.pub>>/root/.ssh/authorized_keys
                status=$?
        fi

else
        [ -e id_rsa.pub ]
        if [ $? -ne 0 ];then
                echo "id_rsa.pub not exist"
                exit
        fi
        if [ $? -eq 0 ];then
               cat id_rsa.pub>>/root/.ssh/authorized_keys
                status=$?
        fi

fi
if [ $status -eq 0 ] ; then
        echo 'successful'
else
        echo 'error'
fi
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值