Files
nagios-plugins/check_gitea.py
2025-06-14 23:05:55 +02:00

147 lines
5.6 KiB
Python

#!/usr/bin/env python3
"""
Gitea Repository Check Script
This script verifies access to a Gitea repository by:
1. Authenticating with provided credentials
2. Checking repository availability
3. Verifying file access
Example usage:
./check_gitea.py --server gitea.example.com --repo-owner owner --repo-name repo --username user --password pass --file path/to/file.txt
"""
import requests
import argparse
import sys
from urllib.parse import quote
def debug_print(debug, message):
if debug:
print(f"DEBUG: {message}")
def check_gitea(server_address, repo_owner, repo_name, username, password, file_path, debug=False):
try:
file_path = file_path.lstrip('/')
base_url = f"https://{server_address}".rstrip('/')
session = requests.Session()
debug_print(debug, "Connecting to Gitea server...")
try:
response = session.get(base_url, timeout=10)
response.raise_for_status()
debug_print(debug, f"Gitea server available (HTTP {response.status_code})")
except requests.exceptions.RequestException as e:
print(f"CRITICAL - Could not connect to Gitea server: {str(e)}")
return 2
login_url = f"{base_url}/user/login"
debug_print(debug, f"Attempting login for user {username}...")
try:
response = session.get(login_url)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"CRITICAL - Could not load login page: {str(e)}")
return 2
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
csrf_token = soup.find('input', {'name': '_csrf'})
if not csrf_token:
print("CRITICAL - Could not find CSRF token on login page")
return 2
csrf_token = csrf_token['value']
debug_print(debug, f"Found CSRF token: {csrf_token}")
login_data = {
"user_name": username,
"password": password,
"_csrf": csrf_token
}
try:
response = session.post(login_url, data=login_data)
response.raise_for_status()
if "invalid username or password" in response.text.lower():
print("CRITICAL - Login failed: invalid username or password")
return 2
debug_print(debug, "Login successful")
except requests.exceptions.RequestException as e:
print(f"CRITICAL - Login error: {str(e)}")
return 2
repo_url = f"{base_url}/{repo_owner}/{repo_name}"
debug_print(debug, f"Checking repository {repo_owner}/{repo_name}...")
try:
response = session.get(repo_url)
if response.status_code == 404:
print(f"CRITICAL - Repository {repo_owner}/{repo_name} not found")
return 2
response.raise_for_status()
debug_print(debug, f"Repository {repo_owner}/{repo_name} is accessible")
except requests.exceptions.RequestException as e:
print(f"CRITICAL - Repository access error: {str(e)}")
return 2
file_url = f"{base_url}/{repo_owner}/{repo_name}/raw/branch/master/{quote(file_path)}"
debug_print(debug, f"Attempting to read file: {file_path}")
debug_print(debug, f"Full file URL: {file_url}")
try:
response = session.get(file_url)
debug_print(debug, f"HTTP response: {response.status_code}")
if response.status_code == 200:
if response.text:
print(f"OK - Successfully read file {file_path} from {repo_owner}/{repo_name}")
return 0
else:
print(f"WARNING - File {file_path} exists but is empty")
return 1
elif response.status_code == 404:
print(f"WARNING - File {file_path} not found in repository")
return 1
else:
print(f"CRITICAL - File read error (HTTP {response.status_code})")
return 2
except requests.exceptions.RequestException as e:
print(f"CRITICAL - File access error: {str(e)}")
return 2
except Exception as e:
print(f"CRITICAL - Unexpected error: {str(e)}")
return 2
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Verify Gitea repository and file access',
epilog='Example:\n'
'./check_gitea.py --server gitea.example.com --repo-owner owner \\\n'
'--repo-name repo --username user --password pass --file path/to/file.txt',
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument('--server', required=True, help='Gitea server address (e.g., gitea.example.com)')
parser.add_argument('--repo-owner', required=True, help='Repository owner username')
parser.add_argument('--repo-name', required=True, help='Repository name')
parser.add_argument('--username', required=True, help='Login username')
parser.add_argument('--password', required=True, help='Login password')
parser.add_argument('--file', required=True, help='File path in repository')
parser.add_argument('--debug', action='store_true', help='Enable debug output')
args = parser.parse_args()
sys.exit(check_gitea(
args.server,
args.repo_owner,
args.repo_name,
args.username,
args.password,
args.file,
args.debug
))