小试pyautogui操作windows上的GUI

需求场景:

大量的windows端上使用某公司的代理软件,不时会出现不可用的情况,多次反馈某公司无果,可又不能不用,只能是定期去重启一下。

想法:

使用Python的pyautogui模块替代手动登陆

实践:

1、由于国际链路问题,往往不能一次就成功登陆。再打开软件时和点击登陆时均可能出现几次不等的登陆失败提示,需要点击OK按钮确认。

2、程序会尝试进行五轮的登陆操作(使用对应的阶段的图片),期间检测到成功登陆则退出。

3、建脚本加入到开机启动(至于重启windows的任务就交给Ansible,将再其他文章进行详细说明)。

# -*- coding: utf-8 -*-
import os
import time
import subprocess
import pyautogui
def kill_proc(description, proc_name):
    try:
        print('终止%s进程...' % (description))
        os.system('taskkill /IM %s /F' % (proc_name))
    except Exception as reason:
        print(e)
def run_proc(description, proc_name):
    try:
        print('启动%s进程...' % (description))
        subprocess.Popen("%s" % (proc_name))
        time.sleep(8)
    except Exception as reason:
        print('启动进程失败!!\n错误的原因是:' + str(reason))
        os._exit(0)
def check_img(description, img_name):
    try:
        print('查找%s图像' % (description))
        button = pyautogui.locateOnScreen("%s" % (img_name))
        print(button)
        if description == 'Success':
            return 1
        if button:
            print('点击%s图像' % (description))
            button_center = pyautogui.center(button)
            pyautogui.click(button_center)
            time.sleep(1)
    except BaseException:
        print('没有找到%s图像' % (description))
        return 0
if __name__ == '__main__':
    count = 1
    kill_proc('911', 'Client.exe')
    run_proc('911', r'C:\911S5 2018-05-23 fixed\Client.exe')
    for i in range(5):
        print('=====进行第%s轮检查=====' % (count))
        count += 1
        check_img('OK1', 'C:\\restart911\\error_OK1.PNG')
        check_img('OK2', 'C:\\restart911\\error_OK2.PNG')
        check_img('Login', 'C:\\restart911\\Login.PNG')
        time.sleep(5)
        if check_img('Success', 'C:\\restart911\\success.PNG'):
            print('执行成功!!')
            break

运行演示:

image.png

存在的问题:

有多台需要运行此脚本,缺少汇总反馈机制。

如果五轮过后还没登陆上,一般就是登陆不上了,还需要查别的原因,可以将失败的结果通过邮件发送到管理员邮箱。

猜你喜欢

转载自blog.51cto.com/9473774/2358065