expect命令

expect介绍

expect 是由 Don Libes 基于 Tcl(Tool Command Language)语言开发的,主要应用于自动化交互式操作的场景,借助 Expect 处理交互的命令,可以将交互过程如:ssh登录,ftp登录等写在一个脚本上,使之自动化完成。尤其适用于需要对多台服务器执行相同操作的环境中,可以大大提高系统管理人员的工作效率。

expect 语法:

expect [option] [-c cmds] [[-[f|b]] cmdfile] [args]

  • 选项:
     -c:从命令行执行 expect 脚本,默认 expect 是交互地执行的
      expect -c expect "\n" {send "pressed enter\n"}
     -d:可以输出调试信息
      expect -d ssh.exp

  • expect 中相关命令:
    spawn:启动新的进程
    send:用于向进程发送字符串
    expect:从进程接收字符串
    interact:允许用户交互
    exp_continue:匹配多个字符串在执行动作后加此命令

  • expect 最常用的语法(tcl 语言:模式 - 动作)

  • 单一分支模式语法:
    匹配到 hi 后,会输出 "You said hi",并换行

    [root@node2 ~]# expect
    expect1.1> expect "hi" {send "You said hi\n"}
    hi
    You said hi
    
  • 多分支模式语法:
    匹配 hi,hehe,bye 任意字符串时,执行相应输出

    [root@node2 ~]# expect
    expect1.1> expect "hi" { send "You said hi\n" } \
    +> "hehe" { send "Hehe yourself\n" } \
    +> "bye" { send "Good bye\n" }
    hi
    You said hi
    
    [root@node2 ~]# expect
    expect1.1> expect {
    +> "hi" { send "You said hi\n" }
    +> "hehe" { send "Hehe yourself\n" }  
    +> "bye" { send "Good bye\n" }
    +> }
    hi
    You said hi
    

示例:

  1. 自动化远程复制文件
    #!/usr/bin/expect
    spawn scp /etc/fstab 192.168.8.100:/app
    expect {
            "yes/no" { send "yes\n";exp_continue }
            "password" { send "RyoATeu6\n" }
    }
    expect eof
    
  2. 自动化登录
    #!/usr/bin/expect
    spawn ssh 192.168.8.100
    expect {
            "yes/no" { send "yes\n";exp_continue }
            "password" { send "RyoATeu6\n" }
    }
    interact
    
  3. 变量
    #!/usr/bin/expect
    set ip 192.168.8.100
    set user root
    set password 88888888
    set timeout 10
    spawn ssh $user@$ip
    expect {
            "yes/no" { send "yes\n";exp_continue }
            "password" { send "$password\n" }
    }
    interact
    
  4. 位置参数
    #!/usr/bin/expect
    set ip [lindex $argv 0]
    set user [lindex $argv 1]
    set password [lindex $argv 2]
    spawn ssh $user@$ip
    expect {
            "yes/no" { send "yes\n";exp_continue }
            "password" { send "$password\n" }
    }
    interact
    
  5. shell脚本调用expect
    #!/bin/bash
    ip=$1
    user=$2
    password=$3
    expect <

你可能感兴趣的:(expect命令)