---
title: "Scrapy Rotating Proxies Middleware: Tăng cường bảo mật, phân quyền và thiết lập giám sát cảnh báo"
description: "Hướng dẫn bảo mật thông tin xác thực proxy trong Scrapy Rotating Proxies Middleware, phân quyền user Linux chạy crawler và gửi cảnh báo tỷ lệ proxy chết về Telegram."
canonical: "https://thuecloud.vn/scrapy-rotating-proxies-middleware-tang-cuong-bao-mat-phan-quyen-va-thiet-lap-giam-sat-canh-bao"
markdown_url: "https://thuecloud.vn/scrapy-rotating-proxies-middleware-tang-cuong-bao-mat-phan-quyen-va-thiet-lap-giam-sat-canh-bao.md"
locale: "vi"
kind: "article"
published_at: "2026-11-22T16:18:24.366Z"
updated_at: "2026-11-22T16:18:22.184Z"
site: "ThueCloud.Vn"
estimated_tokens: 2262
---
# Scrapy Rotating Proxies Middleware: Tăng cường bảo mật, phân quyền và thiết lập giám sát cảnh báo

> Hướng dẫn bảo mật thông tin xác thực proxy trong Scrapy Rotating Proxies Middleware, phân quyền user Linux chạy crawler và gửi cảnh báo tỷ lệ proxy chết về Telegram.

- Canonical HTML: https://thuecloud.vn/scrapy-rotating-proxies-middleware-tang-cuong-bao-mat-phan-quyen-va-thiet-lap-giam-sat-canh-bao
- Markdown URL: https://thuecloud.vn/scrapy-rotating-proxies-middleware-tang-cuong-bao-mat-phan-quyen-va-thiet-lap-giam-sat-canh-bao.md
- Organization: ThueCloud.Vn
- Support Email: support@thuecloud.vn
- Hotline: 03333 499 48
- Published: 2026-11-22
- Updated: 2026-11-22

## Mục lục

- Phân quyền hệ thống và Bảo vệ thông tin Proxy
- Viết Scrapy Extension giám sát Proxy và cảnh báo Telegram
- Câu hỏi thường gặp (FAQ)
  - Nên dùng xác thực Proxy bằng IP Whitelist hay User/Pass trên VPS?
  - Làm sao ẩn thông tin Proxy khỏi file log khi Scrapy in ra lỗi Request?
  - Extension ProxyHealthMonitor có làm chậm tốc độ crawl của Scrapy không?

