其他分享
首页 > 其他分享> > expect自动应答

expect自动应答

作者:互联网

expect脚本
	1. expect简介
	expect是一个用来处理交互的命令。借助Expect,我们可以将交互过程写在一个脚本上,使之自动化完成。
	expect(自动应答)		基于TCL(Tool Command Language)语言演变而来
	
	expect中最关键的四个命令是:
	send:用于向进程发送字符串
	expect:从进程接收字符串
	spawn:启动新的进程
	interact:允许用户交互


	2. 安装expect
	# yum install expect -y

查看expect信息
[root@web1 sed]# rpm -qi expect
Name        : expect                       Relocations: (not relocatable)
Version     : 5.44.1.15                         Vendor: CentOS
Release     : 5.el6_4                       Build Date: Mon 04 Nov 2013 05:05:44 PM CST
Install Date: Sun 21 Aug 2016 11:48:49 PM CST      Build Host: c6b9.bsys.dev.centos.org
Group       : Development/Languages         Source RPM: expect-5.44.1.15-5.el6_4.src.rpm
Size        : 566637                           License: Public Domain
Signature   : RSA/SHA1, Mon 04 Nov 2013 07:53:54 PM CST, Key ID 0946fca2c105b9de
Packager    : CentOS BuildSystem <http://bugs.centos.org>
URL         : http://expect.nist.gov/
Summary     : A program-script interaction and testing utility
Description :
Expect is a tcl application for automating and testing
interactive applications such as telnet, ftp, passwd, fsck,
rlogin, tip, etc. Expect makes it easy for a script to
control another program and interact with it.

This package contains expect and some scripts that use it.

	任何有交互性的操作,都可以用expect来做	

	3. expect使用详解
	#!/bin/bash

	expect <<EOF > /dev/null 2>&1    --/dev/null 代表把标准输出重定向输出到空洞,2>&1代表把出错输出也定向到标准输出。
	spawn passwd $1		--产生passwd $1这个命令
	expect "password:"		--当停在rd:结尾这个标识符时
	send "456\r"		--我就把456传给它
	expect "password:"		--当再次停在rd:结尾这个标识符时
	send "456\r"		--我就再次把456传给它
	expect eof			--表示expect结束
	EOF




	# sh 1.expect test    --执行方法,因为脚本里写的是$1,所以后面接你要修改密码的用户名
远程ssh

	#!/bin/bash

	sed -i '/^'$1'/d' /root/.ssh/known_hosts
	expect << EOF > /dev/null 2>&1
	spawn ssh $1
	expect "no)?"
	send "yes\r"
	expect "password:"
	send "123456\r"
	expect "]#"
	send "mkdir /root/Desktop/aa\r"
	send "touch /root/Desktop/aa/$1\n"
	send "exit\n"
	expect eof
	EOF



	假设管理的机器有N台,密码也各不相同(没有ssh等效性),现在需要在每个机器上都创建一个文件

	# cat ip_user_passwd.txt 		--这个文件里包含你所有管理机器的IP,用户及其对应的密码
	10.1.1.63       root    oracle
	10.1.1.77       root    1234
	10.1.1.73       user1   123456
	10.1.1.85       root    54321
	......


	# cat 6.expect 
	#!/bin/bash

	cat ip_user_passwd.txt |while read ip user password 
	do
	sed -i '/^'$ip'/d' /root/.ssh/known_hosts
	expect <<EOF &> /dev/null
	spawn ssh $ip -l $user
	expect ")?"
	send "yes\r"
	expect "rd:"
	send "$password\n"
	expect "]#"
	send "touch /tmp/123\n"		--这里可以修改你每次要在这些机器上做的命令
	send "exit\n"
	expect eof
	EOF
	done

  

标签:send,自动应答,expect,password,root,dev,ssh
来源: https://www.cnblogs.com/The-day-of-the-wind/p/12064446.html