Files
hostpanel/ssh_manager/utils.py
ilkeral f4ee7a2d0b yeni
2025-08-08 07:24:25 +03:00

237 lines
9.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from .models import SSHLog, Project
from django.utils import timezone
import logging
import os
import tempfile
import requests
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
# Yardımcı fonksiyonlar buraya gelebilir
def check_disk_usage(project):
"""
Proje klasörünün disk kullanımını kontrol eder ve günceller
"""
from .ssh_client import SSHManager
result_messages = []
try:
if not project.ssh_credential:
return False, "SSH bilgisi eksik"
ssh_manager = SSHManager(project.ssh_credential)
if not ssh_manager.check_connection():
return False, "SSH bağlantısı kurulamadı"
# Proje klasörünün tam yolu
base_path = project.ssh_credential.base_path.rstrip('/')
folder_name = project.folder_name.strip('/')
full_path = f"{base_path}/{folder_name}"
# Debug bilgisi ekle
result_messages.append(f"Kontrol edilen path: {full_path}")
# Önce base path'in var olup olmadığını kontrol et
base_check_command = f"test -d '{base_path}' && echo 'BASE_EXISTS' || echo 'BASE_NOT_EXISTS'"
stdout_base, stderr_base, success_base = ssh_manager.execute_command(base_check_command)
if not (success_base and stdout_base.strip() == 'BASE_EXISTS'):
ssh_manager.close()
return False, f"Base path bulunamadı: {base_path}"
# Base path var, şimdi proje klasörünü kontrol et
# Önce base path içindeki klasörleri listele
list_command = f"ls -la '{base_path}' | grep '^d'"
stdout_list, stderr_list, success_list = ssh_manager.execute_command(list_command)
if success_list:
result_messages.append(f"Base path içindeki klasörler: {stdout_list.strip()[:200]}")
# Proje klasörünü kontrol et
check_command = f"test -d '{full_path}' && echo 'EXISTS' || echo 'NOT_EXISTS'"
stdout_check, stderr_check, success_check = ssh_manager.execute_command(check_command)
if not (success_check and stdout_check.strip() == 'EXISTS'):
ssh_manager.close()
return False, f"Proje klasörü bulunamadı: {full_path}"
# Disk kullanımını al
command = f"du -sh '{full_path}' 2>/dev/null | cut -f1"
stdout, stderr, success = ssh_manager.execute_command(command)
if success and stdout.strip():
old_usage = project.disk_usage or "Bilinmiyor"
project.disk_usage = stdout.strip()
project.save() # Veritabanına kaydet
result_messages.append(f"Disk kullanımı güncellendi: {old_usage}{project.disk_usage}")
ssh_manager.close()
return True, "; ".join(result_messages)
else:
ssh_manager.close()
return False, "Disk kullanımı komutu başarısız"
except Exception as e:
if 'ssh_manager' in locals() and ssh_manager:
ssh_manager.close()
return False, f"Disk kontrolü hatası: {str(e)}"
def check_site_status(project):
"""
Projenin web sitesinin aktif olup olmadığını kontrol eder
SADECE meta key doğrulaması ile site aktifliği belirlenir
"""
result_messages = []
# Site durumunu kontrol et
if not project.url:
project.last_site_check = timezone.now()
project.save()
return False, "URL eksik"
# Meta key kontrolü zorunlu
if not project.meta_key:
project.is_site_active = False
project.last_site_check = timezone.now()
project.save()
return False, "Meta key tanımlanmamış - Site doğrulaması için meta key gerekli"
try:
# URL'yi düzenle
url = project.url
if not url.startswith(('http://', 'https://')):
url = f'http://{url}'
# Site kontrolü - sadece erişilebilirlik için
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
# Site erişilebilir, şimdi ZORUNLU meta key kontrolü yapalım
try:
# HTML içeriğini parse et
soup = BeautifulSoup(response.content, 'html.parser')
# Meta tag'i farklı formatlarda ara
meta_tags = []
meta_tags.append(soup.find('meta', attrs={'name': 'site-verification'}))
meta_tags.append(soup.find('meta', attrs={'name': 'site-verify'}))
meta_tags.append(soup.find('meta', attrs={'name': 'verification'}))
# HTML içeriğinde meta key'i doğrudan ara
html_content = response.text
meta_key_in_html = project.meta_key in html_content
# Debug bilgisi ekle
result_messages.append(f"HTML içeriğinde meta key aranıyor: {project.meta_key}")
result_messages.append(f"HTML içeriğinde meta key bulundu: {meta_key_in_html}")
# Bulunan meta tag'leri kontrol et
found_meta_tag = None
for i, tag in enumerate(meta_tags):
if tag:
result_messages.append(f"Meta tag bulundu: {tag}")
if tag.get('content') and project.meta_key in tag.get('content'):
found_meta_tag = tag
result_messages.append(f"Meta key, meta tag içeriğinde doğrulandı")
break
# Tüm meta tag'lerde içerik kontrolü yap
if not found_meta_tag:
all_meta_tags = soup.find_all('meta')
for tag in all_meta_tags:
content = tag.get('content')
if content and project.meta_key in content:
found_meta_tag = tag
result_messages.append(f"Meta key, '{tag.get('name', 'isimsiz')}' meta tag'de bulundu")
break
# HTML yorum kontrolü (<!-- site-verification: key --> formatı için)
comment_pattern = f'<!-- site-verification: {project.meta_key} -->'
comment_found = comment_pattern in html_content
if comment_found:
result_messages.append("Meta key HTML yorum olarak bulundu")
# Meta key doğrulaması - ZORUNLU
if found_meta_tag or meta_key_in_html or comment_found:
# Meta key doğrulandı - Site AKTIF
project.is_site_active = True
project.last_site_check = timezone.now()
project.save()
if found_meta_tag:
return True, f"✅ Site AKTIF - Meta key meta tag'de doğrulandı"
elif comment_found:
return True, f"✅ Site AKTIF - Meta key HTML yorumunda doğrulandı"
else:
return True, f"✅ Site AKTIF - Meta key HTML içeriğinde doğrulandı"
else:
# Meta key bulunamadı - Site PASİF
project.is_site_active = False
project.last_site_check = timezone.now()
project.save()
return False, f"❌ Site PASİF - Site erişilebilir (HTTP {response.status_code}) ancak meta key doğrulanamadı"
except Exception as e:
# Meta key kontrolünde hata - Site PASİF
project.is_site_active = False
project.last_site_check = timezone.now()
project.save()
return False, f"❌ Site PASİF - Meta key kontrolü hatası: {str(e)}"
else:
# Site erişilemez - Site PASİF
project.is_site_active = False
project.last_site_check = timezone.now()
project.save()
return False, f"❌ Site PASİF - Site erişilemez (HTTP {response.status_code})"
except requests.exceptions.Timeout:
project.is_site_active = False
project.last_site_check = timezone.now()
project.save()
return False, "❌ Site PASİF - Zaman aşımı hatası"
except requests.exceptions.ConnectionError as e:
project.is_site_active = False
project.last_site_check = timezone.now()
project.save()
# DNS çözümleme hatası kontrolü
error_str = str(e)
if "NameResolutionError" in error_str or "getaddrinfo failed" in error_str:
return False, f"❌ Site PASİF - Domain '{project.url}' DNS kayıtlarında bulunamadı"
else:
return False, f"❌ Site PASİF - Bağlantı hatası: {str(e)}"
except Exception as e:
project.is_site_active = False
project.last_site_check = timezone.now()
project.save()
return False, f"❌ Site PASİF - Genel hata: {str(e)}"
def check_all_sites():
"""Tüm projelerin site durumunu kontrol et"""
projects = Project.objects.filter(url__isnull=False).exclude(url='')
results = []
for project in projects:
site_status, site_message = check_site_status(project)
disk_status, disk_message = check_disk_usage(project)
results.append({
'project': project,
'status': site_status, # Site durumunu ana durum olarak kullan
'site_message': site_message,
'disk_status': disk_status,
'disk_message': disk_message,
'combined_message': f"Site: {site_message} | Disk: {disk_message}"
})
return results