Linux expect使用摘要

expect交互,包括三个文件:bash文件、expect文件和一个ip列表文件

bash代码:

#!/bin/bash

for ip in `awk '{print $1}' ip.list` ##从ip.list中取ip
do
echo -e "\033[47;30m start get_NicSpeed of $ip \033[0m" ##白底黑字显示
expect -f  expect.exp $ip > $ip.result ##将结果写入文件
cat $ip.result |grep --color Speed  ##从文件中获取所需信息
done

expect代码:

#!/usr/bin/expect -f

set ipaddress   [lindex $argv 0]  ##取传入的第一个参数赋值
set password    ********  ##变量赋值
set timeout 3  #设置超时时间3s,默认10s
spawn ssh $ipaddress  ##spawn关键字发起一个进程
expect {  
        "yes/no" {send "yes\r";exp_continue}  ##exp_continue:继续执行下面匹配
        "*assword:" {send "$password\n"}
}

for {set i 0} {$i < 8 } {incr i} {  ##循环
        expect  "]#" {send "ethtool eth$i|grep Speed\r"}
        set j [expr $i+1]  ##expect中的加法  ##加法
        expect  "~#" {send "/usr/local/bin/ethtool eth$j|grep Speed\r"}
}
expect {
        "~#" {send "exit\r";exp_continue}  ##退出方式之一
        "]#" {send "exit\r"}
}

ip列表文件:

10.10.10.1
10.10.10.2
...

其他:

$argc:统计位置参数数量
timeout -1:永不超时退出
interact:交互后不退出远程终端
puts:打印字符串,类似于echo

猜你喜欢

转载自blog.csdn.net/qq_15742255/article/details/80642434