From 97f82862d03a74af67671faf13eb6c77a57e8d91 Mon Sep 17 00:00:00 2001 From: Manuel Villarroel Date: Sat, 23 Aug 2025 11:15:23 -0400 Subject: [PATCH] First commit --- listmonk-installer.sh | 323 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 323 insertions(+) create mode 100644 listmonk-installer.sh diff --git a/listmonk-installer.sh b/listmonk-installer.sh new file mode 100644 index 0000000..5448aa7 --- /dev/null +++ b/listmonk-installer.sh @@ -0,0 +1,323 @@ +#!/bin/bash + +# Script de instalación automática de Listmonk en Ubuntu 22.04 +# Uso: sudo bash install-listmonk.sh + +set -e + +# Colores para output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Función para imprimir mensajes +print_message() { + echo -e "${GREEN}[INFO]${NC} $1" +} + +print_warning() { + echo -e "${YELLOW}[WARNING]${NC} $1" +} + +print_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +print_step() { + echo -e "${BLUE}[STEP]${NC} $1" +} + +# Verificar si se ejecuta como root +if [ "$EUID" -ne 0 ]; then + print_error "Por favor ejecuta este script como root (sudo)" + exit 1 +fi + +print_message "=== Iniciando instalación de Listmonk ===" +print_message "Sistema operativo recomendado: Ubuntu 22.04 LTS" + +# Paso 1: Actualizar el sistema +print_step "1. Actualizando el sistema..." +apt update && apt upgrade -y + +# Paso 2: Instalar dependencias básicas +print_step "2. Instalando dependencias básicas..." +apt install -y curl wget unzip software-properties-common apt-transport-https ca-certificates gnupg lsb-release + +# Paso 3: Instalar PostgreSQL +print_step "3. Instalando PostgreSQL..." +apt install -y postgresql postgresql-contrib + +# Iniciar y habilitar PostgreSQL +systemctl start postgresql +systemctl enable postgresql + +# Paso 4: Configurar PostgreSQL +print_step "4. Configurando PostgreSQL..." + +# Generar contraseña aleatoria para PostgreSQL +DB_PASSWORD=$(openssl rand -base64 32) +LISTMONK_PASSWORD=$(openssl rand -base64 32) + +# Configurar usuario de PostgreSQL +sudo -u postgres psql << EOF +CREATE DATABASE listmonk; +CREATE USER listmonk WITH ENCRYPTED PASSWORD '$DB_PASSWORD'; +GRANT ALL PRIVILEGES ON DATABASE listmonk TO listmonk; +ALTER USER listmonk CREATEDB; +\q +EOF + +print_message "Base de datos configurada correctamente" + +# Paso 5: Crear usuario para Listmonk +print_step "5. Creando usuario del sistema para Listmonk..." +useradd --system --shell /bin/bash --home /opt/listmonk listmonk || true + +# Paso 6: Descargar e instalar Listmonk +print_step "6. Descargando Listmonk..." + +# Obtener la última versión +LATEST_VERSION=$(curl -s https://api.github.com/repos/knadh/listmonk/releases/latest | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') +print_message "Descargando Listmonk versión: $LATEST_VERSION" + +# Crear directorio de instalación +mkdir -p /opt/listmonk +cd /opt/listmonk + +# Descargar binario +wget "https://github.com/knadh/listmonk/releases/download/$LATEST_VERSION/listmonk_${LATEST_VERSION}_linux_amd64.tar.gz" +tar -xzf "listmonk_${LATEST_VERSION}_linux_amd64.tar.gz" +rm "listmonk_${LATEST_VERSION}_linux_amd64.tar.gz" + +# Hacer ejecutable +chmod +x listmonk + +# Cambiar propietario +chown -R listmonk:listmonk /opt/listmonk + +# Paso 7: Crear archivo de configuración +print_step "7. Creando archivo de configuración..." + +cat > /opt/listmonk/config.toml << EOF +[app] +address = "0.0.0.0:9000" +admin_username = "admin" +admin_password = "$LISTMONK_PASSWORD" + +# Database. +[db] +host = "localhost" +port = 5432 +user = "listmonk" +password = "$DB_PASSWORD" +database = "listmonk" +ssl_mode = "disable" +max_open = 25 +max_idle = 25 +max_lifetime = "300s" + +# SMTP servers. +[smtp] + [smtp.default] + enabled = true + host = "localhost" + port = 1025 + auth_protocol = "none" + username = "" + password = "" + hello_hostname = "" + max_conns = 10 + max_msg_retries = 2 + idle_timeout = "15s" + wait_timeout = "5s" + tls_enabled = false + tls_skip_verify = false + email_headers = [] + +# Bounce processing. +[bounce] +enabled = false +webhooks_enabled = false + +# Default bounce e-mail box that listmonk will connect to. + [bounce.mailbox] + enabled = false + type = "pop" + host = "" + port = 995 + auth_protocol = "userpass" + username = "" + password = "" + return_path = "" + scan_interval = "15m" + tls_enabled = true + tls_skip_verify = false + +# File upload settings. +[upload] +provider = "filesystem" +filesystem_upload_path = "./uploads" +filesystem_upload_uri = "/uploads" + +# HTTP security headers. +[security] +enable_captcha = false +captcha_key = "" +captcha_secret = "" +EOF + +chown listmonk:listmonk /opt/listmonk/config.toml +chmod 600 /opt/listmonk/config.toml + +# Paso 8: Inicializar la base de datos +print_step "8. Inicializando base de datos..." +sudo -u listmonk /opt/listmonk/listmonk --install --config /opt/listmonk/config.toml + +# Paso 9: Crear servicio systemd +print_step "9. Creando servicio systemd..." + +cat > /etc/systemd/system/listmonk.service << EOF +[Unit] +Description=Listmonk +After=network.target + +[Service] +Type=simple +User=listmonk +Group=listmonk +WorkingDirectory=/opt/listmonk +ExecStart=/opt/listmonk/listmonk --config /opt/listmonk/config.toml +Restart=always +RestartSec=3 +StandardOutput=journal +StandardError=journal +SyslogIdentifier=listmonk + +[Install] +WantedBy=multi-user.target +EOF + +# Recargar systemd y habilitar el servicio +systemctl daemon-reload +systemctl enable listmonk +systemctl start listmonk + +# Paso 10: Instalar Nginx como proxy reverso (opcional) +read -p "¿Deseas instalar Nginx como proxy reverso? (s/n): " -n 1 -r +echo +if [[ $REPLY =~ ^[Ss]$ ]]; then + print_step "10. Instalando y configurando Nginx..." + + apt install -y nginx + + # Crear configuración de Nginx + cat > /etc/nginx/sites-available/listmonk << EOF +server { + listen 80; + server_name _; + + client_max_body_size 50M; + + location / { + proxy_pass http://127.0.0.1:9000; + proxy_set_header Host \$host; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_read_timeout 300s; + proxy_connect_timeout 75s; + } +} +EOF + + # Habilitar el sitio + ln -sf /etc/nginx/sites-available/listmonk /etc/nginx/sites-enabled/ + rm -f /etc/nginx/sites-enabled/default + + # Verificar configuración y reiniciar Nginx + nginx -t && systemctl restart nginx + systemctl enable nginx + + print_message "Nginx configurado correctamente" +fi + +# Paso 11: Configurar firewall básico +print_step "11. Configurando firewall básico..." +ufw --force enable +ufw allow ssh +ufw allow 'Nginx Full' +ufw allow 9000/tcp + +# Paso 12: Crear script de backup +print_step "12. Creando script de backup..." +mkdir -p /opt/listmonk/backups + +cat > /opt/listmonk/backup.sh << 'EOF' +#!/bin/bash +BACKUP_DIR="/opt/listmonk/backups" +DATE=$(date +%Y%m%d_%H%M%S) +DB_NAME="listmonk" + +# Crear backup de la base de datos +sudo -u postgres pg_dump $DB_NAME > "$BACKUP_DIR/listmonk_db_$DATE.sql" + +# Crear backup de archivos de configuración +tar -czf "$BACKUP_DIR/listmonk_config_$DATE.tar.gz" -C /opt/listmonk config.toml uploads/ + +# Mantener solo los últimos 7 backups +find $BACKUP_DIR -name "listmonk_*" -type f -mtime +7 -delete + +echo "Backup completado: $DATE" +EOF + +chmod +x /opt/listmonk/backup.sh +chown listmonk:listmonk /opt/listmonk/backup.sh + +# Configurar cron para backup automático +(crontab -u listmonk -l 2>/dev/null; echo "0 2 * * * /opt/listmonk/backup.sh") | crontab -u listmonk - + +# Mostrar información final +print_message "=== Instalación completada exitosamente ===" +echo +print_message "Información de acceso:" +echo -e " ${BLUE}URL:${NC} http://$(hostname -I | awk '{print $1}'):9000" +echo -e " ${BLUE}Usuario:${NC} admin" +echo -e " ${BLUE}Contraseña:${NC} $LISTMONK_PASSWORD" +echo +print_message "Base de datos PostgreSQL:" +echo -e " ${BLUE}Usuario:${NC} listmonk" +echo -e " ${BLUE}Contraseña:${NC} $DB_PASSWORD" +echo -e " ${BLUE}Base de datos:${NC} listmonk" +echo +print_message "Archivos importantes:" +echo -e " ${BLUE}Configuración:${NC} /opt/listmonk/config.toml" +echo -e " ${BLUE}Logs:${NC} sudo journalctl -u listmonk -f" +echo -e " ${BLUE}Backup script:${NC} /opt/listmonk/backup.sh" +echo +print_message "Comandos útiles:" +echo -e " ${BLUE}Estado del servicio:${NC} sudo systemctl status listmonk" +echo -e " ${BLUE}Reiniciar servicio:${NC} sudo systemctl restart listmonk" +echo -e " ${BLUE}Ver logs:${NC} sudo journalctl -u listmonk -f" +echo +print_warning "¡Guarda estas credenciales en un lugar seguro!" +print_warning "Se recomienda cambiar la contraseña del admin desde la interfaz web" + +# Guardar credenciales in archivo +cat > /root/listmonk-credentials.txt << EOF +=== Credenciales de Listmonk === +URL: http://$(hostname -I | awk '{print $1}'):9000 +Usuario admin: admin +Contraseña admin: $LISTMONK_PASSWORD + +Base de datos PostgreSQL: +Usuario: listmonk +Contraseña: $DB_PASSWORD +Base de datos: listmonk + +Fecha de instalación: $(date) +EOF + +print_message "Credenciales guardadas en: /root/listmonk-credentials.txt"