当前位置: 首页 > article >正文

运维-自动访问系统并截图

需求背景

因项目甲方要求需要对系统进行巡检,由于系统服务器较多,并且已经采用Prometheus+Grafana对系统服务器进行管理,如果要完成该任务,需要安排一个人力对各个系统和服务器进行一一截图等操作,费时费力,因此考虑开发一个脚本自动访问各个服务器的CPU、内存等页面并自动截图保存功能。

解决方案

在网上搜了一下,Python提供相关的功能,过程记录如下:

Python版本

C:\Users\admin\Desktop>python -V
Python 3.12.7

安装插件

(1)安装selenium库来控制浏览器,以及Pillow库来处理图像,执行:pip install selenium pillow
(2)打开命令行工具(如CMD、Terminal或PowerShell),运行以下命令来安装webdriver_manager:pip install webdriver-manager

测试代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from PIL import Image
import time
import io

# 设置ChromeDriver的路径(如果使用webdriver_manager,则无需手动下载和设置路径)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)

try:
    # 设置窗口大小,方法可行
    driver.set_window_size(1920, 1080)  # 这里设置窗口大小为1920x1080

    # 访问指定网页
    driver.get('http://192.168.1.1/login')

    # 增加Cookie,避免停留在登录页面,这里的cookie信息,可以通过访问一次grafana获取
    driver.add_cookie({'name': 'grafana_session', 'value': 'd6847db416b74d5111bea92dbf0b2bdd'})
    
    # 访问指定网页
    driver.get('http://192.168.1.1/d/aka/cimdi-xia-kong-jian?orgId=1&from=now-7d&to=now&var-vendor=&var-account=&var-group=All&var-name=All&var-instance=192.168.1.2&var-interval=2m&var-total=17&var-device=All&var-maxmount=%2Fdata&var-show_name=&var-iid=&var-sname=&viewPanel=7')

    # 等待网页加载(可选,根据需要调整)
    time.sleep(2)

    # 对网页进行截图
    screenshot = driver.get_screenshot_as_png()

    # 使用Pillow库保存截图
    img = Image.open(io.BytesIO(screenshot))
    img.save('screenshot.png')

    # 显示截图后的图像(可选)
    img.show()

finally:
    # 关闭浏览器
    driver.quit()

当需要访问多个页面并生成多张图片时,优化代码如下:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from PIL import Image
import time
import io

# 设置ChromeDriver的路径(如果使用webdriver_manager,则无需手动下载和设置路径)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)

try:

    # 设置窗口大小,方法可行
    driver.set_window_size(1920, 1080)  # 这里设置窗口大小为1920x1080

    # 访问指定网页
    driver.get('http://192.168.1.1/login')

    # 增加Cookie
    driver.add_cookie({'name': 'grafana_session', 'value': 'd6847db416b74d5111bea92dbf0b2bdd'})
    
    for number in range(1, 50):
        # 访问指定网页
        url = 'http://192.168.1.1/d/aka/cimdi-xia-kong-jian?orgId=1&from=now-7d&to=now&var-vendor=&var-account=&var-group=All&var-name=All&var-instance=192.168.1.{}&var-interval=2m&var-total=17&var-device=All&var-maxmount=%2Fdata&var-show_name=&var-iid=&var-sname=&viewPanel=7'.format(number)
        driver.get(url)
        # 等待网页加载(可选,根据需要调整)
        time.sleep(2)
        # 对网页进行截图
        screenshot = driver.get_screenshot_as_png()
        # 使用Pillow库保存截图
        img = Image.open(io.BytesIO(screenshot))
        img.save('cpu-{}.png'.format(number))
finally:
    # 关闭浏览器
    driver.quit()

执行代码

执行命令python test.py后就会自动截图,这里需要强调一下,这里需要科学上网,否则执行容易报错,且报错信息如下:

C:\Users\admin\Desktop>python test.py
urllib3.exceptions.SSLError: [SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1000)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\AppData\Python\Python312\Lib\site-packages\requests\adapters.py", line 667, in send
    resp = conn.urlopen(
           ^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\urllib3\connectionpool.py", line 843, in urlopen
    retries = retries.increment(
              ^^^^^^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\urllib3\util\retry.py", line 519, in increment
    raise MaxRetryError(_pool, url, reason) from reason  # type: ignore[arg-type]
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='googlechromelabs.github.io', port=443): Max retries exceeded with url: /chrome-for-testing/latest-patch-versions-per-build.json (Caused by SSLError(SSLEOFError(8, '[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1000)')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\AppData\Python\Python312\Lib\site-packages\webdriver_manager\core\http.py", line 32, in get
    resp = requests.get(
           ^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\requests\api.py", line 73, in get
    return request("get", url, params=params, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\requests\api.py", line 59, in request
    return session.request(method=method, url=url, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\requests\sessions.py", line 589, in request
    resp = self.send(prep, **send_kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\requests\sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\requests\adapters.py", line 698, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='googlechromelabs.github.io', port=443): Max retries exceeded with url: /chrome-for-testing/latest-patch-versions-per-build.json (Caused by SSLError(SSLEOFError(8, '[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1000)')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\admin\Desktop\test.py", line 9, in <module>
    service = Service(ChromeDriverManager().install())
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\webdriver_manager\chrome.py", line 40, in install
    driver_path = self._get_driver_binary_path(self.driver)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\webdriver_manager\core\manager.py", line 35, in _get_driver_binary_path
    binary_path = self._cache_manager.find_driver(driver)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\webdriver_manager\core\driver_cache.py", line 107, in find_driver
    driver_version = self.get_cache_key_driver_version(driver)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\webdriver_manager\core\driver_cache.py", line 154, in get_cache_key_driver_version
    return driver.get_driver_version_to_download()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\webdriver_manager\core\driver.py", line 48, in get_driver_version_to_download
    return self.get_latest_release_version()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\webdriver_manager\drivers\chrome.py", line 59, in get_latest_release_version
    response = self._http_client.get(url)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\AppData\Python\Python312\Lib\site-packages\webdriver_manager\core\http.py", line 35, in get
    raise exceptions.ConnectionError(f"Could not reach host. Are you offline?")
requests.exceptions.ConnectionError: Could not reach host. Are you offline?

C:\Users\admin\Desktop>

截图效果如下所示:
在这里插入图片描述


http://www.kler.cn/a/548192.html

相关文章:

  • DeepSeek24小时写作机器人,持续创作高质量文案
  • 医院数智化转型下的大健康发展AI化多路径探析(上)
  • 【R语言】回归分析
  • 【C++内存管理】—— 策略、陷阱及应对之道
  • Qt工作总结03 <qSort按某一属性进行排序>
  • 解析 2025 工业边缘计算:三大技术风向的影响力
  • QEMU 搭建 Ubuntu x86 虚拟机
  • 力扣-二叉树-257 二叉树的所有路径
  • 关于Redis的主从复制(上)
  • LabVIEW 天然气水合物电声联合探测
  • excel中单元格字符串提取数字累加
  • stable diffusion 文生图流程
  • 认识与安装git
  • Android设备 网络安全检测
  • 10款视频无损压缩软件介绍(deepseek汇总)
  • 【ISO 14229-1:2023 UDS诊断全量测试用例清单系列:第二节】
  • 算法17(力扣217)存在重复元素
  • DeepSeek 助力 Vue 开发:打造丝滑的面包屑导航(Breadcrumbs)
  • 【ARM】解决ArmDS Fast Models 中部分内核无法上电的问题
  • c#自动更新-源码