expect命令

2020-03-08  本文已影响0人  Simon_Ye

expect介绍

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

expect 语法:

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

示例:

  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 <<EOF
    set timeout 10
    spawn ssh $user@$ip
    expect {
            "yes/no" { send "yes\n";exp_continue }
            "password" { send "$password\n" }
    }
    expect "]#" { send "useradd hehe\n" }
    expect "]#" { send "echo 88888888 | passwd --stdin hehe\n" }
    expect "]#" { send "exit\n" }
    expect eof
    EOF
    
上一篇下一篇

猜你喜欢

热点阅读