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