由于工作需要,编写了一个自动检查办公区无线AP是否掉线的python脚本,我这里用的是python3环境,请大家注意
还有要注意的是我这里用的是锐捷的无线AC及无线AP。其它品牌只需要替换相关命令即可,就是脚本内容的中的command内容更改成你的品牌无线AC命令即可。
下面是实际脚本内容:
#!/usr/local/python3/bin/python3
import telnetlib,time,os
def do_telnet(Host,password,finish,commands):
import telnetlib
tn = telnetlib.Telnet(Host, port=23)
tn.read_until(b‘Password:‘)
tn.write(password + b‘\n‘)
tn.read_until(finish)
tn.write(commands1 + b‘\r\n‘)
time.sleep(1)
tn.read_until(b‘Password:‘)
tn.write(password + b‘\n‘)
time.sleep(1)
tn.read_until(b‘#‘)
tn.write(commands + b‘\n‘)
time.sleep(10) # 这里一定要等待10秒,因为你write命令以后,会等待很长时间。
tn.write(b‘exit\n‘)
result = tn.read_all()
file_object = open(‘/opt/scripts/network/result.txt‘, ‘wb‘)
file_object.write(result)
file_object.close()
tn.close()
if __name__ == ‘__main__‘:
Host = ‘192.168.1.12‘ # Telnet服务器IP
password = ‘abc123‘.encode(encoding=‘utf-8‘) # 登录密码
finish = ‘>‘.encode(encoding=‘utf-8‘) # 命令提示符
commands = ‘show web-api ibeacon‘.encode(encoding=‘utf-8‘)
commands1 = ‘en‘.encode(encoding=‘utf-8‘)
do_telnet(Host,password,finish,commands)
#判断AP是否在线
with open(‘/opt/scripts/network/result.txt‘,‘r‘) as f:
for i in f:
if ‘code‘ in i:
#把[email protected]替换成空的并转换成字典
i = eval(i.replace(‘ac#exit‘,‘‘))
aplist = i[‘data‘][‘list‘]
day = time.strftime(‘%Y-%m-%d‘, time.localtime())
time = time.strftime(‘%H:%M:%S‘, time.localtime())
for j in aplist:
if j[‘status‘] != ‘run‘:
ip = j[‘ip‘]
mac = j[‘mac‘]
name = j[‘name‘]
status = j[‘status‘]
with open(‘satus.txt‘,‘a‘) as f1:
message = ‘当前时间:‘ + day + ‘ ‘ + time + ‘,‘ + ‘无线AP的ip:‘ + ip + ‘,‘ + ‘当前状态是不在线,‘ + ‘无线AP的mac地址:‘ + mac + ‘,‘ + ‘无线AP名称是:‘ + name + ‘,‘ + ‘无线AP状态:不在线‘
f1.write(message + ‘\n‘)
#发送微信报警
os.system(‘./weixin.py a abc 无线AP名称:%s不在线,请检查!‘ %name)
else:
print(‘无线AP状态正常!‘)
原文地址:http://blog.51cto.com/461884/2136409
时间: 2024-10-28 04:03:36