expect自动应答
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
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 expectName : expect Relocations: (not relocatable)Version : 5.44.1.15 Vendor: CentOSRelease : 5.el6_4 Build Date: Mon 04 Nov 2013 05:05:44 PM CSTInstall Date: Sun 21 Aug 2016 11:48:49 PM CST Build Host: c6b9.bsys.dev.centos.orgGroup : Development/Languages Source RPM: expect-5.44.1.15-5.el6_4.src.rpmSize : 566637 License: Public DomainSignature : RSA/SHA1, Mon 04 Nov 2013 07:53:54 PM CST, Key ID 0946fca2c105b9dePackager : CentOS BuildSystem <http://bugs.centos.org>URL : http://expect.nist.gov/Summary : A program-script interaction and testing utilityDescription :Expect is a tcl application for automating and testinginteractive applications such as telnet, ftp, passwd, fsck,rlogin, tip, etc. Expect makes it easy for a script tocontrol 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 |

浙公网安备 33010602011771号