最近openwrt出现wan口显示连接正常,测试却ping不通外网的情况,家里的多个接入设备断网,写了个python脚本,利用nas上的测试用虚机执行每五分钟检测一次,一但公网不可达,重启openwrt的网络连接。
python,
import paramiko
import re
import subprocess #python2.0 是commands
import time
ipset = ['123.126.96.181','39.156.66.14','8.8.8.8','114.114.114.114',
'120.221.226.245'] #这里填写公网地址,不要写域名,
公网不通dns会失效,尽量多写几个,避免误操作
allresult = []
a = 0
for ip in ipset: #循环测试多个ip,结果或运算
match=re.search('transmitted,\s(\d)',subprocess.getoutput('ping '+ip+' -c 1'))
result=match.groups()
if result:
allresult.append(result[0]) #这里直接append(1)也可以
else:
allresult.append(0)
for i in range(len(allresult)):
a |= int(allresult[i])
if not a: #以上测试全部不通,才会执行这段通过paramiko登录openwrt,重启网络的操作
channel = paramiko.SSHClient()
channel.set_missing_host_key_policy(paramiko.AutoAddPolicy())
channel.connect(hostname='openwrt管理ip',username='openwrt用户名',password='密码',look_for_keys=False,allow_agent=False)
shell = channel.invoke_shell()
shell.send("/etc/init.d/network restart\n")
time.sleep(2)
print (shell.recv(5000).decode('ascii'))
最后设置任务计划,定期执行即可
[dali@localhost ~/test/script]$cat /var/spool/cron/root
*/5 * * * * /usr/local/bin/python3 /root/test/script/ping.py