Linux shell脚本中用expect实现自动输入密码

1. 安装 expect

sudo apt-get install tcl tk expect

2. 使用示例

下面是一个scp的使用例子

#! /usr/bin/expect # 表示使用expect的shell的交互模式
set timeout 100    # 设置超时100秒,如果要执行的shell的命令很长可以设置超时时间长一些,expect超过超时时间没有检测到要找的字符串,则不执行,默认超时时间为10秒
set password "root" # set对password赋值
spawn scp output/bin/service_test [email protected]:/root # expect对通过spawn执行的shell脚本返回进行判断,是否包含 “” 中的字段
expect "password:"
send "$password\n" # 如果expect监测到了包含的字符串,将输入send中的内容,\n相当于回车
interact # 留在开的子进程内,可以继续输入,否则将退出子进程回到shell中(比如ssh登录到某台服务器上,只有加了interact才可以留在登录后的机器上进行操作)

3. 引用参考

参考链接

猜你喜欢

转载自blog.csdn.net/gmq_syy/article/details/111832030