Centos7 shell下的expect 免交互实现

阅读: 评论:0

Centos7 shell下的expect 免交互实现

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 "liu13881044103r"};
}
Interact

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

192.168.80.170

keygen_expect.sh:主机执行文件

#!/bin/bash
if [ x"$1" = x ] ;thenecho "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 "yr";exp_continue};"Enter passphrase (empty for no passphrase):" { send "r";exp_continue};"Enter same passphrase again:" { send "r";exp_continue};
}
EFOwhile read ip;doping -c1 -w1 $ipif [ $? -ne 0 ];thenecho "ping $ip is error"continuefi /usr/bin/expect<<-EFOspawn scp /root/.ssh/id_rsa.pub /root/install_keygen.sh root@$ip:/root/expect {"password:" { send "liu13881044103r";exp_continue};}EFO/usr/bin/expect<<-EFOspawn ssh root@$ip "chmod a+x /root/install_keygen.sh; bash /root/install_keygen.sh"expect {"password:" { send "liu13881044103r";exp_continue};}EFOecho "create $ip ssh-keygen successful"done<$1

install_keygen.sh 从机执行文件

#!/bin/bash
[ -e /root/.ssh/authorized_keys ]
if [ $? -ne 0 ];thenecho "/root/.ssh/authorized_keys not exist"[ -e id_rsa.pub ]if [ $? -ne 0 ];thenecho "id_rsa.pub not exist"exitfimkdir /root/.ssh &>/dev/nullif [ $? -eq 0 ];thencat id_rsa.pub>>/root/.ssh/authorized_keysstatus=$?fielse[ -e id_rsa.pub ]if [ $? -ne 0 ];thenecho "id_rsa.pub not exist"exitfiif [ $? -eq 0 ];thencat id_rsa.pub>>/root/.ssh/authorized_keysstatus=$?fifi
if [ $status -eq 0 ] ; thenecho 'successful'
elseecho 'error'
fi

本文发布于:2024-01-31 09:04:30,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170666307327411.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:shell   expect
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23