#!/bin/bash ################################################################# # auto-mediawiki # # Instala un servidor LAMP (Linux+Apache+MySQL+PHP) e instala # # MediaWiki y lo configura. # # # # Guzman Castanedo Villalba (guzman@castanedo.es) Junio 2018 # # GPLv3 (https://www.gnu.org/licenses/gpl.html) # ################################################################# comprobarError() { # Permite comprobar si se ha producido un error y de serlo devuelve un código de error # comprobarError exitNum codeNum extraInfo # 1xx: Servidor Web # 2xx: Base de Datos # 3xx: PHP # 4xx: SSL/TLS # 5xx: MediaWiki # 6xx: Moodle # 7xx: Backup automático # 8xx: Dependencias # 9xx: Servicios & Firewall type="ERROR" exitNum=$1 shift codeNum=$1 shift extraInfo=$@ case $codeNum in 1) error="$type $codeNum:\tInstalación interrumpida por el usuario.\n" ;; 2) error="$type $codeNum:\tError interno (selección express).\n" ;; 3) error="$type $codeNum:\tError interno (selección avanzada).\n" ;; 4) error="\n$type $codeNum:\tEl archivo '"$(realpath $extraInfo)"' no existe.\n" ;; 5) error="\n$type $codeNum:\tEl directorio '"$(realpath $extraInfo)"' no existe.\n" ;; 6) error="$type $codeNum:\tError interno (selección SSL/TLS).\n" ;; 100) error="$type $codeNum:\tError interno (selección del servidor web).\n" ;; 101) error="\n$type $codeNum:\tError al instalar Apache2.\nDetalles:\n$extraInfo\n" ;; 102) error="\n$type $codeNum:\tError al instalar Nginx.\nDetalles:\n$extraInfo\n" ;; 103) error="\n$type $codeNum:\tError al nstalar repositorio 'epel-release'.\nDetalles:\n$extraInfo\n" ;; 104) error="\n$type $codeNum:\tError interno (instalación Apache2).\n" ;; 105) error="\n$type $codeNum:\tError interno (instalación Nginx).\n" ;; 106) type="WARNING" error="\n$type $codeNum:\tImposible instalar 'info.php'.\n" ;; 107) error="\n$type $codeNum:\tError al configurar Nginx.\n" ;; 108) error="\n$type $codeNum:\tError al configurar Apache2.\n" ;; 200) error="$type $codeNum:\tError interno (selección de base de datos).\n" ;; 201) error="\n$type $codeNum:\tError al instalar MySQL.\nDetalles:\n$extraInfo\n" ;; 202) error="\n$type $codeNum:\tError al instalar MariaDB.\nDetalles:\n$extraInfo\n" ;; 203) error="\n$type $codeNum:\tError interno (instalación MySQL).\n" ;; 204) error="\n$type $codeNum:\tError interno (instalación MariaDB).\n" ;; 205) error="\n$type $codeNum:\t$DIST no incluye MySQL en sus repositorios.\n" ;; 206) type="WARNING" error="\n$type $codeNum:\tUsuario 'root' ya dispone de contraseña." ;; 207) error="\n$type $codeNum:\tImposible cambiar la contraseña de 'root'." ;; 208) error="\n$type $codeNum:\tImposible desactivar acceso 'root' desde el exterior." ;; 209) error="\n$type $codeNum:\tImposible eliminar usuarios anónimos." ;; 210) type="WARNING" error="\n$type $codeNum:\tImposible eliminar bases de datos de pruebas." ;; 211) type="WARNING" error="\n$type $codeNum:\tImposible eliminar los permisos de las bases de datos de pruebas." ;; 212) error="\n$type $codeNum:\tImposible recargar base de datos." ;; 213) error="\n$type $codeNum:\tImposible configurar SQL.\n" ;; 214) type="WARNING" error="\n$type $codeNum:\tSQL ya está configurado." ;; 300) error="\n$type $codeNum:\tError interno (instalación PHP-7.2).\n" ;; 301) error="\n$type $codeNum:\tError interno (Web Server no seleccionado).\n" ;; 302) error="\n$type $codeNum:\tError al instalar PHP-7.2.\nDetalles:\n$extraInfo\n" ;; 303) error="\n$type $codeNum:\tError al instalar Repositorio Remi.\nDetalles:\n$extraInfo\n" ;; 304) error="\n$type $codeNum:\tSistema Operativo no compatible con PHP-7.2 ($OS $DIST $REV).\n" ;; 305) error="\n$type $codeNum:\tImposible configurar PHP-7.2.\n" ;; 501) error="\n$type $codeNum:\tImposible descargar MediaWiki-1.31.0.\n" ;; 502) error="\n$type $codeNum:\tImposible configurar MediaWiki-1.31.0.\n" ;; 503) type="WARNING" error="\n$type $codeNum:\tYa existe una copia configurada de MediaWiki en el dominio: '$extraInfo'." ;; 601) error="\n$type $codeNum:\tImposible descargar Moodle-3.5.1.\n" ;; 602) error="\n$type $codeNum:\tImposible configurar Moodle-3.5.1.\n" ;; 603) type="WARNING" error="\n$type $codeNum:\tYa existe una copia configurada de Moodle en el dominio: '$extraInfo'." ;; 604) error="\n$type $codeNum:\tImposible configurar SELinux.\n" ;; 605) error="\n$type $codeNum:\tImposible instalar 'policycoreutils-python'.Detalles:\n$extraInfo\n" ;; 800) error="$type $codeNum:\tEs necesario ser root ('sudo $0').\n" ;; 801) error="$type $codeNum:\t'whiptail' no instalado.\n" ;; 802) error="$type $codeNum:\t'hostnamectl' no instalado.\n" ;; 803) error="$type $codeNum:\t'apt-get' no instalado.\n" ;; 804) error="$type $codeNum:\t'yum' no instalado.\n" ;; 805) error="\n$type $codeNum:\tImposible actualizar repositorio\nDetalles:\n$extraInfo.\n" ;; 806) error="$type $codeNum:\t'ufw' no instalado.\n" ;; 807) error="$type $codeNum:\t'firewall-cmd' no instalado.\n" ;; 808) error="$type $codeNum:\t'tput' no instalado.\nDetalles:\n$extraInfo\n" ;; 809) error="$type $codeNum:\t'sed' no instalado.\nDetalles:\n$extraInfo\n" ;; 810) error="$type $codeNum:\t'curl' no instalado.\nDetalles:\n$extraInfo\n" ;; 811) error="$type $codeNum:\t'tar' no instalado.\nDetalles:\n$extraInfo\n" ;; 812) error="$type $codeNum:\t'gzip' no instalado.\nDetalles:\n$extraInfo\n" ;; 813) error="$type $codeNum:\t'bzip2' no instalado.\nDetalles:\n$extraInfo\n" ;; 814) error="$type $codeNum:\t'xz' no instalado.\nDetalles:\n$extraInfo\n" ;; 815) error="$type $codeNum:\t'openssl' no instalado.\nDetalles:\n$extraInfo\n" ;; 816) error="$type $codeNum:\t'find' no instalado.\n" ;; 900) error="$type $codeNum:\tError interno (habilitar servicio).\n" ;; 901) error="$type $codeNum:\tImposible encender servicio '$extraInfo'.\n" ;; 902) error="$type $codeNum:\tImposible habilitar servicio '$extraInfo' durante el arranque.\n" ;; 903) error="$type $codeNum:\tError interno (deshabilitar servicio).\n" ;; 904) error="$type $codeNum:\tImposible parar servicio '$extraInfo'.\n" ;; 905) error="$type $codeNum:\tImposible deshabilitar servicio '$extraInfo' durante el arranque.\n" ;; 906) type="WARNING" error="\n$type $codeNum:\tImposible añadir regla al cortafuegos ('$extraInfo').\n" ;; 907) type="WARNING" error="\n$type $codeNum:\tImposible encender cortafuegos.\n" ;; 908) error="\n$type $codeNum:\tError interno (instalar Virtual Host).\n" ;; 909) error="\n$type $codeNum:\tVirtual Host '$extraInfo' no existe.\n" ;; 910) error="\n$type $codeNum:\tImposible copiar Virtual Host '$extraInfo'.\n" ;; 911) error="\n$type $codeNum:\tImposible activar Virtual Host '$extraInfo'.\n" ;; 912) error="\n$type $codeNum:\tError interno (recargar servicio).\n" ;; 913) error="\n$type $codeNum:\tImposible recargar servicio '$extraInfo'.\n" ;; *) error="ERROR 13:\tError interno (comprobación de errores)\n" exitNum=1 codeNum=13 ;; esac if [ $exitNum -ne 0 ];then echo -en "$error" | tee -a $logFile if [ $type = "ERROR" ];then exit $codeNum fi fi unset error exitNum codeNum type } OSInfo() { # Detecta el OS en el que se está ejecutando el programa, así como su versión echo -en "Detectando SO..." >> $logFile OS=$(uname -s) if [ $OS = "Linux" ]; then OS="GNU/Linux" if [ -f /etc/os-release ]; then DIST=$(grep ^NAME= /etc/os-release | cut -d = -f 2 | cut -d '"' -f 2) REV=$(grep ^VERSION= /etc/os-release | cut -d = -f 2 | cut -d '"' -f 2) ID_LIKE=$(grep ^ID_LIKE= /etc/os-release | cut -d = -f 2 | cut -d '"' -f 2) VERSION=$(grep ^VERSION_ID= /etc/os-release | cut -d = -f 2 | cut -d '"' -f 2) for i in $ID_LIKE; do #echo -en "$i\n" case $i in debian|ubuntu) debianOS=true break ;; rhel|fedora) rhelOS=true break ;; *) debianOS=false rhelOS=false ;; esac done elif [ -f /etc/debian-version ]; then # Familia Debian (Debian, Ubuntu, Linux Mint, ...) DIST="Debian" REV="" ID_LIKE="debian" VERSION="" debianOS=true elif [ -f /etc/redhat-release ]; then # Familia Red-Hat (RHEL, Fedora, CentOS, ...) DIST="Red-Hat" REV="" ID_LIKE="rhel" VERSION="" rhelOS=true else # Other Linux (No Soportado) DIST="" REV="" ID_LIKE="" VERSION="" fi else # UNIX, OS X, ... (No Soportado) DIST=$OS REV="" ID_LIKE="" VERSION="" fi echo -en " $OS $DIST $REV\n" >> $logFile HDInfo=$(df -h | head -1)"\n"$(df -h | grep ^/dev/sd)"\n"$(df -h | grep ^/dev/mapper) echo -en "$HDInfo\n" >> $logFile } comprobarRoot() { # Comprueba si se está ejecutando con privilegios de root comprobarError $(id -u) 800 } comprobarDependencias() { # Comprueba si están instalados todos los programas necesarios. # En la mayoría de los casos, trata de instalarlos. # Comprobamos whiptail which whiptail > /dev/null 2>&1 comprobarError $? 801 # Comprobamos hostnamectl which hostnamectl > /dev/null 2>&1 comprobarError $? 802 which find > /dev/null 2>&1 comprobarError $? 816 if [ $debianOS = true ];then # Comprobamos apt-get which apt-get > /dev/null 2>&1 comprobarError $? 803 # Actualizamos base de datos del repositorio echo -en "Actualizando repositorio APT..." | tee -a $logFile result=$(apt-get -q -y update 2>&1) comprobarError $? 805 $result echo -en " OK.\n" | tee -a $logFile # Comprobamos Firewall (ufw) which ufw > /dev/null 2>&1 comprobarError $? 806 # Comprobamos tput which tput > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(apt-get -q -y ncurses-bin 2>&1) comprobarError $? 808 $result fi # Comprobar sed which sed > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(apt-get -q -y sed 2>&1) comprobarError $? 809 $result fi # Comprobar curl which curl > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(apt-get -q -y curl 2>&1) comprobarError $? 810 $result fi # Comprobamos tar, gzip, bzip2 y xz which tar > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(apt-get -q -y install tar 2>&1) comprobarError $? 811 $result fi which gzip > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(apt-get -q -y install gzip 2>&1) comprobarError $? 812 $result fi which bzip2 > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(apt-get -q -y install bzip2 2>&1) comprobarError $? 813 $result fi which xz > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(apt-get -q -y install xz-utils 2>&1) comprobarError $? 814 $result fi which openssl > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(apt-get -q -y install openssl 2>&1) comprobarError $? 815 $result fi fi if [ $rhelOS = true ]; then # Comprobamos yum which yum > /dev/null 2>&1 comprobarError $? 804 # Actualizamos base de datos del repositorio echo -en "Actualizando repositorio YUM..." | tee -a $logFile result=$(yum -y makecache 2>&1) comprobarError $? 805 $result echo -en " OK.\n" | tee -a $logFile # Comprobamos Firewall (firewall-cmd) which firewall-cmd > /dev/null 2>&1 comprobarError $? 807 # Comprobamos tput which tput > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(yum -y ncurses 2>&1) comprobarError $? 808 $result fi # Comprobar sed which sed > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(yum -y sed 2>&1) comprobarError $? 809 $result fi # Comprobar curl which curl > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(yum -y curl 2>&1) comprobarError $? 810 $result fi # Comprobamos tar, gzip, bzip2 y xz which tar > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(yum -y install tar 2>&1) comprobarError $? 811 $result fi which gzip > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(yum -y install gzip 2>&1) comprobarError $? 812 $result fi which bzip2 > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(yum -y install bzip2 2>&1) comprobarError $? 813 $result fi which xz > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(yum -y install xz 2>&1) comprobarError $? 814 $result fi which openssl > /dev/null 2>&1 if [ $? -ne 0 ];then result=$(yum -y install openssl 2>&1) comprobarError $? 815 $result fi fi } inicializarVariables() { # Inicializa las variables que necesitan de un estado previo debianOS=false rhelOS=false apacheOn=false nginxOn=false mySQLOn=false mariaDBOn=false phpOn=false sslOn=false letsEncryptOn=false mediaWikiOn=false moodleOn=false infoPHPOn=false backupOn=false hostname="" logFile="./."$(basename $0)".log" maxUpload="100M" webServerName="" webServerUser="" webServerGroup="" sqlServerName="" phpFPMName="" nombreMediaWiki="" dominioMediaWiki="" passwdMediaWiki="" nombreMoodle="" nombreCortoMoodle="" dominioMoodle="" passwdMoodle="" } instalacionExpress() { # Permite una instalación rápida, haciendo el menor número de preguntas apacheOn=true mariaDBOn=true phpOn=true sslOn=true letsEncryptOn=true mediaWikiOn=true moodleOn=true backupOn=true # Preguntas mínimas establecerFQDN leerSQLPasswd mostrarMediaWiki mostrarMoodle } mostrarBienvenida() { # Pantalla de bienvenida y muestra SO y estado de los discos ANCHO=$(tput cols) ALTO=$(tput lines) if [ $debianOS = false ] && [ $rhelOS = false ]; then whiptail --title "ERROR S.O. NO SOPORTADO" --msgbox "Este script automatiza la creación de una web MediaWiki SOLO para distribuciones Linux de la familia Debian (Ubuntu, Linux Mint, ...) y de la familia Red-Hat (CentOS, Fedora, ...).\n\nInformación del sistema:\nOS: $OS $DIST $REV\n$HDInfo" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --ok-button "Salir" exit 1 fi whiptail --title "INSTALACION MEDIAWIKI" --yesno "Este script automatiza completamente la instalación de una WIKI y un CAMPUS VIRTUAL.\nPara ello instala un servidor LAMP, el software MediaWiki y configura todo lo necesario.\n\nInformación del sistema:\nOS: $OS $DIST $REV\n$HDInfo" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --yes-button "Continuar" --no-button "Salir" comprobarError $? 1 } mostrarExpress() { # Pantalla de elección entre instalación express o avanzada express=$(whiptail --title "INSTALACION EXPRESS" --radiolist ": seleccionar : cambiar : moverse\n\nLa instalación express instala Apache2, MariaDB, PHP-7, Let's Encrypt, MediaWiki, Moodle y backups automático.\nSeleccione el tipo de instalación que desee:" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) 2 \ "Express" "Instalación rápida" ON \ "Avanzada" "Permite escoger todas las opciones disponibles" OFF \ --ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3) comprobarError $? 1 case $express in Express) instalacionExpress # DECIDIR QUÉ OPCIONES SON LAS MÍNIMAS ;; Avanzada) mostrarAvanzada ;; *) comprobarError 1 2 ;; esac unset express } mostrarAvanzada() { # Pantalla que permite instalar un servidor LAMP o LEMP webServer=$(whiptail --title "INSTALACION AVANZADA" --radiolist ": seleccionar : cambiar : moverse\n\nEscoge el tipo de Servidor Web que quieres instalar:" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) 2 \ "LAMP" "GNU/Linux + Apache + MySQL/MariaDB + PHP-7" ON \ "LEMP" "GNU/Linux + Nginx + MySQL/MariaDB + PHP-7" OFF \ --ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3) comprobarError $? 1 for i in $webServer; do case $i in LAMP) apacheOn=true ;; LEMP) nginxOn=true ;; *) comprobarError 1 100 ;; esac done # Opciones comunes establecerFQDN mostrarDatabase phpOn=true establecerMaxUpload mostrarComponentes mostrarConfirmacion unset webServer } mostrarComponentes() { # Pantalla de elección de componentes (SSL/TLS, MediaWiki, Moodle, InfoPHP y Backup) componentes=$(whiptail --title "INSTALACION AVANZADA" --checklist ": seleccionar : cambiar : moverse\n\nEscoge los componentes que quieres instalar:" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) 5 \ "SSL/TLS" "Instalar certificados para activar HTTPS" ON \ "MediaWiki" "Instalar wiki con MediaWiki" ON \ "Moodle" "Instalar campus virtual con Moodle" ON \ "InfoPHP" "Instalar info.php (sólo para pruebas)" OFF \ "Backup" "Programar backups automáticos" ON \ --ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3) comprobarError $? 1 # Mejora: autodetección de componentes ya instalados for i in $componentes; do case $i in \"SSL/TLS\") # 2 Opciones: Let's Encrypt o Autofirmado mostrarSSL ;; \"MediaWiki\") mediaWikiOn=true mostrarMediaWiki ;; \"Moodle\") moodleOn=true mostrarMoodle ;; \"InfoPHP\") infoPHPOn=true ;; \"Backup\") BackupOn=true ;; *) comprobarError 1 3 ;; esac done unset componentes } mostrarSSL() { # Pantalla que permite seleccionar el tipo de certificados ssl=$(whiptail --title "INSTALACION SSL/TLS" --radiolist ": seleccionar : cambiar : moverse\n\nEscoge el tipo de Certificado SSL/TLS que quieres instalar:" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) 2 \ "LetsEncrypt" "Compatible con todos los navegadores" ON \ "Auto-Firmado" "Certificados auto-firmados (sólo para pruebas)" OFF \ --ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3) comprobarError $? 1 for i in $ssl; do case $i in LetsEncrypt) sslOn=true letsEcnryptOn=true ;; Auto-Firmados) sslOn=true ;; *) comprobarError 1 6 ;; esac done unset ssl } mostrarMediaWiki(){ # Pantalla que pregunta sobre las opciones necesarias para configurar MediaWiki # Introducir nombre wiki while [ -z "$nombreMediaWiki" ]; do nombreMediaWiki=$(whiptail --title "CONFIGURACION MEDIAWIKI" --inputbox "Introduzca el nombre de la Wiki:" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3) comprobarError $? 1 done # Introducir dominio while [ -z "$dominioMediaWiki" ]; do dominioMediaWiki=$(whiptail --title "CONFIGURACION MEDIAWIKI" --inputbox "Introduzca el dominio/subdominio de la Wiki.\nTenga en cuenta que debes apuntar este dominio a la dirección IP de esta máquina mediante un registro DNS de tipo CNAME.\nSi quiere introducir varios dominios sepárelos con espacios. El primero será el principal.\nPor ejemplo: 'www.$hostname $hostname wiki.$hostname'" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) wiki.$hostname --ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3) comprobarError $? 1 done cont=1 serverName="" aliasMediaWiki="" for dominio in $dominioMediaWiki;do if [ $cont -eq 1 ];then # Dominio Principal (ServerName) serverName=$dominio else # Dominios Secundarios (ServerAlias) aliasMediaWiki=$aliasMediaWiki" "$dominio fi cont=$((cont + 1)) done dominioMediaWiki=$serverName # Introducir contraseña control=false error="" while [ $control = false ]; do passwdMediaWiki=$(whiptail --title "CONFIGURACION MEDIAWIKI" --passwordbox "$error""Introduzca la contraseña para el usuario administrador 'admin':" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --ok-button "Continuar" --nocancel 3>&1 1>&2 2>&3) comprobarError $? 1 passwdMediaWiki2=$(whiptail --title "CONFIGURACION MEDIAWIKI" --passwordbox "Confirme la contraseña:" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --ok-button "Continuar" --nocancel 3>&1 1>&2 2>&3) comprobarError $? 1 if [ -z "$passwdMediaWiki" ] || [ -z "$passwdMediaWiki2" ]; then error="ERROR: LA CONTRASEÑA NO PUEDE ESTAR VACIA.\n" elif [ $passwdMediaWiki != $passwdMediaWiki2 ];then error="ERROR: LAS CONTRASEÑAS NO COINCIDEN.\n" else control=true fi done unset control error passwdMediaWiki2 dominio cont serverName } mostrarMoodle() { # Pantalla que pregunta sobre las opciones necesarias para configurar Moodle # Introducir Nombre Moodle while [ -z "$nombreMoodle" ]; do nombreMoodle=$(whiptail --title "CONFIGURACION MOODLE" --inputbox "Introduzca el NOMBRE COMPLETO del campus virtual.\nPor ejemplo: 'Campus Virtual Ejemplo'." $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3) comprobarError $? 1 done # Introducir Nombre Corto Moodle while [ -z "$nombreCortoMoodle" ]; do nombreCortoMoodle=$(whiptail --title "CONFIGURACION MOODLE" --inputbox "Introduzca el NOMBRE CORTO del campus virtual.\nPor ejemplo: 'Ejemplo'." $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3) comprobarError $? 1 done nombreCortoMoodle=$(echo $nombreCortoMoodle | cut -d ' ' -f 1) # Introducir dominio while [ -z "$dominioMoodle" ]; do dominioMoodle=$(whiptail --title "CONFIGURACION MOODLE" --inputbox "Introduzca el dominio/subdominio del campus virtual.\nMoodle SÓLO permite un ÚNICO DOMINIO." $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) moodle.$hostname --ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3) comprobarError $? 1 done cont=1 serverName="" aliasMoodle="" for dominio in $dominioMoodle;do if [ $cont -eq 1 ];then # Dominio Principal (ServerName) serverName=$dominio else # Dominios Secundarios (ServerAlias) aliasMeoodle=$aliasMoodle" "$dominio fi cont=$((cont + 1)) done dominioMoodle=$serverName # Introducir contraseña control=false error="" while [ $control = false ]; do passwdMoodle=$(whiptail --title "CONFIGURACION MOODLE" --passwordbox "$error""Introduzca la contraseña para el usuario administrador 'admin':" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --ok-button "Continuar" --nocancel 3>&1 1>&2 2>&3) comprobarError $? 1 passwdMoodle2=$(whiptail --title "CONFIGURACION MOODLE" --passwordbox "Confirme la contraseña:" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --ok-button "Continuar" --nocancel 3>&1 1>&2 2>&3) comprobarError $? 1 if [ -z "$passwdMoodle" ] || [ -z "$passwdMoodle2" ]; then error="ERROR: LA CONTRASEÑA NO PUEDE ESTAR VACIA.\n" elif [ $passwdMoodle != $passwdMoodle2 ];then error="ERROR: LAS CONTRASEÑAS NO COINCIDEN.\n" else control=true fi done unset control error passwdMoodle2 dominio cont serverName aliasMoodle } mostrarConfirmacion() { # Pantalla que presenta una confirmación antes de realizar la instalación whiptail --title "INSTALACION" --yesno "ESTA TODO LISTO PARA LA INSTALACION.\n¿DESEA CONTINUAR?" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --yes-button "Instalar" --no-button "Salir" comprobarError $? 1 } establecerFQDN() { # Configura el FQDN (dominio principal del servidor) while [ -z "$hostname" ]; do hostname=$(whiptail --title "FQDN" --inputbox "El nombre de dominio principal (FQDN) de este servidor es:\n"$(hostname)"\n\n¿Quieres cambiarlo por otro?" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --ok-button "Cambiar" --cancel-button "No Cambiar" 3>&1 1>&2 2>&3) if [ $? -eq 0 ] && [ ! -z "$hostname" ]; then hostnamectl set-hostname $hostname else hostname=$(hostname) fi done echo -en "Hostname: $hostname\n" >> $logFile } instalarApache() { # Instala Apache2 if [ $debianOS = true ];then webServerName="apache2" result=$(apt-get -q -y install apache2 2>&1) comprobarError $? 101 $result elif [ $rhelOS = true ]; then webServerName="httpd" result=$(yum -y install httpd 2>&1) comprobarError $? 101 $result else comprobarError 1 104 fi deshabilitarServicio $webServerName } configurarApache() { # Configura Apache2 if [ $debianOS = true ];then apacheConfFile="./etc/apache2/apache2.conf" if [ ! -f $apacheConfFile ];then comprobarError 1 4 $apacheConfFile fi cp -f $apacheConfFile /etc/$webServerName/apache2.conf 2>/dev/null comprobarError $? 108 webServerUser=$(grep ^User /etc/$webServerName/apache2.conf | cut -d ' ' -f 2) webServerGroup=$(grep ^Group /etc/$webServerName/apache2.conf | cut -d ' ' -f 2) if [ ! -L /etc/$webServerName/logs ];then ln -s /var/log/apache2 /etc/$webServerName/logs 2>/dev/null comprobarError $? 108 fi # Activamos mod_rewrite (no viene activado por defecto) a2enmod rewrite >/dev/null 2>&1 comprobarError $? 108 elif [ $rhelOS = true ];then apacheConfFile="./etc/apache2/conf/httpd.conf" welcomeConfFile="/etc/apache2/conf.d/welcome.conf" if [ ! -f $apacheConfFile ];then comprobarError 1 4 $apacheConfFile fi cp -f $apacheConfFile /etc/$webServerName/conf/httpd.conf 2>/dev/null comprobarError $? 108 if [ -f $welcomeConfFile ];then sed -i -e 's/^/#/' $welcomeConfFile comprobarError $? 108 fi webServerUser=$(grep ^User /etc/$webServerName/conf/httpd.conf | cut -d ' ' -f 2) webServerGroup=$(grep ^Group /etc/$webServerName/conf/httpd.conf | cut -d ' ' -f 2) unset apacheConfFile welcomeConfFile fi if [ ! -d "/etc/$webServerName/sites-available" ];then mkdir "/etc/$webServerName/sites-available" 2>/dev/null comprobarError $? 5 "/etc/$webServerName/sites-available" fi if [ ! -d "/etc/$webServerName/sites-enabled" ]; then mkdir "/etc/$webServerName/sites-enabled" 2>/dev/null comprobarError $? 5 "/etc/$webServerName/sites-enabled" else # Eliminar Virtual Host por defecto if [ -f /etc/$webServerName/sites-enabled/000-default.conf ];then rm -f /etc/$webServerName/sites-enabled/000-default.conf 2>/dev/null fi fi } instalarNginx() { # Instala Nginx webServerName="nginx" if [ $debianOS = true ];then result=$(apt-get -q -y install nginx 2>&1) comprobarError $? 102 $result elif [ $rhelOS = true ]; then # Hay que instalar primero otro repositorio result=$(yum -y install epel-release) comprobarError $? 103 $result result=$(yum -y install nginx 2>&1) comprobarError $? 102 $result else comprobarError 1 105 fi deshabilitarServicio $webServerName } configurarNginx() { # Configura Nginx rm -Rf "/etc/$webServerName/!(sites-available|sites-enabled)" 2>/dev/null comprobarError $? 107 nginxConfFile="./etc/$webServerName" if [ -d "$nginxConfFile" ];then cp -Rf $nginxConfFile/* /etc/$webServerName/ 2>/dev/null comprobarError $? 107 else comprobarError 1 5 "$nginxConfFile" fi if [ ! -d "/etc/$webServerName/sites-available" ];then mkdir "/etc/$webServerName/sites-available" 2>/dev/null comprobarError $? 5 "/etc/$webServerName/sites-available" fi if [ ! -d "/etc/$webServerName/sites-enabled" ]; then mkdir "/etc/$webServerName/sites-enabled" 2>/dev/null comprobarError $? 5 "/etc/$webServerName/sites-enabled" else # Eliminar Virtual Host por defecto if [ -f /etc/$webServerName/sites-enabled/default ];then rm -f /etc/$webServerName/sites-enabled/default 2>/dev/null fi fi # Configuramos Usuario y Grupo if [ $debianOS = true ];then webServerUser="www-data" webServerGroup=$webServerUser elif [ $rhelOS = true ];then webServerUser="nginx" webServerGroup=$webServerUser fi sed -i '/user /c\user '$webServerUser';' /etc/$webServerName/nginx.conf comprobarError $? 107 unset nginxConfFile } instalarVirtualHost() { # Configuramos un Virtual Host para Apache o Nginx # Uso: instalarVirtualHost $root $virtualHost $dominio $alias if [ $# -ge 3 ];then rootVirtualHost=$(realpath $1) shift virtualHostFile=$(realpath $1) shift dominioVirtualHost=$1 virtualHostName=$dominioVirtualHost".conf" shift aliasVirtualHost=$@ else comprobarError 1 908 fi if [ ! -f $virtualHostFile ];then comprobarError 1 909 $virtualHostName fi if [ $apacheOn = true ];then # Configuramos root, dominio y logs sed -i '/ServerName /c\\tServerName '"$dominioVirtualHost" $virtualHostFile comprobarError $? 908 if [ ! -z "$aliasVirtualHost" ];then sed -i '/ServerName /a\\tServerAlias '"$aliasVirtualHost" $virtualHostFile comprobarError $? 908 fi sed -i '/DocumentRoot /c\\tDocumentRoot '"$rootVirtualHost" $virtualHostFile comprobarError $? 908 sed -i '/ErrorLog /c\\tErrorLog logs/'"$dominioVirtualHost"'-error.log' $virtualHostFile comprobarError $? 908 sed -i '/CustomLog /c\\tCustomLog logs/'"$dominioVirtualHost"'-access.log common' $virtualHostFile comprobarError $? 908 elif [ $nginxOn = true ];then # Configuramos root, dominio, logs y php-fpm.sock (NGINX) sed -i '/root /c\\troot '$rootVirtualHost';' "$virtualHostFile" comprobarError $? 908 sed -i '/server_name /c\\tserver_name '"$dominioVirtualHost"' '"$aliasVirtualHost"';' $virtualHostFile comprobarError $? 908 sed -i '/access_log /c\\taccess_log /var/log/nginx/'"$dominioVirtualHost"'-access.log;' $virtualHostFile comprobarError $? 908 sed -i '/error_log /c\\terror_log /var/log/nginx/'"$dominioVirtualHost"'-error.log;' $virtualHostFile comprobarError $? 908 socket=$(find /var/run/ -type s -name 'php*.sock') sed -i '/fastcgi_pass /c\\t\tfastcgi_pass unix:'"$socket"';' $virtualHostFile fi # Copiamos ficheros de configuración cp -f $virtualHostFile "/etc/$webServerName/sites-available/$virtualHostName" >> $logFile 2>&1 comprobarError $? 910 ln -s "/etc/$webServerName/sites-available/$virtualHostName" "/etc/$webServerName/sites-enabled/$virtualHostName" >> $logFile 2>&1 comprobarError $? 911 $virtualHostName recargarServicio $webServerName unset rootVirtualHost dominioVirtualHost virtualHostFile virtualHostName aliasVirtualHost socket } mostrarDatabase() { # Pantalla que permite escoger entre instalar MariaDB o MySQL if [ $debianOS = true ]; then database=$(whiptail --title "BASE DE DATOS" --radiolist ": seleccionar : cambiar : moverse\n\nEscoge la base de datos que quieres usar:" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) 2 \ "MariaDB" "Instalar la base de datos MariaDB (fork de MySQL)" ON \ "MySQL" "Instalar la base de datos MySQL (uso no comercial)" OFF \ --ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3) comprobarError $? 1 case $database in MariaDB) mariaDBOn=true ;; MySQL) mySQLOn=true ;; *) comprobarError 1 200 ;; esac unset database elif [ $rhelOS = true ]; then whiptail --title "BASE DE DATOS" --yesno "Para su distribucion $OS $DIST $REV, sólo está disponible la base de datos MariaDB." $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --yes-button "Continuar" --no-button "Salir" comprobarError $? 1 mariaDBOn=true else comprobarError 1 200 fi # Otras opciones (contraseña) leerSQLPasswd } leerSQLPasswd() { # Pantalla para leer la contraseña para el usuario root de SQL control=false error="" # Leemos la contreseña (stdin) y confirmamos while [ $control = false ]; do sqlPasswd=$(whiptail --title "CONTRASEÑA SQL" --passwordbox "$error""Introduzca la contraseña para el usuario 'root' de la base de datos:" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --ok-button "Continuar" --nocancel 3>&1 1>&2 2>&3) comprobarError $? 1 sqlPasswd2=$(whiptail --title "CONTRASEÑA SQL" --passwordbox "Confirme la contraseña:" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) --ok-button "Continuar" --nocancel 3>&1 1>&2 2>&3) comprobarError $? 1 #echo -en "SQL Password 1: $sqlPasswd\n" #echo -en "SQL Password 2: $sqlPasswd2\n" if [ -z "$sqlPasswd" ] || [ -z "$sqlPasswd2" ]; then error="ERROR: LA CONTRASEÑA NO PUEDE ESTAR VACIA.\n" elif [ $sqlPasswd != $sqlPasswd2 ];then error="ERROR: LAS CONTRASEÑAS NO COINCIDEN.\n" else control=true fi done #echo -en "SQL Password: $sqlPasswd\n" unset control error sqlPasswd2 } establecerSQLPasswd() { # Establecemos SQL root passwd y securizamos BD (mysql_secure_installation) # Comprobamos si ya tiene una contraseña asignada mysql -e "FLUSH PRIVILEGES" >> $logFile 2>&1 if [ $? -eq 0 ];then # Establecemos contraseña del usuario root (y desactivamos posibles plugins para forzar login por contraseña) mysql -e "UPDATE mysql.user SET plugin = '', Password = PASSWORD('$sqlPasswd') WHERE User = 'root'" >> $logFile 2>&1 if [ $? -ne 0 ];then # Lo intentamos de otra forma (para versiones modernas de mysql) mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$sqlPasswd'" >> $logFile 2>&1 comprobarError $? 207 fi # Aplicamos el cambio de contraseña mysql -e "FLUSH PRIVILEGES" >> $logFile 2>&1 # Desactivamos acceso root desde el exterior (solo localhost) mysql -u root --password=$sqlPasswd -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1')" >> $logFile 2>&1 comprobarError $? 208 # Eliminamos todos los usuarios anónimos mysql -u root --password=$sqlPasswd -e "DELETE FROM mysql.user WHERE User=''" >> $logFile 2>&1 comprobarError $? 209 # Eliminamos bases de datos 'test' mysql -u root --password=$sqlPasswd -e "DROP DATABASE IF EXISTS test" >> $logFile 2>&1 comprobarError $? 210 # Eliminamos privilegios de la base de datos 'test' mysql -u root --password=$sqlPasswd -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'" >> $logFile 2>&1 comprobarError $? 211 # Aplicamos los cambios mysql -u root --password=$sqlPasswd -e "FLUSH PRIVILEGES" >> $logFile 2>&1 comprobarError $? 212 else comprobarError 1 206 fi } instalarMySQL() { # Instala MySQL (sólo para Debian) sqlServerName="mysql" if [ $debianOS = true ];then result=$(apt-get -q -y install mysql-server mysql-client 2>&1) comprobarError $? 201 $result elif [ $rhelOS = true ];then # MySQL no disponible en RHEL. 2 opciones: # 1) Instalar un repositorio adicional # 2) No instalar MySQL en distribuciones RHEL comprobarError 1 205 else comprobarError 1 203 fi deshabilitarServicio $sqlServerName } instalarMariaDB() { # Instala MariaDB sqlServerName="mariadb" if [ $debianOS = true ];then result=$(apt-get -q -y install mariadb-server mariadb-client 2>&1) comprobarError $? 202 $result elif [ $rhelOS = true ];then result=$(yum -y install mariadb-server mariadb 2>&1) comprobarError $? 202 $result else comprobarError 1 204 fi deshabilitarServicio $sqlServerName } configurarSQL() { # Configura BarracudaFS en mysql (necesario para Moodle) # Configura MariaDB o MySQL if [ $mariaDBOn = true ] && [ $debianOS = true ];then sqlConfFile="/etc/mysql/my.cnf" elif [ $mariaDBOn = true ] && [ $rhelOS = true ];then sqlConfFile="/etc/my.cnf" elif [ $mySQLOn = true ] && [ $debianOS = true ];then sqlConfFile="/etc/mysql/my.cnf" else comprobarError 1 213 fi if [ ! -f $sqlConfFile ];then comprobarError 1 213 fi grep "# Configuration for Moodle" $sqlConfFile >/dev/null 2>&1 if [ $? -ne 0 ];then # Establecemos UTF8 (codificación de caracteres) y Barracuda (sistema de ficheros) echo -en "\n# Configuration for Moodle\n" >> $sqlConfFile echo -en "[client]\n" >> $sqlConfFile echo -en "default-character-set = utf8mb4\n\n" >> $sqlConfFile echo -en "[mysqld]\n" >> $sqlConfFile echo -en "innodb_file_format = Barracuda\n" >> $sqlConfFile echo -en "innodb_file_per_table = 1\n" >> $sqlConfFile echo -en "innodb_large_prefix\n\n" >> $sqlConfFile echo -en "character-set-server = utf8mb4\n" >> $sqlConfFile echo -en "collation-server = utf8mb4_unicode_ci\n" >> $sqlConfFile echo -en "skip-character-set-client-handshake\n\n" >> $sqlConfFile echo -en "[mysql]\n" >> $sqlConfFile echo -en "default-character-set = utf8mb4\n" >> $sqlConfFile else comprobarError 1 214 fi unset sqlConfFile } instalarPHP() { # Instalamos PHP-7 y los módulos PHP que necesitan MediaWiki y Moodle if [ $debianOS = true ];then if [ $apacheOn = true ]; then result=$(apt-get -q -y install php libapache2-mod-php php-mysql php-intl php-mbstring php-xml php-apcu php-gd php-curl php-zip php-soap php-xmlrpc 2>&1) comprobarError $? 302 $result elif [ $nginxOn = true ];then phpFPMName="php7.2-fpm" result=$(apt-get -q -y install php-fpm php-mysql php-intl php-mbstring php-xml php-apcu php-gd php-curl php-zip php-soap php-xmlrpc 2>&1) comprobarError $? 302 $result deshabilitarServicio $phpFPMName else comprobarError 1 301 fi elif [ $rhelOS = true ];then # Necesitamos un repositorio adicional para PHP-7 (EPEL-RELEASE) result=$(yum -y install epel-release yum-utils 2>&1) comprobarError $? 103 $result # Necesitamos un repositorio adicional para PHP-7 (REMI-RELEASE) if [ ! -f /etc/yum.repos.d/remi-php72.repo ];then if [ $VERSION = "7" ];then result=$(yum -y install http://remi.mirrors.cu.be/enterprise/remi-release-7.rpm 2>&1) comprobarError $? 303 $result elif [ $VERSION = "6" ];then result=$(yum -y install http://remi.mirrors.cu.be/enterprise/remi-release-6.rpm 2>&1) comprobarError $? 303 $result elif [ $VERSION = "28" ];then result=$(yum -y install http://remi.mirrors.cu.be/fedora/remi-release-28.rpm 2>&1) comprobarError $? 303 $result elif [ $VERSION = "27" ];then result=$(yum -y install http://remi.mirrors.cu.be/fedora/remi-release-27.rpm 2>&1) comprobarError $? 303 $result else comprobarError 1 304 fi fi # Activamos repositorio remi-php72 result=$(yum-config-manager --enable remi-php72 2>&1) comprobarError $? 303 $result # Instalamos PHP-7.2 if [ $apacheOn = true ];then result=$(yum -y install php php-mysql php-intl php-mbstring php-mcrypt php-xml php-pecl-apcu php-gd php-pear-Net-Curl php-pecl-zip php-soap php-xmlrpc 2>&1) comprobarError $? 302 $result elif [ $nginxOn = true ];then phpFPMName="php-fpm" result=$(yum -y install php php-fpm php-mysql php-intl php-mbstring php-mcrypt php-xml php-pecl-apcu php-gd php-pear-Net-Curl php-pecl-zip php-soap php-xmlrpc 2>&1) comprobarError $? 302 $result deshabilitarServicio $phpFPMName else comprobarError 1 301 fi else comprobarError 1 300 fi } configurarPHP() { # Configura PHP para segurizarlo y establecer máximo de subida. if [ $debianOS = true ];then phpConfFile="./etc/php/php.ini.debian" phpDest="/etc/php/7.2/cli/php.ini" elif [ $rhelOS = true ];then phpConfFile="./etc/php/php.ini.rhel" phpDest="/etc/php.ini" fi if [ ! -f $phpConfFile ];then comprobarError 1 4 "$phpConfFile" fi # Copiamos configuración cp -f $phpConfFile $phpDest 2>/dev/null comprobarError $? 305 # Configuramos cgi.fix_pathinfo sed -i '/cgi.fix_pathinfo=/c\cgi.fix_pathinfo=0' $phpDest comprobarError $? 305 # Configuramos post_max_size sed -i '/post_max_size =/c\post_max_size = '$maxUpload $phpDest comprobarError $? 305 # Configuramos upload_max_filesize sed -i '/upload_max_filesize =/c\upload_max_filesize = '$maxUpload $phpDest comprobarError $? 305 # Configurar php-fpm (sólo en RHEL con Nginx) if [ $rhelOS = true ] && [ $nginxOn = true ];then # Configurar Socket UNIX phpConfFile="./etc/php/php-fpm.d/www.conf" phpDest="/etc/php-fpm.d/www.conf" if [ ! -f $phpConfFile ];then comprobarError $? 4 "$phpConfFile" fi cp -f $phpConfFile $phpDest 2>/dev/null comprobarError $? 305 # Configurar Permisos /var/lib/php chown -R $webServerUser:$webServerGroup /var/lib/php/ comprobarError $? 305 fi unset phpConfFile phpDest } establecerMaxUpload() { # Pantalla para establecer el máximo de subida al servidor (vía PHP) control=false error="" while [ $control = false ];do maxUpload2=$(whiptail --title "PHP MAX UPLOAD" --inputbox "$error""Introduzca el tamaño máximo permitido de los ficheros subidos al servidor:\n( )" $((ALTO * 9 / 10)) $((ANCHO * 9 / 10)) $maxUpload --ok-button "Continuar" --cancel-button "Salir" 3>&1 1>&2 2>&3) comprobarError $? 1 if [ -z "$maxUpload2" ];then error="ERROR: NO PUEDES DEJAR ESTE PARÁMETRO VACIO.\n" else control=true fi done maxUpload=$maxUpload2 unset control maxUpload2 } instalarPHPInfo() { # Instalar fichero info.php y su VirtualHost if [ ! -f /etc/$webServerName/sites-enabled/phpinfo.conf ];then infoFile="./var/www/info.php" if [ ! -f $infoFile ];then comprobarError 1 4 "$infoFile" fi mkdir /var/www/localhost 2>/dev/null comprobarError $? 106 cp -f $infoFile /var/www/localhost/ 2>/dev/null comprobarError $? 106 chown -R $webServerUser:$webServerGroup /var/www/localhost 2>/dev/null comprobarError $? 106 unset infoFile # Instalar VirtualHost if [ $apacheOn = true ] && [ $sslOn = false ];then virtualHost="./etc/apache2/sites-available/phpinfo.conf" elif [ $nginxOn = true ] && [ $sslOn = false ];then virtualHost="./etc/nginx/sites-available/phpinfo.conf" elif [ $apacheOn = true ] && [ $sslOn = true ];then virtualHost="./etc/apache2/sites-available/phpinfo-ssl.conf" elif [ $nginxOn = true ] && [ $sslOn = true ];then virtualHost="./etc/nginx/sites-available/phpinfo-ssl.conf" else comprobarError 1 106 fi instalarVirtualHost "/var/www/localhost" $virtualHost "localhost" unset virtualHost return 0 else return 1 fi } habilitarServicio() { # Arrancamos y habilitamos el servicio (con SystemD, Upstart o SystemV) # Intentamos con systemctl (SystemD) #echo -en "Habilitando Servicio '$1'" | tee -a $logFile if [ $# -le 0 ];then comprobarError 1 900 fi which systemctl > /dev/null 2>&1 if [ $? -eq 0 ]; then #echo -en " (SystemD)..." | tee -a $logFile systemctl start $1 > /dev/null 2>&1 comprobarError $? 901 $1 systemctl enable $1 > /dev/null 2>&1 comprobarError $? 902 $1 else # Intentamos con service (Upstart) which service > /dev/null 2>&1 if [ $? -eq 0 ]; then #echo -en " (Upstart)..." | tee -a $logFile service $1 start > /dev/null 2>&1 comprobarError $? 901 $1 else # Intentamos con init.d (SystemV) #echo -en " (SystemV)..." | tee -a $logFile /etc/init.d/$1 start > /dev/null 2>&1 comprobarError $? 901 $1 fi # Intentamos habilitar en el arranque (Upstart) which update-rc.d > /dev/null 2>&1 if [ $? -eq 0 ];then update-rc.d $1 enable comprobarError $? 902 $1 else # Intentamos habilitar en el arranque (SystemV) which chkconfig > /dev/null 2>&1 if [ $? -eq 0 ];then chkconfig $1 on comprobarError $? 902 $1 else # ¿Qué mas opciones nos quedan? comprobarError 1 902 $1 fi fi fi # Mejora: comprobar si el servicio está parado #echo -en " OK.\n" | tee -a $logFile } deshabilitarServicio() { # Paramos y deshabilitamos el servicio (con SystemD, Upstart o SystemV) # Intentamos con systemctl (SystemD) #echo -en "Deshabilitando Servicio '$1'" | tee -a $logFile if [ $# -le 0 ];then comprobarError 1 903 fi which systemctl > /dev/null 2>&1 if [ $? -eq 0 ]; then #echo -en " (SystemD)..." | tee -a $logFile systemctl stop $1 > /dev/null 2>&1 comprobarError $? 904 $1 systemctl disable $1 > /dev/null 2>&1 comprobarError $? 905 $1 else # Intentamos con service (Upstart) which service > /dev/null 2>&1 if [ $? -eq 0 ]; then #echo -en " (Upstart)..." | tee -a $logFile service $1 stop > /dev/null 2>&1 comprobarError $? 904 $1 else # Intentamos con init.d (SystemV) #echo -en " (SystemV)..." | tee -a $logFile /etc/init.d/$1 stop > /dev/null 2>&1 comprobarError $? 904 $1 fi # Intentamos habilitar en el arranque (Upstart) which update-rc.d > /dev/null 2>&1 if [ $? -eq 0 ];then update-rc.d $1 disable comprobarError $? 905 $1 else # Intentamos habilitar en el arranque (SystemV) which chkconfig > /dev/null 2>&1 if [ $? -eq 0 ];then chkconfig $1 off comprobarError $? 905 $1 else # ¿Qué mas opciones nos quedan? comprobarError 1 905 $1 fi fi fi # Mejora: comprobar si el servicio está funcionando #echo -en " OK.\n" | tee -a $logFile } recargarServicio() { # Recargamos el servicio (con SystemD, Upstart o SystemV) # Intentamos con systemctl (SystemD) #echo -en "Recargando Servicio '$1'" | tee -a $logFile if [ $# -le 0 ];then comprobarError 1 912 fi which systemctl > /dev/null 2>&1 if [ $? -eq 0 ]; then #echo -en " (SystemD)..." | tee -a $logFile systemctl reload $1 > /dev/null 2>&1 comprobarError $? 913 $1 else # Intentamos con service (Upstart) which service > /dev/null 2>&1 if [ $? -eq 0 ]; then #echo -en " (Upstart)..." | tee -a $logFile service $1 reload > /dev/null 2>&1 comprobarError $? 913 $1 else # Intentamos con init.d (SystemV) #echo -en " (SystemV)..." | tee -a $logFile /etc/init.d/$1 reload > /dev/null 2>&1 comprobarError $? 913 $1 fi fi # Mejora: comprobar si el servicio está funcionando #echo -en " OK.\n" | tee -a $logFile } configurarCortafuegos() { # Configuramos cortafuegos (añadir reglas y encender) # Comprobamos si estamos usando SSH esSSH $PPID if [ $debianOS = true ];then ufw allow 80/tcp >> $logFile 2>&1 comprobarError $? 906 "80/tcp" if [ $sshControl = true ];then ufw allow 22/tcp >> $logFile 2>&1 comprobarError $? 906 "22/tcp" fi if [ $sslOn = true ];then ufw allow 443/tcp >> $logFile 2>&1 comprobarError $? 906 "443/tcp" fi ufw --force enable >> $logFile 2>&1 comprobarError $? 907 elif [ $rhelOS = true ];then firewall-cmd --add-port=80/tcp >> $logFile 2>&1 comprobarError $? 906 "80/tcp" if [ $sshControl = true ];then firewall-cmd --add-port=22/tcp >> $logFile 2>&1 comprobarError $? 906 "22/tcp" fi if [ $sslOn = true ];then firewall-cmd --add-port=443/tcp >> $logFile 2>&1 comprobarError $? 906 "443/tcp" fi firewall-cmd --runtime-to-permanent >> $logFile 2>&1 comprobarError $? 907 habilitarServicio firewalld >> $logFile 2>&1 comprobarError $? 907 fi unset sshControl } esSSH() { # Comprobamos si nuestro terminal usa SSH p=${1:-$PPID} #read pid name x ppid y < <( cat /proc/$p/stat ) read pid name ppid < <( ps -o pid= -o comm= -o ppid= -p $p) [[ "$name" =~ sshd ]] && { sshControl=true; return 0; } [ "$ppid" -le 1 ] && { sshControl=false; return 1; } esSSH $ppid } descargarMediaWiki() { # Descargar la versión 1.31.0 de MediaWiki if [ ! -d ./var ];then comprobarError 1 5 "./var" fi curl "https://releases.wikimedia.org/mediawiki/1.31/mediawiki-1.31.0.tar.gz" 2>/dev/null | tar -xz -C "./var/" comprobarError $? 501 } configurarMediaWiki() { # Configuramos MediaWiki if [ ! -f /var/www/$dominioMediaWiki/LocalSettings.php ];then # Copiamos archivos cp -fR ./var/mediawiki-1.31.0/ /var/www/$dominioMediaWiki comprobarError $? 502 # Configuramos LocalSettings.php (y crea la base de datos por nosotros) nombreDBMW=$(echo $dominioMediaWiki | sed -e 's/\./_/g') userDBMW=$(echo $dominioMediaWiki | sed -e 's/\./_/g') php /var/www/$dominioMediaWiki/maintenance/install.php --dbname=$nombreDBMW --dbserver="localhost" --installdbuser=root --installdbpass=$sqlPasswd --dbuser=$userDBMW --dbpass=$sqlPasswd --scriptpath="" --lang=es --pass=$passwdMediaWiki --with-extensions "$nombreMediaWiki" "admin" >> $logFile 2>&1 comprobarError $? 502 # Configuraciones adicionales sed -i '/$wgLanguageCode =/c\$wgLanguageCode = "es";' /var/www/$dominioMediaWiki/LocalSettings.php comprobarError $? 502 sed -i '/$wgEnableEmail =/c\$wgEnableEmail = false;' /var/www/$dominioMediaWiki/LocalSettings.php comprobarError $? 502 sed -i '/$wgEnableUploads =/c\$wgEnableUploads = true;' /var/www/$dominioMediaWiki/LocalSettings.php comprobarError $? 502 echo -en "\$wgArticlePath = \"/wiki/\$1\";\n" >> /var/www/$dominioMediaWiki/LocalSettings.php echo -en "\$wgUsePathInfo = true;\n" >> /var/www/$dominioMediaWiki/LocalSettings.php echo -en "\$wgGroupPermissions['*']['createaccount'] = true;\n" >> /var/www/$dominioMediaWiki/LocalSettings.php echo -en "\$wgGroupPermissions['*']['edit'] = false;\n" >> /var/www/$dominioMediaWiki/LocalSettings.php echo -en "\$wgGroupPermissions['*']['read'] = true;\n" >> /var/www/$dominioMediaWiki/LocalSettings.php # Actualizamos permisos chown -R $webServerUser:$webServerGroup /var/www/$dominioMediaWiki comprobarError $? 502 # Configuramos VirtualHost if [ $apacheOn = true ] && [ $sslOn = false ];then virtualHost="./etc/apache2/sites-available/mediawiki.conf" elif [ $nginxOn = true ] && [ $sslOn = false ];then virtualHost="./etc/nginx/sites-available/mediawiki.conf" elif [ $apacheOn = true ] && [ $sslOn = true ];then virtualHost="./etc/apache2/sites-available/mediawiki-ssl.conf" elif [ $nginxOn = true ] && [ $sslOn = true ];then virtualHost="./etc/nginx/sites-available/mediawiki-ssl.conf" else comprobarError 1 502 fi if [ ! -f $virtualHost ];then comprobarError $? 502 fi instalarVirtualHost "/var/www/$dominioMediaWiki" $virtualHost $dominioMediaWiki $aliasMediaWiki unset virtualHost else comprobarError 1 503 $dominioMediaWiki fi } descargarMoodle() { # Descargar la versión 1.31.0 de MediaWiki if [ ! -d ./var ];then comprobarError 1 5 "./var" fi #echo -en "Descargando Moodle-3.5-1..." | tee -a $logFile #curl -o "./var/moodle-3.5.1.tgz" "https://download.moodle.org/download.php/direct/stable35/moodle-latest-35.tgz" >> $logFile 2>&1 curl "https://download.moodle.org/download.php/direct/stable35/moodle-latest-35.tgz" 2>/dev/null | tar -xz -C "./var/" comprobarError $? 501 #echo -en " OK.\n" | tee -a $logFile } configurarMoodle() { # Configurar Moodle if [ ! -f /var/www/$dominioMoodle/config.php ];then # Copiamos archivos cp -Rf ./var/moodle/ /var/www/$dominioMoodle comprobarError $? 602 # Crear carperta de datos (no online) if [ ! -d /var/www/moodledata ];then mkdir /var/www/moodledata 2>/dev/null comprobarError $? 602 fi #Actualizamos permisos perm=$(stat -c %a /var/www/moodledata) if [ $perm -ne 777 ];then chmod -R 777 /var/www/moodledata 2>/dev/null comprobarError $? 602 fi perm=$(stat -c %U /var/www/moodledata) if [ $perm != "$webServerUser" ];then chown -R $webServerUser:$webServerGroup /var/www/moodledata 2>/dev/null comprobarError $? 602 fi unset perm # Creamos Base de Datos nombreDBMo=$(echo $dominioMoodle | sed -e 's/\./_/g') userDBMo=$(echo $dominioMoodle | sed -e 's/\./_/g') crearDBMoodle # Configurar SE-Linux (RHEL) if [ $rhelOS = true ];then configurarSELinux fi # Configuramos e instalamos Moodle if [ $sslOn = true ];then wwwroot="https://$dominioMoodle" else wwwroot="http://$dominioMoodle" fi if [ $mySQLOn = true ];then dbtype="mysqli" elif [ $mariaDBOn = true ];then dbtype="mariadb" else comprobarError 1 602 fi php /var/www/$dominioMoodle/admin/cli/install.php --lang=es --wwwroot="$wwwroot" --dataroot="/var/www/moodledata" --dbtype="$dbtype" --dbname="$nombreDBMo" --dbuser="$userDBMo" --dbpass="$sqlPasswd" --fullname="$nombreMoodle" --shortname="$nombreCortoMoodle" --adminuser=admin --adminpass="$passwdMoodle" --adminemail="admin@$dominioMoodle" --agree-license --non-interactive >>$logFile 2>&1 comprobarError $? 602 # Actualizamos permisos chown -R $webServerUser:$webServerGroup /var/www/$dominioMoodle /var/www/moodledata # Configuramos VirtualHost if [ $apacheOn = true ] && [ $sslOn = false ];then virtualHost="./etc/apache2/sites-available/moodle.conf" elif [ $nginxOn = true ] && [ $sslOn = false ];then virtualHost="./etc/nginx/sites-available/moodle.conf" elif [ $apacheOn = true ] && [ $sslOn = true ];then virtualHost="./etc/apache2/sites-available/moodle-ssl.conf" elif [ $nginxOn = true ] && [ $sslOn = true ];then virtualHost="./etc/nginx/sites-available/moodle-ssl.conf" else comprobarError 1 602 fi instalarVirtualHost "/var/www/$dominioMoodle" $virtualHost $dominioMoodle unset virtualHost wwwroot dbtype else comprobarError 1 603 $dominioMoodle fi } crearDBMoodle() { # Crear base de datos para Moodle dbDir="./etc/db" if [ ! -d $dbDir ];then mkdir $dbDir 2>/dev/null comprobarError $? 503 fi dbFile=$dbDir"/moodle.sql" echo -en "CREATE DATABASE IF NOT EXISTS $nombreDBMo DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;\n" > $dbFile echo -en "GRANT ALL PRIVILEGES ON $nombreDBMo.* TO '$userDBMo'@'localhost' IDENTIFIED BY '$sqlPasswd';\n" >> $dbFile mysql -u root --password=$sqlPasswd < $dbFile control=$? rm -f $dbFile 2>/dev/null comprobarError $? 503 comprobarError $control 503 unset control dbFile dbDir } configurarSELinux() { # Configurar SELinux (Sólo para RHEL) which semanage >/dev/null 2>&1 if [ $? -ne 0 ];then result=$(yum -y install policycoreutils-python 2>&1) comprobarError $? 605 $result fi semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/moodledata(/.*)?" > /dev/null 2>&1 comprobarError $? 604 restorecon -R /var/www/ > /dev/null 2>&1 comprobarError $? 604 } # Comprobación del sistema e inicialización inicializarVariables comprobarRoot OSInfo comprobarDependencias # Bienvenida mostrarBienvenida # Selección de componentes (express vs avanzada) mostrarExpress # Instalación Servidor Web if [ $apacheOn = true ]; then echo -en "Instalando Servidor Web Apache..." | tee -a $logFile instalarApache echo -en " OK.\n" | tee -a $logFile elif [ $nginxOn = true ]; then echo -en "Instalando Servidor Web Nginx..." | tee -a $logFile instalarNginx echo -en " OK.\n" | tee -a $logFile fi # Instalación Base de Datos if [ $mySQLOn = true ]; then echo -en "Instalando Base de Datos MySQL..." | tee -a $logFile instalarMySQL echo -en " OK.\n" | tee -a $logFile elif [ $mariaDBOn = true ]; then echo -en "Instalando Base de Datos MariaDB..." | tee -a $logFile instalarMariaDB echo -en " OK.\n" | tee -a $logFile fi # Instalación PHP-7.2 if [ $phpOn = true ]; then echo -en "Instalando PHP-7..." | tee -a $logFile instalarPHP echo -en " OK.\n" | tee -a $logFile fi # Instalación SSL/TLS if [ $sslOn = true ];then echo -en "Instalando SSL/TLS..." | tee -a $logfile sleep 2 echo -en " OK.\n" | tee -a $logFile fi # Configuración Web Server if [ $apacheOn = true ];then echo -en "Configurando Servidor Web Apache..." | tee -a $logFile configurarApache echo -en " OK.\n" | tee -a $logFile elif [ $nginxOn = true ]; then echo -en "Configurando Servidor Web Nginx..." | tee -a $logFile configurarNginx echo -en " OK.\n" | tee -a $logFile fi # Configuración Database (Arrancar Base de Datos, establecer contraseña y configuración segura) if [ $mySQLOn = true ] || [ $mariaDBOn = true ];then echo -en "Configurando Base de Datos..." | tee -a $logFile configurarSQL echo -en " OK.\n" | tee -a $logFile habilitarServicio "$sqlServerName" echo -en "Estableciendo contraseña de la Base de Datos..." | tee -a $logFile establecerSQLPasswd echo -en " OK.\n" | tee -a $logFile fi # Configuración PHP (cgi.fix_pathinfo=0 y Configurar máximo de subida de archivos) if [ $phpOn = true ];then echo -en "Configurando PHP-7..." | tee -a $logFile configurarPHP echo -en " OK.\n" | tee -a $logFile fi # Configuración SSL/TLS # Generar certificados # Configurar certificados if [ $sslOn = true ];then echo -en "Configurando SSL/TLS..." | tee -a $logFile sleep 2 echo -en " OK.\n" | tee -a $logFile fi # Arrancar y habilitar todos los servicios (SystemD, Service o SystemV) echo -en "Habilitando todos los servicios..." | tee -a $logFile if [ $apacheOn = true ];then habilitarServicio $webServerName elif [ $nginxOn = true ];then habilitarServicio $webServerName if [ $phpOn = true ];then habilitarServicio $phpFPMName fi fi echo -en " OK.\n" | tee -a $logFile # MediaWiki if [ $mediaWikiOn = true ]; then # Descargar MediaWiki echo -en "Descargando MediaWiki-1.31.0..." | tee -a $logFile descargarMediaWiki echo -en " OK.\n" | tee -a $logFile # Configurar MediWiki echo -en "Configurando MediaWiki..." | tee -a $logFile configurarMediaWiki echo -en " OK.\n" | tee -a $logFile fi # Moodle if [ $moodleOn = true ]; then # Descargar Moodle echo -en "Descargando Moodle-3.5.1..." | tee -a $logFile descargarMoodle echo -en " OK.\n" | tee -a $logFile # Configuración Moodle echo -en "Configurando Moodle (puede llevar un tiempo largo)..." | tee -a $logFile configurarMoodle echo -en " OK.\n" | tee -a $logFile fi # Configurar Virtual Hosts # Instalar info.php if [ $infoPHPOn = true ];then echo -en "Configurando 'info.php'..." | tee -a $logFile instalarPHPInfo if [ $? -eq 0 ];then echo -en " OK.\n" | tee -a $logFile else echo -en " Ya se encuentra configurado.\n" | tee -a $logFile fi fi # Añadir reglas del cortafuegos echo -en "Configurando Cortafuegos..." | tee -a $logFile configurarCortafuegos echo -en " OK.\n" | tee -a $logFile # Configurar Backup if [ $backupOn = true ]; then echo -en "Configurando Backup Automático..." | tee -a $logFile sleep 2 echo -en " OK.\n" | tee -a $logFile fi