shell脚本实现循环收集交换机信息

背景

某个客户主同中心互联的两台设备ospf邻居不知道什么原因偶发中断,但链路并没有down,经华为分析好像DC01的设备因为ospf hello报文超时,造成邻居down,至于为什么会超时,华为答复需要一直在设备上display信息,但ospf邻居down是偶发的,人工display太消耗人力了(但现实就是这样做的),我想了下是否可以通过写个shell脚本来自动收集display信息,从0开始慢慢写出了一个“笨拙”脚本。

脚本

思路:

  1. 写一个for循环shell脚本,for循环 ip文件里的IP地址,ssh登录设备,使用expect send交换机命令执行;
  2. 在写一个for 时间循环的shell脚本,因为linux中的crontab最少每1分钟执行一次,1分钟对于网络设备来说有点长,使用for循环+sleep实现秒级命令执行,把上一次shell脚本放到这个shell脚本中(套娃),将命令执行的结果导入到以时间为名称的文件里;
  3. crontab 写两个定时任务,一个执行2中的shell脚本,一个定期执行tar+bzip的shell脚本。

注意:

  • shell脚本中的路径要写一个具体的路径,不然会找不会脚本或脚本中调用的文件等。

  • tar+bzip(tar -jcvf)脚本的定时任务不知道为什么没有执行,但是在命令行中可以成功执行这个命令,也能实现相应的功能,但是设置定时任务后就不行了,于是乎又写了一个.sh脚本 执行tar命令。

1.批量收集设备信息,脚本名称为caiji04.sh
#!/bin/bash
for host in `cat /tmp/1/ip`
do
       echo -e "---------$host configration-----------\n\n"
        expect -c "
           set timeout 10;
           spawn ssh admin@${host} -p 22 ;
           expect {
               yes/no { send \"yes\r\"; exp_continue }
               *assword* { send \"admin\r\" }
           } ;
           sleep 0.5
           expect <*>   {send \" sc dis \r\"  } ;
           expect <*>   {send \" display cur \r\"  } ;
           expect <*>   {send exit\r }  ;
           expect eof ;
       "
done

2.for 时间循环,脚本名称为s-for.sh
[root@rhel 1]# cat s-for.sh
#!/bin/bash

step=6 #间隔的秒数,不能大于60

for (( i = 0; i < 60; i=(i+step) )); do
bash /tmp/1/caiji04.sh > /tmp/1/`date "+%F-%H-%M-%S"`
sleep $step
done

exit 0

[root@rhel 1]# cat tar.sh
#!/bin/bash
tar -jcvf `date "+%m-%d-%H-%M-%S"`.tar.bz2 /tmp/1/2023-03* --remove-files  //压缩后的tar文件放在了/etc/crontab中home自定义的目录中了。



3.crontab定时任务

[root@rhel 1]# crontab -l
* * * * * bash /tmp/1/s-for.sh
* * * * * bash /tmp/1/tar.sh

脚本优化:两个脚本合并成一个脚本

[root@rhel 1]# cat comb.sh
#!/bin/bash
step=6 #间隔的秒数,不能大于60
for (( i = 0; i < 60; i=(i+step) )); do
	for host in `cat /tmp/1/ip`
	do
       echo -e "---------$host configration-----------\n\n"
        expect -c "
           set timeout 10;
           spawn ssh admin@${host} -p 22 ;
           expect {
               yes/no { send \"yes\r\"; exp_continue }
               *assword* { send \"admin\r\" }
           } ;
           sleep 0.5
           expect <*>   {send \" sc dis \r\"  } ;
           expect <*>   {send \" display cur \r\"  } ;
           expect <*>   {send exit\r }  ;
           expect eof ;
       "
	done
sleep $step
done
exit 0
posted @   wefjack  阅读(276)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示