应同事需求自行编写了第一个脚本,中间遇到一些坑。
需求,要求抓取设备“show ip interface brief”信息和“show interface des”描述信息。并且要求VLAN与描述信息在一个文件中显示出来。其实抓取工作很简单,难点在于字符处理中遇到时很多坑,比如关键字"More“抓取之后会有类似于“^[[7m--More--^[[m^M”的多余字符,是因为系统版本原因产生的。要用sed将其处理为awk可以匹配的格式。
先上内容。
1,抓取“show ip interface brief”信息(show inter des命令直接替换)。
#!/usr/bin/expect
#set ip
set ipaddress [lindex $argv 0]
#set user
set name [lindex $argv 1]
#set passwd
set passwd [lindex $argv 2]
#set timeout
set timeout 2
#ssh process
spawn ssh $name@$ipaddress
#进行判断
expect {
"yes/no" { send "yes\r" }
"*assword:" { send "$passwd\r";exp_continue}
"*# " { send "show ip inter bri\r" }
while (1) {
expect {
"More--" { send " " }
"*#" { break }
}
}
expect eof
2,字符处理脚本
用户名密码文件的格式为:
ip1 user1 passwd1
ip2 user2 passwd2
脚本如下:
#!/bin/bash
p=`pwd`
for i in `awk '{print $1}' $p/passwd` #取文件中第一列IP
do
j=`grep $i $p/passwd | awk '{print $2}'`
k=`grep $i $p/passwd | awk '{print $3}'` #j,k分别为取到的用户名,密码
echo "正在抓取"$i"的信息"
expect $p/ssh-brief.exp $i $j $k | grep Vlan > $p/brief/$i-bri.log #将ip,j,k作为参数传给expect登录并取配置存入文件中
if [ $? -eq 0 ];then
echo $i"地址文件抓取成功,下一步抓取描述文件。"
else
echo $i"地址文件抓取失败,即将退出脚本"
exit
fi
expect $p/ssh-des.exp $i $j $k | grep Vlan > $p/des/$i-des.log
if [ $? -eq 0 ];then
echo $i"描述文件抓取成功成功"
else
echo $i"描述文件抓取失败,即将退出脚本"
exit
fi
echo "处理"$i"的地址文件"
if [ $? -eq 0 ];then
echo $i"---------------------------------------------------------------------成功"
else
echo "生成"$i"文件失败,即将退出。"
exit
fi
done