expect实现免交互
如果想写一个能够自动处理输入输出的脚本又不想面对C或Perl,那么expect是最好的选择。它可以用来做一些Linux下无法做到交互的一些命令操作。
(1).安装和使用expect
expect是不会自动安装的所以需要使用命令进行安装,这里使用yum即可:
1 | [root@xuexi ~]# yum -y install expect |
在脚本中使用expect的方法一般有两种:
第一种、定义脚本执行的shell时,定义为expect。即脚本第一行为#!/bin/expect或#!/usr/bin/expect;
第二种、在shell脚本中使用时,可以使用一组/usr/bin/expect<<EOF和EOF来对expect调用。
(2).expect中参数和语法说明
set [变量名] "[String]"
在expect脚本中设置变量需要在前面使用set,否则无法使用。
set timeout 30
设置超时时间,单位为秒,如果设为timeout -1则永不超时。
spawn
spawn是进入expect环境后才能执行的内部命令,如果没有安装expect或直接在默认shell下执行是找不到spawn命令的。它主要的功能是开启脚本和命令之间的会话。(后面跟随的命令必须是需要交互的,因为expect脚本是用来做交互应用的)
expect
这里的expect同样是expect的内部命令。主要功能是判断输出结果是否包含某项关键字,没有则立即返回,否则等待一段时间后返回,等待时间通过set timeout进行设置。有两种写法:
1 2 3 4 5 6 7 8 9 10 11 12 | expect{ "[String1]" {send "[sendString1]\r" ;exp_continue} "[String2]" {send "[sendString2]\r" ;exp_continue} ... "[StringN]" {send "[sendStringN]\r" } } 或 expect "String" send "sendString1\r" sned "sendString2\r" ... expect eof |
send
执行交互动作,将交互要执行的动作输入。命令字符串结尾要加上"\r",如果出现异常等待状态可以进行核查
exp_continue
继续执行接下来的交互操作
interact
执行完后保持交互状态,把控制权交给控制台;如果没有这一项,交互完成后会自动退出
$argv
expect脚本可以接受从bash传递过来的参数,可以使用[Iindex $argv n]获得,n从0开始表示第一个参数。
注意:spawn开启会话,expect和send进行交互。
(3).脚本实例
1)expect脚本实现ssh免交互
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | [root@xuexi ~]# cat ssh-6.exp #!/bin/expect set ipaddr "192.168.1.6" set name "root" set passwd "123456" set timeout 30 spawn ssh $name@$ipaddr expect "password" send "$passwd\r" expect eof expect "#" send "ls /etc/ >> /root/1.txt\r" send "exit\r" expect eof [root@xuexi ~]# expect ssh-6.exp spawn ssh root@192.168.1.6 root@192.168.1.6's password: Last login: Sat May 11 18:24:27 2019 from xuexi [root@youxi1 ~]# ls /etc/ >> /root/1.txt [root@youxi1 ~]# exit 登出 Connection to 192.168.1.6 closed. |
在192.168.1.6上可以看到生成了/root/1.txt
2)shell脚本实现免交互
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 | [root@xuexi ~]# cat ssh-6.sh #!/bin/bash name= "root" passwd= "123456" ipaddr= "192.168.1.6" /bin/expect << EOF set timeout 30 spawn ssh $name@$ipaddr expect "password" send "$passwd\r" expect eof expect "#" send "ls /etc/ >> /root/2.txt\r" send "exit\r" expect eof EOF [root@xuexi ~]# sh ssh-6.sh spawn ssh root@192.168.1.6 root@192.168.1.6's password: Last login: Sat May 11 19:21:18 2019 from xuexi [root@youxi1 ~]# ls /etc/ >> /root/2.txt [root@youxi1 ~]# exit 登出 Connection to 192.168.1.6 closed. |
在192.168.1.6上可以看到生成了/root/2.txt
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性