initial
This commit is contained in:
112
scripts/common.py
Normal file
112
scripts/common.py
Normal file
@@ -0,0 +1,112 @@
|
||||
# common.py
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
import platform
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
def get_host_ip():
|
||||
"""Получает IP-адрес хоста в локальной сети"""
|
||||
try:
|
||||
# Для WSL2 получаем IP хоста (Windows)
|
||||
if 'microsoft' in platform.uname().release.lower():
|
||||
# В WSL2 получаем IP хоста из файла resolv.conf
|
||||
with open('/etc/resolv.conf', 'r') as f:
|
||||
for line in f:
|
||||
if line.startswith('nameserver'):
|
||||
return line.split()[1]
|
||||
# Для других систем используем подключение к внешнему серверу
|
||||
else:
|
||||
import socket
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.connect(("8.8.8.8", 80))
|
||||
ip = s.getsockname()[0]
|
||||
s.close()
|
||||
return ip
|
||||
except Exception as e:
|
||||
print(f"Не удалось получить IP-адрес хоста: {e}")
|
||||
# Возвращаем IP по умолчанию, если не удалось получить
|
||||
return "192.168.31.60"
|
||||
|
||||
def read_services_config():
|
||||
"""Читает конфигурацию сервисов из файла"""
|
||||
config_path = Path.home() / "projects" / "docker" / "network" / "services.json"
|
||||
default_config = {
|
||||
"services": [
|
||||
{"name": "gitea", "port": 3000},
|
||||
{"name": "youtrack", "port": 8080},
|
||||
{"name": "n8n", "port": 5678}
|
||||
]
|
||||
}
|
||||
|
||||
if config_path.exists():
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
else:
|
||||
# Создаем файл конфигурации по умолчанию
|
||||
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(config_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(default_config, f, indent=2, ensure_ascii=False)
|
||||
return default_config
|
||||
|
||||
def generate_dnsmasq_config():
|
||||
"""Генерирует конфигурационный файл dnsmasq"""
|
||||
host_ip = get_host_ip()
|
||||
services = read_services_config()
|
||||
|
||||
config_content = f"""# Локальные домены → твой ПК
|
||||
"""
|
||||
for service in services['services']:
|
||||
config_content += f"address=/{service['name']}.local/{host_ip}\n"
|
||||
|
||||
config_content += f"""address=/.local/{host_ip}
|
||||
|
||||
# Кэш DNS
|
||||
cache-size=500
|
||||
|
||||
# Лог (опционально)
|
||||
log-queries
|
||||
log-facility=/var/log/dnsmasq.log
|
||||
|
||||
# Не перехватывать внешние запросы — делегируем
|
||||
no-resolv
|
||||
server=8.8.8.8
|
||||
server=1.1.1.1
|
||||
"""
|
||||
|
||||
# Путь к конфигурационному файлу
|
||||
config_path = Path.home() / "projects" / "docker" / "network" / "dnsmasq.conf"
|
||||
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(config_path, 'w', encoding='utf-8') as f:
|
||||
f.write(config_content.strip())
|
||||
|
||||
print(f"Конфигурационный файл dnsmasq обновлен: {config_path}")
|
||||
|
||||
def run_docker_command(cmd):
|
||||
"""Выполняет команду Docker и возвращает результат"""
|
||||
try:
|
||||
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
print(f"Ошибка выполнения команды: {cmd}")
|
||||
print(f"Ошибка: {result.stderr}")
|
||||
return False
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Ошибка выполнения команды: {e}")
|
||||
return False
|
||||
|
||||
def setup_project():
|
||||
"""Настройка проекта: генерация конфигов и переход в директорию"""
|
||||
# Генерируем конфигурационный файл dnsmasq
|
||||
generate_dnsmasq_config()
|
||||
|
||||
# Переходим в директорию проекта
|
||||
project_path = Path.home() / "projects" / "docker" / "network"
|
||||
if not project_path.exists():
|
||||
print(f"Директория проекта не найдена: {project_path}")
|
||||
sys.exit(1)
|
||||
|
||||
os.chdir(project_path)
|
||||
return project_path
|
||||
Reference in New Issue
Block a user