311 lines
8.7 KiB
Bash
Executable File
311 lines
8.7 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
# Script para configurar el sistema NAT industrial como servicio permanente
|
|
# Ejecutar desde PC1 (WSL2)
|
|
|
|
set -e
|
|
|
|
echo "🏭 Configuración de Sistema NAT Industrial Permanente"
|
|
echo "===================================================="
|
|
|
|
# Función para verificar Docker
|
|
check_docker() {
|
|
echo "🐳 Verificando Docker..."
|
|
|
|
if ! command -v docker &> /dev/null; then
|
|
echo "❌ Docker no está instalado"
|
|
echo " Instalar con: curl -fsSL https://get.docker.com | sh"
|
|
exit 1
|
|
fi
|
|
|
|
if ! docker info &> /dev/null; then
|
|
echo "⚠️ Docker no está ejecutándose, iniciando..."
|
|
sudo service docker start || {
|
|
echo "❌ No se pudo iniciar Docker"
|
|
exit 1
|
|
}
|
|
fi
|
|
|
|
if ! command -v docker-compose &> /dev/null; then
|
|
echo "⚠️ Docker Compose no está instalado, instalando..."
|
|
sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
|
|
sudo chmod +x /usr/local/bin/docker-compose
|
|
fi
|
|
|
|
echo "✅ Docker está listo"
|
|
}
|
|
|
|
# Función para verificar conexión SSH
|
|
test_ssh_connection() {
|
|
echo "🔐 Verificando conexión SSH a PC3..."
|
|
|
|
local ssh_host=$(grep "host:" config/nat_config.yaml | awk '{print $2}' | tr -d '"')
|
|
local ssh_user=$(grep "user:" config/nat_config.yaml | awk '{print $2}' | tr -d '"')
|
|
local ssh_key="certs/ssh_private_key"
|
|
|
|
echo " Host: $ssh_host"
|
|
echo " Usuario: $ssh_user"
|
|
echo " Clave: $ssh_key"
|
|
|
|
if ssh -i "$ssh_key" -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$ssh_user@$ssh_host" "echo 'SSH OK'" &>/dev/null; then
|
|
echo "✅ Conexión SSH exitosa"
|
|
else
|
|
echo "❌ Error de conexión SSH"
|
|
echo " Verifica:"
|
|
echo " 1. PC3 ($ssh_host) está accesible"
|
|
echo " 2. Usuario '$ssh_user' es correcto"
|
|
echo " 3. Clave SSH está configurada en PC3"
|
|
return 1
|
|
fi
|
|
}
|
|
|
|
# Función para crear directorios necesarios
|
|
create_directories() {
|
|
echo "📁 Creando directorios necesarios..."
|
|
|
|
mkdir -p logs
|
|
mkdir -p config
|
|
mkdir -p certs
|
|
|
|
# Establecer permisos correctos
|
|
chmod 700 certs
|
|
chmod 600 certs/ssh_private_key 2>/dev/null || true
|
|
|
|
echo "✅ Directorios creados"
|
|
}
|
|
|
|
# Función para construir imagen Docker
|
|
build_image() {
|
|
echo "🔨 Construyendo imagen Docker..."
|
|
|
|
if docker-compose build; then
|
|
echo "✅ Imagen construida exitosamente"
|
|
else
|
|
echo "❌ Error construyendo imagen"
|
|
return 1
|
|
fi
|
|
}
|
|
|
|
# Función para configurar como servicio del sistema
|
|
create_systemd_service() {
|
|
local service_name="industrial-nat"
|
|
local service_file="/etc/systemd/system/${service_name}.service"
|
|
local work_dir="$(pwd)"
|
|
|
|
echo "⚙️ Configurando servicio systemd..."
|
|
|
|
# Crear archivo de servicio systemd
|
|
sudo tee "$service_file" > /dev/null << EOF
|
|
[Unit]
|
|
Description=Industrial NAT Proxy Service
|
|
Documentation=https://github.com/user/industrial-nat
|
|
After=docker.service
|
|
Requires=docker.service
|
|
|
|
[Service]
|
|
Type=oneshot
|
|
RemainAfterExit=yes
|
|
WorkingDirectory=$work_dir
|
|
ExecStart=/usr/local/bin/docker-compose up -d
|
|
ExecStop=/usr/local/bin/docker-compose down
|
|
ExecReload=/usr/local/bin/docker-compose restart
|
|
TimeoutStartSec=300
|
|
TimeoutStopSec=120
|
|
|
|
# Reiniciar en caso de fallo
|
|
Restart=on-failure
|
|
RestartSec=30
|
|
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
EOF
|
|
|
|
# Recargar systemd y habilitar servicio
|
|
sudo systemctl daemon-reload
|
|
sudo systemctl enable "$service_name"
|
|
|
|
echo "✅ Servicio systemd configurado: $service_name"
|
|
echo " Comandos disponibles:"
|
|
echo " sudo systemctl start $service_name"
|
|
echo " sudo systemctl stop $service_name"
|
|
echo " sudo systemctl status $service_name"
|
|
}
|
|
|
|
# Función para configurar inicio automático en WSL2
|
|
setup_wsl_autostart() {
|
|
echo "🚀 Configurando inicio automático en WSL2..."
|
|
|
|
local wsl_config="$HOME/.profile"
|
|
local service_name="industrial-nat"
|
|
|
|
# Agregar comando de inicio a .profile si no existe
|
|
if ! grep -q "industrial-nat" "$wsl_config" 2>/dev/null; then
|
|
cat >> "$wsl_config" << EOF
|
|
|
|
# Industrial NAT Service - Auto start
|
|
if command -v systemctl &> /dev/null; then
|
|
if ! systemctl is-active --quiet $service_name; then
|
|
echo "🏭 Iniciando servicio Industrial NAT..."
|
|
sudo systemctl start $service_name
|
|
fi
|
|
fi
|
|
EOF
|
|
echo "✅ Inicio automático configurado en WSL2"
|
|
else
|
|
echo "✅ Inicio automático ya estaba configurado"
|
|
fi
|
|
}
|
|
|
|
# Función para iniciar el servicio
|
|
start_service() {
|
|
echo "🎬 Iniciando servicio Industrial NAT..."
|
|
|
|
# Parar contenedor existente si está ejecutándose
|
|
docker-compose down 2>/dev/null || true
|
|
|
|
# Iniciar servicio
|
|
if docker-compose up -d; then
|
|
echo "✅ Servicio iniciado exitosamente"
|
|
|
|
# Esperar a que esté listo
|
|
echo "⏳ Esperando que el servicio esté listo..."
|
|
for i in {1..30}; do
|
|
if curl -s http://localhost:8080/status >/dev/null 2>&1; then
|
|
echo "✅ Servicio está respondiendo"
|
|
break
|
|
fi
|
|
sleep 2
|
|
echo -n "."
|
|
done
|
|
echo
|
|
|
|
else
|
|
echo "❌ Error iniciando servicio"
|
|
return 1
|
|
fi
|
|
}
|
|
|
|
# Función para mostrar estado del servicio
|
|
show_service_status() {
|
|
echo ""
|
|
echo "📊 Estado del Servicio Industrial NAT"
|
|
echo "===================================="
|
|
|
|
# Estado del contenedor
|
|
echo "🐳 Estado del contenedor:"
|
|
docker-compose ps
|
|
|
|
echo ""
|
|
echo "📋 Estado de la API:"
|
|
if curl -s http://localhost:8080/status | python3 -m json.tool 2>/dev/null; then
|
|
echo "✅ API funcionando correctamente"
|
|
else
|
|
echo "❌ API no responde"
|
|
fi
|
|
|
|
echo ""
|
|
echo "📝 Logs recientes:"
|
|
docker-compose logs --tail=10
|
|
}
|
|
|
|
# Función para crear scripts de gestión
|
|
create_management_scripts() {
|
|
echo "📄 Creando scripts de gestión..."
|
|
|
|
# Script de inicio rápido
|
|
cat > start_nat.sh << 'EOF'
|
|
#!/bin/bash
|
|
echo "🏭 Iniciando Sistema NAT Industrial..."
|
|
cd "$(dirname "$0")"
|
|
docker-compose up -d
|
|
echo "✅ Sistema iniciado. API disponible en: http://localhost:8080"
|
|
EOF
|
|
chmod +x start_nat.sh
|
|
|
|
# Script de parada
|
|
cat > stop_nat.sh << 'EOF'
|
|
#!/bin/bash
|
|
echo "🛑 Deteniendo Sistema NAT Industrial..."
|
|
cd "$(dirname "$0")"
|
|
docker-compose down
|
|
echo "✅ Sistema detenido"
|
|
EOF
|
|
chmod +x stop_nat.sh
|
|
|
|
# Script de estado
|
|
cat > status_nat.sh << 'EOF'
|
|
#!/bin/bash
|
|
echo "📊 Estado del Sistema NAT Industrial:"
|
|
cd "$(dirname "$0")"
|
|
docker-compose ps
|
|
echo ""
|
|
echo "📋 Estado de la API:"
|
|
curl -s http://localhost:8080/status | python3 -m json.tool 2>/dev/null || echo "API no disponible"
|
|
EOF
|
|
chmod +x status_nat.sh
|
|
|
|
echo "✅ Scripts de gestión creados:"
|
|
echo " ./start_nat.sh - Iniciar sistema"
|
|
echo " ./stop_nat.sh - Detener sistema"
|
|
echo " ./status_nat.sh - Ver estado"
|
|
}
|
|
|
|
# Función principal
|
|
main() {
|
|
echo "Configurando sistema NAT industrial permanente..."
|
|
echo ""
|
|
|
|
# Verificaciones previas
|
|
check_docker
|
|
create_directories
|
|
test_ssh_connection
|
|
|
|
# Construcción e instalación
|
|
build_image
|
|
create_systemd_service
|
|
setup_wsl_autostart
|
|
create_management_scripts
|
|
|
|
# Iniciar servicio
|
|
start_service
|
|
|
|
# Mostrar estado
|
|
show_service_status
|
|
|
|
echo ""
|
|
echo "🎉 ¡Sistema NAT Industrial configurado como servicio permanente!"
|
|
echo ""
|
|
echo "📋 INFORMACIÓN IMPORTANTE:"
|
|
echo "========================="
|
|
echo "✅ Servicio: industrial-nat"
|
|
echo "✅ Auto-inicio: Configurado para WSL2"
|
|
echo "✅ API REST: http://localhost:8080"
|
|
echo "✅ Logs: ./logs/nat_proxy.log"
|
|
echo ""
|
|
echo "🎮 COMANDOS DE GESTIÓN:"
|
|
echo "======================"
|
|
echo "sudo systemctl start industrial-nat # Iniciar servicio"
|
|
echo "sudo systemctl stop industrial-nat # Detener servicio"
|
|
echo "sudo systemctl status industrial-nat # Ver estado"
|
|
echo "sudo systemctl restart industrial-nat # Reiniciar servicio"
|
|
echo ""
|
|
echo "⚡ SCRIPTS RÁPIDOS:"
|
|
echo "=================="
|
|
echo "./start_nat.sh # Inicio rápido"
|
|
echo "./stop_nat.sh # Parada rápida"
|
|
echo "./status_nat.sh # Ver estado"
|
|
echo ""
|
|
echo "📱 USO DESDE PC2:"
|
|
echo "================="
|
|
echo "python nat_client.py plc 10.1.33.11 vnc --wait"
|
|
echo "./scripts/industrial_manager.sh"
|
|
echo ""
|
|
echo "🔄 El sistema se reiniciará automáticamente:"
|
|
echo "- Si WSL2 se reinicia"
|
|
echo "- Si el contenedor falla"
|
|
echo "- Si PC1 se reinicia"
|
|
echo ""
|
|
}
|
|
|
|
# Ejecutar función principal
|
|
main "$@" |