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

需求背景

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

解决方案

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

Python版本

bash 复制代码
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

测试代码

python 复制代码
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()

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

python 复制代码
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后就会自动截图,这里需要强调一下,这里需要科学上网,否则执行容易报错,且报错信息如下:

python 复制代码
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>

截图效果如下所示:

相关推荐
喵手7 分钟前
Python爬虫实战:用代码守护地球,追踪WWF濒危物种保护动态!
爬虫·python·爬虫实战·濒危物种·零基础python爬虫教学·wwf·濒危物种保护动态追踪
梦想的旅途28 分钟前
如何通过 QiWe API 实现企业微信主动发消息
开发语言·python
喵手13 分钟前
Python爬虫实战:自动化抓取 Pinterest 热门趋势与创意!
爬虫·python·爬虫实战·pinterest·零基础python爬虫教学·采集pinterest热门趋势·热门趋势预测
凌晨一点的秃头猪18 分钟前
Python文件操作
开发语言·python
小张贼嚣张28 分钟前
数据分析全流程实战:Python(Pandas/Matplotlib/Numpy)+ MySQL(附可下载数据源+多图形绘制)
python·数据分析·pandas
努力的小白o(^▽^)o36 分钟前
面向课堂考勤场景的桌面端人脸识别签到系统
python·人脸识别
Johnstons1 小时前
读懂 TCP 标志位:网络运维中的“信号灯”
运维·网络·tcp/ip
坚定的共产主义生产设备永不宕机1 小时前
网络层协议(IPV4报头)
运维·服务器·网络
weixin_505154461 小时前
Bowell Studio:重塑工业互联网时代的装配制造与运维检修
运维·数据库·人工智能·制造·数字孪生·3d产品配置器·3d交互展示
sa100271 小时前
淘宝商品详情 API 接口开发实战:item_detail 调用、参数与 Python 示例
linux·数据库·python