Linux expect使用摘要

expect交互,包括三个文件:bash.sh、expect.exp、ip.list(默认在同一个目录下)
执行有两种方式,1.sh bash.sh 根据ip.list表来执行;2.expect.exp x.x.x.x单个ip执行
后面发现在expect脚本中,“#”要出现在命令最开始的地方才是注释,否则会报错。

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 ## 将ip作为参数传递给expect脚本执行,并将结果写入生成$ip.result文件
## cat $ip.result |grep --color Speed  ## 读出文件内容,并过滤。
done

expect代码:

#!/usr/bin/expect -f

# 取传入的第一个参数赋值
set ipaddress   [lindex $argv 0]
  
# 变量赋值
set password    ******** 

# 设置超时时间3s,默认10s
set timeout 3  

 # “spawn” 关键字发起一个进程,“exp_continue” 继续执行下面匹配
spawn ssh $ipaddress 
expect {  
        "yes/no" {send "yes\r";exp_continue}  
        "*assword:" {send "$password\n"}
}

## 下面是执行语句,仍然需要使用 “expect” 关键字进行匹配,配合 “send” 关键字,发送命令。
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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值