Linux-交互式转化批处理工具expect
expect 是由Don Libes基于 Tcl( Tool Command Language )语言开发的,主要应用于自动化交互式 操作的场景,借助 expect 处理交互的命令,可以将交互过程如:ssh登录,ftp登录等写在一个脚本 上,使之自动化完成。尤其适用于需要对多台服务器执行相同操作的环境中,可以大大提高系统管理人 员的工作效率
安装expect
yum -y install expect
expect 语法:
expect [选项] [ -c cmds ] [ [ -[f|b] ] cmdfile ] [ args ] 常见选项 -c:从命令行执行expect脚本,默认expect是交互地执行的 -d:可以调试信息
示例:
[root@centos8~]$expect -c 'expect "\n" {send "pressed enter\n"}' expect #交互式输入“expect” 接收 pressed enter #匹配到expect后,会输出“pressed enter”,并换行
[root@centos8~]$expect -d ssh.exp expect version 5.45.4 argv[0] = expect argv[1] = -d argv[2] = ssh.exp set argc 0 #set 定义变量 格式:set 变量名 变量值 set argv0 "ssh.exp" set argv "" executing commands from command file ssh.exp couldn't read file "ssh.exp": no such file or directory
expect中相关命令
spawn 启动新的进程 expect 从进程接收字符串 send 用于向进程发送字符串 interact 允许用户交互 exp_continue 匹配多个字符串在执行动作后加此命令
expect最常用的语法(tcl语言:模式-动作)
单一分支模式语法
[root@centos8~]$expect expect1.1> expect "hi" {send "You said hi\n"} #交互式输入时,不能随意编辑,需一次性输入成功 hahiccc You said hi expect1.2>
匹配到hi后,会输出“you said hi”,并换行
多分支模式语法:
[root@centos8~]$expect expect1.1> expect "hi" {send "You said hi\n"} hahiccc You said hi expect1.2> expect "hi" { send "You said hi\n" } "hehe" { send "Hehe yourself\n"} "bye" { send "Good bye\n" } bye Good bye expect1.3> expect "hi" { send "You said hi\n" } "hehe" { send "Hehe yourself\n"} "bye" { send "Good bye\n" } hi You said hi expect1.4> expect "hi" { send "You said hi\n" } "hehe" { send "Hehe yourself\n"} "bye" { send "Good bye\n" } hehe Hehe yourself
匹配hi,hehe,bye任意字符串时,执行相应输出。
示例:自动登录
[root@centos8/data]$vim expect.logon #!/usr/bin/expect # # spawn ssh root@10.0.0.77 expect { "yes/no" { send "yes\n";exp_continue } "password" { send "密***码\n" } } interact [root@centos8/data]$ll expect.logon -rw-r--r-- 1 root root 141 Apr 27 15:30 expect.logon [root@centos8/data]$chmod +x expect.logon [root@centos8/data]$ll total 4 -rwxr-xr-x 1 root root 141 Apr 27 15:30 expect.logon [root@centos8/data]$./expect.logon spawn ssh root@10.0.0.77 The authenticity of host '10.0.0.77 (10.0.0.77)' can't be established. ECDSA key fingerprint is SHA256:a8HZZS4TTvzQbF1/XJKDZvry1Lwa+9/jYIYXRPwqfIk. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '10.0.0.77' (ECDSA) to the list of known hosts. root@10.0.0.77's password: Last login: Wed Apr 27 15:05:01 2022 from 10.0.0.1