文章目录
Shell编程之免交互
一、概览
1、Here Document概述
- 使用I/O重定向的方式将命令列表提供给交互式程序
- 标准输入的一种替代品
- 语法格式
命令 <<标记
…
…
标记
2、Here Document使用注意事项
- 标记可以使用任意合法字符
- 结尾的标记一-定要顶格写,前面不能有任何字符
- 结尾的标记后面也不能有任何字符(包括空格)
- 开头标记前后的空格会被省略掉
3、Expect概述
- 建立在tcl之.上的一个工具
- 用于进行自动化控制和测试
- 解决shel脚本中交互相关的问题
4、基本命令
1、expect
- 判断上次输出结果中是否包含指定的字符串,如果有则立即返回,否则就等待超时时间后返回
- 只能捕捉由spawn启动的进程的输出
- 用于接收命令执行后的输出,然后和期望的字符串匹配
2、send
- 向进程发送字符串,用于模拟用户的输入
- 该命令不能自动回车换行,- -般要加\r (回车)
3、spawn
- 启动进程,并跟踪后续交互信息
4、结束符
- expect eof—等待执行结束
- interact—执行完成后保持交互状态,把控制权交给控制台
5、set
- 设置超时时间,过期则继续执行后续指令
- 单位是秒
- timeout -1表示永不超时
- 默认情况下,timeout是10秒
6、exp_ continue
- 允许expect继续向下执行指令
7、send_ user
- 回显命令,相当于echo
8、接收参数
- Expect脚本可以接受从bash传递的参数
- 可以使用[lindex $argv n]获得
- n从0开始,分别表示第一个,第二个 ,第三个…参数
二、实验案例
案例1:创建用户并设置密码
- 正常情况下的交互过程
- 编写Shell脚本(嵌入方式)
#!/bin/bash
user=$1
password=$2
useradd $user
#expect嵌入
expect <<EOF
spawn passwd $user
expect "New password:"
send "${password}\r"
expect "Retype new password:"
send "${password}\r"
expect eof;
EOF
案例2:实现SSH自动登录
- 首次登录
- 正常登录
- 连接被拒绝,可能是ssh没开,或者端口不对,或者防火墙限制
- 没有连接地址
方案1
#!/usr/bin/expect
set timeout -1
set hostname [lindex $argv 0]
set password [lindex $argv 1]
spawn ssh root@${hostname}
expect {
"Connection refused" exit
"Name or service not known" exit
"to continue" {send "yes\r";exp_continue}
"password:" {send "${password}\r";}
}
expect "*]#"
send "exit\r"
expect eof
方案2
#!/bin/bash
hostname=$1
password=$2
/usr/bin/expect <<-EOF
set timeout -1
spawn ssh root@${hostname}
expect {
"Connection refused" exit
"Name or service not known" exit
"to continue" {send "yes\r";exp_continue}
"password:" {send "${password}\r";}
}
expect "*]#"
send "exit\r"
expect eof
EOF
案例3:利用expect完成FTP登录过程
#!/usr/bin/expect
set timeout -1
set hostname [lindex $argv 0]
spawn ftp ${hostname}
expect {
"root):" {send "ftp\r";exp_continue}
"Password:*" {send "\r";exp_continue}
}
expect "ftp>*"
interact
expect eof