Khi triển khai hệ thống crawl dữ liệu dùng **Scrapy Rotating Proxies Middleware** trên [VPS Việt Nam](https://thuecloud.vn/vps-viet-nam) hoặc máy chủ dùng chung cho nhiều thành viên, hai rủi ro bảo mật thường bị bỏ qua là: lưu cứng mật khẩu [Proxy Việt Nam](https://thuecloud.vn/proxy-viet-nam) / [Proxy USA](https://thuecloud.vn/proxy-usa) dưới dạng văn bản thuần trong tệp `settings.py` (dễ lộ khi đẩy lên Git) và chạy crawler bằng quyền `root`. Đồng thời, nếu không có cảnh báo sớm khi tỷ lệ proxy hỏng vượt ngưỡng, bạn có thể mất trắng cả một đêm chạy dữ liệu.

> **Tóm tắt nhanh (TL;DR):**
> - Nạp danh sách proxy từ tệp riêng ngoài Git (`.env` hoặc `/etc/crawler/proxies.txt`) với quyền `chmod 600` chỉ cho user dịch vụ đọc.
> - Tạo user Linux không có quyền `sudo` (như `scrapy_svc`) để cô lập tiến trình crawl.
> - Viết một **Scrapy Extension** nhẹ theo dõi `rotating_proxies/dead` và bắn cảnh báo Telegram ngay khi tỷ lệ proxy sống tụt dưới 50%.
> - *Cập nhật: 11/2026*

## 1. Phân quyền hệ thống và Bảo vệ thông tin Proxy

Tuyệt đối không chạy `scrapy crawl` dưới quyền `root`. Hãy tạo một tài khoản dịch vụ riêng và khóa quyền truy cập tệp chứa mật khẩu proxy:

```bash
sudo useradd -r -m -s /bin/bash scrapy_svc
sudo mkdir -p /etc/scrapy_secrets
sudo touch /etc/scrapy_secrets/proxies.txt
sudo chown scrapy_svc:scrapy_svc /etc/scrapy_secrets/proxies.txt
sudo chmod 600 /etc/scrapy_secrets/proxies.txt
```

Trong `settings.py`, đọc đường dẫn từ biến môi trường thay vì hardcode:

```python
import os
ROTATING_PROXY_LIST_PATH = os.environ.get('PROXY_LIST_FILE', '/etc/scrapy_secrets/proxies.txt')
```

| Lớp bảo vệ | Rủi ro nếu bỏ qua | Biện pháp triển khai chuẩn |
| --- | --- | --- |
| Quyền User chạy Spider | Lỗi bảo mật thư viện cho phép ghi đè file hệ thống | Chạy qua user `scrapy_svc` không có `sudo` |
| Tệp `proxies.txt` | Lộ user/pass proxy lên GitHub/GitLab | Lưu ngoài repo tại `/etc/scrapy_secrets/`, `chmod 600` |
| Log Scrapy (`DEBUG`) | Log ghi lại header `Proxy-Authorization` | Dùng `LOG_LEVEL = 'INFO'` trên Production |

## 2. Viết Scrapy Extension giám sát Proxy và cảnh báo Telegram

Tạo tệp `extensions.py` trong dự án Scrapy để kiểm tra định kỳ các chỉ số từ `crawler.stats` và gửi cảnh báo nếu toàn bộ proxy gặp sự cố:

```python
import urllib.request, urllib.parse, os
from scrapy import signals
from twisted.internet import task

class ProxyHealthMonitor:
    def __init__(self, stats, token, chat_id):
        self.stats = stats
        self.token = token
        self.chat_id = chat_id
        self.alerted = False

    @classmethod
    def from_crawler(cls, crawler):
        ext = cls(
            crawler.stats,
            os.environ.get('TG_BOT_TOKEN'),
            os.environ.get('TG_CHAT_ID')
        )
        crawler.signals.connect(ext.spider_opened, signal=signals.spider_opened)
        crawler.signals.connect(ext.spider_closed, signal=signals.spider_closed)
        return ext

    def spider_opened(self, spider):
        self.loop = task.LoopingCall(self.check_health, spider.name)
        self.loop.start(120.0, now=False)

    def check_health(self, name):
        good = self.stats.get_value('rotating_proxies/good', 0)
        dead = self.stats.get_value('rotating_proxies/dead', 0)
        total = good + dead
        if total > 0 and (good / total) < 0.5 and not self.alerted:
            self.send_tg(f"[ALERT] Spider {name}: Proxy song chi con {good}/{total}!")
            self.alerted = True

    def spider_closed(self, spider):
        if hasattr(self, 'loop') and self.loop.running:
            self.loop.stop()

    def send_tg(self, msg):
        if not self.token or not self.chat_id: return
        url = f"https://api.telegram.org/bot{self.token}/sendMessage"
        data = urllib.parse.urlencode({'chat_id': self.chat_id, 'text': msg}).encode()
        urllib.request.urlopen(url, data=data, timeout=5)
```

Kích hoạt extension trong `settings.py`:

```python
EXTENSIONS = {
    'price_crawler.extensions.ProxyHealthMonitor': 500,
}
```

Để hoàn thiện kỹ năng vận hành, bạn có thể tham khảo thêm quy trình gỡ lỗi khi nhận được cảnh báo trong [Scrapy Rotating Proxies Middleware: Phân tích lỗi thường gặp và quy trình xử lý sự cố nhanh](https://thuecloud.vn/scrapy-rotating-proxies-middleware-phan-tich-loi-thuong-gap-va-quy-trinh-xu-ly-su-co-nhanh) hoặc đọc bài [Scrapy Rotating Proxies Middleware: Kinh nghiệm vận hành thực tế và so sánh phương án thay thế](https://thuecloud.vn/scrapy-rotating-proxies-middleware-kinh-nghiem-van-hanh-thuc-te-va-so-sanh-phuong-an-thay-the).

> **An tâm vận hành dữ liệu với ThueCloud.Vn:**
> **ThueCloud.Vn** cung cấp **Proxy VN/USA** sạch từ `70.000đ/tháng` hỗ trợ cả xác thực User/Pass lẫn Whitelist IP VPS giúp bạn loại bỏ hoàn toàn nỗi lo lộ mật khẩu trong file cấu hình. Kết hợp cùng hạ tầng Cloud VPS KVM Enterprise NVMe tại `vn-hn` (VAT `0%`, SLA `99,9%`, hoàn tiền `07 ngày`) với **VPS VN 1** (`45.000đ`/`60.000đ`) hoặc **VPS VN 2** (`78.000đ`/`90.000đ`). Xem chi tiết tại [bảng giá ThueCloud](https://thuecloud.vn/pricing).

## Câu hỏi thường gặp (FAQ)

### Nên dùng xác thực Proxy bằng IP Whitelist hay User/Pass trên VPS?
Nếu bạn chạy Scrapy trên một hoặc vài VPS có IP tĩnh cố định (như VPS tại ThueCloud.Vn), **IP Whitelist** là phương án bảo mật và tiện lợi nhất vì bạn không cần lưu bất kỳ mật khẩu nào trong tệp `proxies.txt`.

### Làm sao ẩn thông tin Proxy khỏi file log khi Scrapy in ra lỗi Request?
Mặc định khi ở mức `INFO`, Scrapy không in chi tiết header `Proxy-Authorization`. Tuy nhiên, nếu bạn bật `DEBUG` hoặc ghi log `request.meta['proxy']`, hãy tránh ghi chuỗi mật khẩu bằng cách dùng `urllib.parse` cắt bỏ phần `user:pass@` trước khi log.

### Extension `ProxyHealthMonitor` có làm chậm tốc độ crawl của Scrapy không?
Không. `LoopingCall` chạy kiểm tra bộ đếm trong RAM mỗi 120 giây (tốn chưa tới 0.1ms) và chỉ thực hiện 1 HTTP call tới Telegram khi phát hiện sự cố thực sự.

## References / Sources

- https://docs.scrapy.org/en/latest/topics/extensions.html
- https://core.telegram.org/bots/api#sendmessage

---

## Navigation & Machine-Readable Endpoints

- [Site Summary (llms.txt)](https://thuecloud.vn/llms.txt)
- [Full Technical Reference (llms-full.txt)](https://thuecloud.vn/llms-full.txt)
- [Pricing Catalog (Markdown)](https://thuecloud.vn/pricing.md)
- [Blog & Technical Guides (Markdown)](https://thuecloud.vn/blog.md)
- [XML Sitemap](https://thuecloud.vn/sitemap.xml)
