zoukankan      html  css  js  c++  java
  • shell脚本系列:expect脚本

    参数说明:

    • set:可以设置超时,也可以设置变量
    • timeout:expect超时等待时间,默认10S
    • spawn:执行一个命令
    • expect "":匹配输出的内容
    • exp_continue:继续执行下面匹配
    • :可以理解为回车
    • $argc:统计位置参数数量
    • [lindex $argv 0]:脚本后第一个参数,类似于shell中$1,以此类推
    • puts:打印字符串,类似于echo
    • awk -v I="$ip":赋值变量
    • expect{...}:输入多行记录

    其他参数说明:

    • timeout -1:永不超时退出
    • log_file /var/log/expect.log:记录交互信息,一般crontab时使用
    • interact:交互后不退出远程终端,如果加要把expect "root@*" {send "exit "}注释掉,如果不加,就直接退出
    • 将spawn ssh root@$ip换成spawn ssh -o StrictHostKeyChecking=no root@ip既不会再提示是否将服务器计算机密钥加入本地known_hosts

    示例:

    shell内嵌类型:

    #!/bin/bash
    /usr/bin/expect << EOF
    spawn /bin/su -
    expect "Password: "
    send "123
    "
    expect "*#"
    interact
    expect eof
    EOF
    

    分离型:

    vi login.exp
    
    #!/usr/bin/expect 
    set ipaddress [lindex $argv 0]
    set username [lindex $argv 1]
    set password [lindex $argv 2]
    
    if { $argc != 3 } {
    puts "Usage: expect login.exp ipaddress username password"
    exit 1
    }
    
    set timeout 30
    spawn ssh $username@$ipaddress
    expect {
            "(yes/no)" {send "yes
    "; exp_continue}
            "password:" {send "$password
    "}
    }
    
    expect "$username@*"  {send "df -h
    "}
    expect "$username@*"  {send "exit
    "}
    expect eof
    
    vi user_info
    
    192.168.1.156   user    user
    192.168.1.154   root    123.com
    
    vi expect.sh
    
    #!/bin/bash
    for ip in `awk '{print $1}' user_info`
    do
        user=`awk -v I="$ip" '{if(I==$1)print $2}' user_info`
        pass=`awk -v I="$ip" '{if(I==$1)print $3}' user_info`
        expect login.exp $ip $user $pass
    done
    
  • 相关阅读:
    一失足千古恨在 WSL 中使用了 md 创建文件夹 (2020-04-26)
    开源中国 ThinkPHP 领奖
    投资投机脑图(2019-12-12)
    什么? 1XIN = 21BTC
    笔记:投机和投资 F4NNIU
    如何设置单个 Git 仓库的代理从而提高更新速度
    FastAdmin 使用 phpmail 出现 spl_autoload_register 错误
    plsql 引用型变量
    oracle 存储函数
    oracle存储过程(带参数的存储过程)
  • 原文地址:https://www.cnblogs.com/iuskye/p/shell-expect.html
Copyright © 2011-2022 走看看