一般来说,我们在编写shell脚本时都是自动运行的,如果涉及到与用户的交付,如远程ssh终端输入用户名/密码。有时我们需要编写的脚本自动运行,而不需要人工干预,选择Expect实现是一个很好的方式。
来一个简单的例子:
hello.sh
#!/bin/sh
echo -n "What's your name?:"
read name
echo "Hello $name!"
exit 0单独执行过程中需要在终端输入用户名称,执行结果如下,中间需要用户输入名称,脚本才会继续往下执行
执行截图:
nfssrv:/opt/mytest # sh hello.sh
What's your name?:使用expect,编写一个应答脚本autoHello.sh,使hello.sh自动运行下去
autoHello.sh
#!/bin/bash
expect << END
spawn ./hello.sh
expect "name"
send "ssrs\n"
expect eof
exit
END
执行截图:
nfssrv:/opt/mytest # sh autoHello.sh
spawn ./hello.sh
What's your name?:ssrs
Hello ssrs!
使用Expect自动应答Shell脚本
本文介绍如何使用Expect工具让需要用户交互的Shell脚本实现自动化运行,通过一个简单示例展示如何编写Expect应答脚本来自动输入用户名。
1472

被折叠的 条评论
为什么被折叠?



