我使用这个功能主要是为了不用手动打开一个服务器监控系统的页面,让程序自动检查告警信息,有问题就弹出告警
一、环境准备
操作系统:WINDOWS10
安装python的selenium模块,略
下载火狐浏览器的驱动geckodriver.exe
下载地址:https://github.com/mozilla/geckodriver/releases
选择相应的版本,并将geckodriver.exe拷贝至和firefox.exe同一目录,并将此目录加入WINDOWS10的系统环境变量
二、实现的程序
# -*- coding: utf-8 -*-
from selenium import webdriver
#import time
from selenium.webdriver.firefox.options import Options
import ctypes
def message_box(title, msg):
ctypes.windll.user32.MessageBoxW(0, msg, title, 1)
#弹出消息
def chkalert():
#浏览器在运行的时候自动隐藏
foption = Options()
foption.add_argument('-headless')
try:
browser = webdriver.Firefox(firefox_options=foption)
browser.get("https://yoururls")
browser.refresh()
browser.maximize_window()
#登陆的用户名密码写在和EXE同一文件夹的pwdss.txt文件内,各写一行
f=open("pwdss.txt","r")
lines=f.readlines()
usernames=lines[0]
passwords=lines[1]
f.close()
elem=browser.find_element_by_id("username")
elem.send_keys(usernames)
elem=browser.find_element_by_id("password")
elem.send_keys(passwords)
elem=browser.find_element_by_class_name('logins')
#这些用户名密码登陆按钮等名称根据具体页面的html元素来确定,一般通过查看HTML源代码获取
elem.click()
#time.sleep(5)
try:
elem=browser.find_element_by_css_selector('p[data-test]')
#检查的信息,这个范例在P标签内,就这样引用,然后再对比有没有希望看到的正常信息,如果没有,弹出WINDOWS消息告警
str1=elem.text
#系统如果正常无告警,上面这段P标签会返回包含"木有"这个字符串,否则页面上就是有告警信息
infos='木有'
if infos in str1:
timenow=time.localtime()
datenow = time.strftime('%Y-%m-%d %H:%M:%S', timenow)
print ("ok " + datenow)
file = open("log.html", "a")
file.write("okay "+datenow +"\n")
file.close()
#time.sleep(3)
browser.close()
#message_box("监控没有告警", "监控没有告警")
else:
timenow=time.localtime()
datenow = time.strftime('%Y-%m-%d %H:%M:%S', timenow)
print ("alert " + datenow)
file = open("log.html", "a")
file.write("alert "+datenow +"\n")
file.close()
#time.sleep(3)
browser.close()
message_box("监控有告警", "监控有告警")
except:
#如果不能正常获取这个P标签的值,也认为有告警
timenow=time.localtime()
datenow = time.strftime('%Y-%m-%d %H:%M:%S', timenow)
print ("alert " + datenow)
file = open("log.html", "a")
file.write("alert "+datenow + "\n")
file.close()
#time.sleep(3)
browser.close()
message_box("监控有告警", "监控有告警")
except:
timenow=time.localtime()
datenow = time.strftime('%Y-%m-%d %H:%M:%S', timenow)
file = open("log.html", "a")
file.write("browser fail "+datenow+"\n")
file.close()
#time.sleep(3)
browser.close()
message_box("打开浏览器不正常", "打开浏览器不正常")
三、执行的方式
跑这个程序最好的办法就先在代码time.sleep一个时间间隔重复执行,打包成EXE,然后再注册为WINDOWS后台服务的模式,可是WINDOWS10似乎不支持通过WINDOWS后台服务弹出消息框,这样只好打包一次性任务的EXE放在计划任务里面周期执行了,程序虽然会在前端跑,但浏览器会被隐藏,对当前用户的操作不会有影响
打包EXE的方法是安装PyInstaller模块,打开WINDOWS的命令行,再进入到pyinstaller所在的目录,执行pyinstaller -F c:\yourpyfilepath.py,有提示生成EXE的路径
为了任务方便调用又不用对环境变量等进行修改,打包好的exe文件和pwdss.txt等文件放到了C:\Windows\SysWOW64\这个目录
这是导出来为XML格式的WINDOWS计划任务
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2020-05-15T11:56:23.7610113</Date>
<Author>host01\admin</Author>
<URI>\msg</URI>
</RegistrationInfo>
<Triggers>
<CalendarTrigger>
<Repetition>
<Interval>PT30M</Interval>
<Duration>PT12H</Duration>
<StopAtDurationEnd>false</StopAtDurationEnd>
</Repetition>
<StartBoundary>2020-05-15T07:00:00</StartBoundary>
<Enabled>true</Enabled>
<ScheduleByDay>
<DaysInterval>1</DaysInterval>
</ScheduleByDay>
</CalendarTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>S-1-5-21-3427520612-787180917-2663887765-684061</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>true</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>C:\Windows\SysWOW64\fhtinfos.exe</Command>
</Exec>
</Actions>
</Task>