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

需求背景

因项目甲方要求需要对系统进行巡检,由于系统服务器较多,并且已经采用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>

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

### 大数据平台中 Hive 的运维测评与最佳实践 #### 1. Hive 运维的核心关注点 Hive 是一种基于 Hadoop 的分布式数据分析工具,其运维过程中需要重点关注以下几个方面[^1]: - **性能优化**:通过调整查询语句、分区设计以及压缩算法等方式提升查询效率。 - **资源管理**:合理分配 YARN 或 Spark 集群中的计算资源,防止因资源争抢而导致的任务失败。 - **元数据管理**:定期清理无用的表和分区,减少 Metastore 数据库的压力。 #### 2. 性能调优的最佳实践 为了提高 Hive 查询的执行速度,可以采取以下措施[^1]: - 使用合适的文件格式(如 ORC 或 Parquet),这些列式存储格式能够显著降低 I/O 开销。 - 启用谓词下推功能,在读取数据之前就过滤掉不必要的记录。 - 设置合理的行度参数 `hive.exec.parallel` 和 `mapreduce.job.reduces` 来平衡负载分布。 #### 3. 资源调度策略 在大规模生产环境中,良好的资源调度机制至关重要。推荐采用 Fair Scheduler 或 Capacity Scheduler 对不同优先级的工作流进行隔离处理[^2]: - 定义清晰的服务级别协议(SLA),确保高优先级任务获得足够的计算能力支持。 - 动态扩展节点数量以应对突发流量高峰情况下的需求激增现象。 #### 4. 元数据治理方案 随着时间积累,数据库内的对象数目会快速增长从而影响整体表现效果因此有必要实施有效的元数据管控手段包括但不限于如下几点建议: - 自动化检测长期未被访问过的表格或者分片且提示管理员考虑删除操作. - 利用 ACID 特性实现事务级别的更新控制使得修改过程更加安全可靠. ```sql -- 示例 SQL: 创建带有分区的外部表 CREATE EXTERNAL TABLE IF NOT EXISTS sales_data ( order_id STRING, product_name STRING, quantity INT, price FLOAT ) PARTITIONED BY (year INT, month INT) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' STORED AS TEXTFILE LOCATION '/user/hive/warehouse/sales'; ``` #### 5. 日志监控体系构建 建立健全的日志收集分析框架可以帮助快速定位问题根源所在同时也有助于预防潜在风险的发生概率增加系统稳定性水平达到预期目标值范围内保持正常运转状态不变形不损坏等功能特性得以充分体现出来.[^1] ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

angushine

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值