标签:and 地址 编写 net enc 更改 %s 替换 bin
由于工作需要,编写了一个自动检查办公区无线AP是否掉线的python脚本,我这里用的是python3环境,请大家注意#!/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:
#把ac@exit替换成空的并转换成字典
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状态正常!‘)
标签:and 地址 编写 net enc 更改 %s 替换 bin
原文地址:http://blog.51cto.com/461884/2136409