参考文档:Shell 编程 免交互 expect
expect脚本
编写以 #!/usr/bin/expect 开头的脚本,缺点是只能执行 expect 相关命令,不能执行 ls, pwd 等其他命令。示例:
#!/usr/bin/expect
set timeout 30
# 上传文件到服务器
spawn scp target/test-service.jar root@192.168.42.90:/root
expect "root@192.168.42.90's password: "
send "root\r"
expect eof
# 启动服务
spawn ssh root@192.168.42.90
expect "password: "
send "root\r"
expect "~]# "
send "java -jar test-service.jar\r"
expect "~]# "
send "exit\r"
expect eof
exit
shell 脚本嵌入 expect 命令
用 shell 脚本的好处是在 expect 前后可以执行其他的 shell 命令。有两种使用方式:
方式一:/usr/bin/expect << EOF
#!/bin/sh
./mvnw clean package
ls -l target/test-service.jar
/usr/bin/expect << EOF
set timeout 30
spawn scp target/test-service.jar root@192.168.42.90:/root
expect "root@192.168.42.90's password: "
send "root\r"
expect eof
# 启动服务
spawn ssh root@192.168.42.90
expect "password: "
send "root\r"
expect "~]# "
send "java -jar test-service.jar\r"
expect "~]# "
send "exit\r"
expect eof
EOF
方式二:expect -c
这种方式相当于把要执行的内容以字符串的形式传给 expect,所以中间的引号字符需要用 \ 转义。
#!/bin/sh
./mvnw clean package
ls -l target/test-service.jar
expect -c "
set timeout 30
spawn scp target/test-service.jar root@192.168.42.90:/root
expect \"root@192.168.42.90's password: \"
send \"root\r\"
expect eof
# 启动服务
spawn ssh root@192.168.42.90
expect \"password: \"
send \"root\r\"
expect \"~]# \"
send \"java -jar target/test-service.jar\r\"
expect \"~]# \"
send \"exit\r\"
expect eof
"