Intro
Today, we’ll dive into the Python script we posted yesterday that monitors website availability and sends alerts through Slack.
Core Components and Setup
The script is built around a WebsiteMonitor
class that handles all the monitoring functionality. Let’s break down its key components:
Initial Setup and Dependencies
The script uses several important Python libraries:
requests
for making HTTP requestssocks
for SOCKS proxy support (used with Tor)datetime
for time-based operationsjson
for configuration handling
The WebsiteMonitor Class
The class initializes with two separate request sessions:
def __init__(self, slack_webhook_url):
self.slack_webhook_url = slack_webhook_url
self.sites = {}
# Two separate sessions for different types of sites
self.regular_session = requests.Session()
self.tor_session = requests.Session()
# Configure Tor session with SOCKS proxy
self.tor_session.proxies = {
'http': 'socks5h://127.0.0.1:9050',
'https': 'socks5h://127.0.0.1:9050'
}
This dual-session approach is clever – it maintains one session for regular websites and another for .onion addresses through Tor, allowing the monitor to check both regular websites and Tor hidden services.
How the Monitoring Works
Site Management
The script maintains a dictionary of sites with their status:
self.sites[url] = {
'failures': 0,
'last_check': None,
'alerted': False
}
Each site entry tracks:
- Number of consecutive failures
- Timestamp of the last check
- Whether an alert has been sent
Site Checking Logic
The check_site
method handles the actual verification:
- It determines which session to use based on the URL (.onion or regular)
- Makes a request with a realistic user agent
- Sets a 30-second timeout to avoid hanging
- Considers a site “up” if it returns a 200 status code
Alert System
The monitoring system has two types of alerts:
- Failure Alerts: Triggered every three consecutive failures
if self.sites[url]['failures'] % 3 == 0:
self.send_slack_alert(url)
- Daily Status Reports: Sent every 24 hours, showing the status of all monitored sites
if (current_time - self.last_status_report).total_seconds() >= 86400:
self.send_daily_report()
Slack Integration
The Slack alerts are formatted with helpful emojis and site information:
- 🚨 for failure alerts
- 📊 for daily reports
- ✅ for up status
- ❌ for down status
Configuration and Usage
The script uses a JSON configuration file for flexibility:
{
"slack_webhook_url": "YOUR_SLACK_WEBHOOK_URL",
"sites": [
{
"url": "https://example.com",
"comment": "Main website"
}
]
}
This approach allows easy modification of monitored sites without changing the code.
Error Handling and Robustness
The script includes several robust error handling features:
- SSL verification is disabled to handle sites with invalid certificates
- Comprehensive exception handling for network issues
- Configuration validation at startup
- Proper handling of missing or invalid configuration files
The Monitoring Loop
The main monitoring loop runs continuously:
- Checks each site in the configuration
- Updates failure counts and sends alerts if needed
- Resets failure counts when sites recover
- Waits for an hour before the next check cycle
Beyond the Basics
Some advanced features worth noting:
- Tor Support: The ability to monitor .onion sites makes this tool valuable for organizations running hidden services
- Flexible Timing: The hour-long wait between checks and three-failure alert threshold can be easily modified
- Detailed Logging: Console output helps track the monitor’s operation
- Clean Exit Handling: Proper system exit codes for different error conditions
Conclusion
This website monitor is a practical example of how to build a robust monitoring system with Python. It demonstrates several important concepts:
- Session management for different types of requests
- Proper error handling and logging
- Configuration-driven design
- Integration with external services (Slack)
- Support for both regular and Tor hidden services
The script’s modular design makes it easy to extend with additional features like different notification methods or more detailed status reporting.