【Linux系列教程】expect工具
一、安装expect工具
[root@localhost ~]# yum install -y expect 
二、独立使用expect工具
set timeout 10 设置超时时间, 单位秒
spawn 指定交互式命令
expect 指定捕获的提示信息
send 发送指令
expect eof 捕获结束
#!/usr/bin/expect
#
set timeout 10
spawn passwd martin
expect "New password:"
send "www.1.com\n"
expect "Retype new password:"
send "www.1.com\n"
expect eof
三、配合Shell脚本使用
1.自动创建用户和设置用户密码
#!/bin/bash
#
useradd AAA
/usr/bin/expect << eof	#固定格式
set timeout 10
spawn passwd AAA
expect "New password:"
send "123\n"
expect "Retype new password:"
send "123\n"
expect eof	#固定eof结尾
eof	#固定格式
2.配合expect工具,配置ssh免密
#! /bin/bash
if [ -e ~/.ssh/known_hosts ]; then
    > ~/.ssh/known_hosts	#判断如果这个文件有内容,就清空文件内容
fi
if ls ~/.ssh/id_rsa* &> /dev/null ; then
    rm -rf ~/.ssh/id_rsa*	#判断如果有公钥文件和密钥文件,先清除
fi
ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa &> /dev/null	#创建密钥
for i in 129 130; do	#使用for循环,指定需要拷贝密钥的机器主机地址
/usr/bin/expect << eof	#固定格式
set timeout 2	#设置超时时间
spawn ssh-copy-id root@10.10.10.$i	#上面变量$i分别是129和130
expect "(yes/no)?"	#捕获
send "yes\n"	#选择yes
expect "password:"	#捕获
send "centos\n"	#设置密码
expect eof	#结束expect工具
eof	#固定格式
done	#循环结束
 
            
    
评论