Administración por línea de comando

De MoodleDocs

Nota: Esta es una traducción de una página de la documentación en idioma Inglés (Docs), que se considera particularmente importante, y que en su versión original se actualiza frecuentemente. Por ello, se le recomienda que revise la página original en idioma inglés: Administration via command line.

Esta página necesita actualizarse con la información existente en la documentación vigente/moderna/actualizada en el idioma inglés original para Moodle. Se le sugiere al lector que consulte la página original en idioma inglés cuyo enlace está al fondo de esta página. y que, por favor, actualice esta información y quite la plantilla {{Actualizar}} cuando haya terminado.     (otras páginas pendientes de actualizar)


Corriendo scripts con Interfaz por Línea de Comandos ((CLI)

Si Usted tiene acceso de shell a su servidor web, Usted puede encontrar varios scripts CLI (CLI = Command Line Interfase) útiles para la administración de Moodle. Las herramientas de CLI del núcleo de Moodle están localizadas en la carpeta admin/cli/*. Otros plugins proporcionan su funcionalidad CLI mediante scripts en sus propias carpetas cli. Por ejemplo, el script de sincronización enrol_db está localizado en enrol/db/cli/.

Para evitar problemas con el control de acceso, Usted debería de correr los scripts como el propietario del proceso del servidor web. Es especialmente importante para la instalación y actualización por CLI, dado que crean archivos nuevos en el directorio moodledata, y el servidor web tiene que tener acceso de escritura a ellos. En las distribuciones Linux, el usuario que corre el servidor web usualmente es apache o wwrun o httpd o algo similar. Como root Usted probablemente querrá ejecutar los scripts CLI de Moodle de esta manera:

   $ cd /path/to/your/moodle/dir
   $ sudo -u apache /usr/bin/php admin/cli/somescript.php --params

La mayoría de los scripts aceptan el parámetro común --help (o -h) para mostrarle la información completa respecto al uso, por ejemplo:

   $ sudo -u apache /usr/bin/php admin/cli/install.php --help


Nota: Estos scripts están para ser corridos (ejecutados) bajo la identidad del usuario del servidor web. Los ejemplos en esta página usan al usuario apache para ilustración. El valor particular depende de su distribución de Sistema Operativo y de su configuración local. Los valores típicos suelen ser apache, www-data (Ubuntu) o httpd.


¡Nueva característica
en Moodle 3.0!
Si se necesita, la instalación de la BasedeDatos puede saltarse, poblando únicamente config.php.

 $ sudo -u apache /usr/bin/php admin/cli/install.php --skip-database

Actualización por línea de comando

Moodle puede ser actualizado mediante línea de comando. Al igual que con el script de instalación, hay un modo interactivo y otro no-interactivo para actualizar. El script por sí mismo no pone al sitio en modo de mantenimiento, Usted mismo tiene que hacerlo. También, tome nota de que el script no respalda los datos (pero si está leyendo esta página Usted probablemente tenga sus propios scripts para respaldar moodledata y la BasedeDatos ¿o nó?)

   $ sudo -u apache /usr/bin/php admin/cli/upgrade.php

Actualizar mediante línea de comando es una forma muy cómoda de actualizar Moodle si Usted usa Git checkout' del código fuente de Moodle (vea Git para Administradores). Vea el siguiente procedimiento sobre cómo actualizar su sitio a los pocos segundos de la versión más reciente, al mismo tiempo que preserva sus eventuales personalizaciones locales seguidas en el repositorio git:

   $ cd /var/www/sites/moodle/htdocs/
   $ sudo -u apache /usr/bin/php admin/cli/maintenance.php --enable
   $ git pull
   $ sudo -u apache /usr/bin/php admin/cli/upgrade.php
   $ sudo -u apache /usr/bin/php admin/cli/maintenance.php --disable

Instalación por línea de comando

Since version 2.0, Moodle can be installed from the command line. There are two modes of installation. In interactive mode, the install script asks you for all data needed to properly set up new Moodle site. In non-interactive mode, you must provide all required data as the script parameters and then the new site is installed silently. The parameters can be passed in the interactive mode, too. The provided values are then used as the default values during the interactive session.

   $ sudo -u apache /usr/bin/php admin/cli/install.php --lang=cs

Modo de mantenimiento

Para cambiar su sitio hacia Modo de mantenimiento mediante la Interfaz por Línea de Comando, Usted puede usar

   $ sudo -u apache /usr/bin/php admin/cli/maintenance.php --enable

Para desactivar el Modo de mantenimiento, simplemente ejecute el mismo script con --disable parameter.

   $ sudo -u apache /usr/bin/php admin/cli/maintenance.php --disable

Si no quiere habilitar inmediatamente el modo de mantenimiento, sino mostrar un cronómetro descendiente a sus usuarios. ejecute el mismo script con el parámetro --enablelater y el número de minutos que debería correr el conteo regresivo:

   $ sudo -u apache /usr/bin/php admin/cli/maintenance.php --enablelater=10

Este script también creará y quitará el archivo climaintenance.html para el modo "Fuera-de-línea (Offline)".

Modo fuera de línea (Offline)

In some situations, you may want to switch your Moodle site into offline mode so that it is not accessible via the web but you can not stop the web server completely (typically because there are other web pages and applications running there). If a file called climaintenance.html exists in the root folder of moodledata directory, Moodle will automatically display the contents of that file instead of any other page.

   $ cd /var/www/sites/moodle/moodledata/
   $ echo '<h1>Sorry, maintenance in progress</h1>' > climaintenance.html

You can prepare a nice formatted HTML page to inform your users about the server being down and keep in the moodledata directory under a name like climaintenance.off and rename it to the climaintenance.html if needed.

Valores por defecto personalizados del sitio (Custom site defaults)

During the install and upgrade via CLI, Moodle sets the administration variables to the default values. You can use different defaults. See MDL-17850 for details. Shortly, all you need to do is to add a file local/defaults.php into your Moodle installation. The format of the file is like

<?php $defaults['pluginname']['settingname'] = 'settingvalue'; // for plugins $defaults['moodle']['settingname'] = 'settingvalue'; // for core settings

These defaults are used during install, upgrade and are also displayed as defaults at the Site administration pages.

Reiniciar contraseña de usuario

Si Usted perdiera su contraseña de administrador (o si quiere configurar una contraseña para cualquier otro usuario de su sistema Moodle), Usted puede usar el script reset_password.php que configura la contraseña correctamente salada para el usuario dado.

   $ sudo -u apache /usr/bin/php admin/cli/reset_password.php

Conversión de motor de almacenamiento MySQL

Nota: Pendiente de Traducir. ¡Anímese a traducir esta página!.     ( y otras páginas pendientes)

If you run your Moodle site with MySQL database backend and use the default MyISAM as the storage engine for your tables, you may want to convert them to use some more reliable engine like InnoDB (actually, you should want to switch to PostgreSQL ;-) anyway).

   $ sudo -u apache /usr/bin/php admin/cli/mysql_engine.php --engine=InnoDB

Convertir tablas InnoDB a Barracuda

Sites using MySQL with database tables using Antelope as the file format are recommended to convert the tables to the Barracuda file format.

This is because tables using Antelope as the file format cannot handle more than 10 text columns. This file formats only supports compact and redundant row formats for backward compatibility reasons. This may cause a problem on larger sites when restoring a course, in which case the following error will be displayed:

Row size too large (>8126). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED may help.

Barracuda is the newest innoDB file format. In addition to supporting compact and redundant row formats, Barracuda also supports compressed and dynamic row formats.

However, converting tables to Barracuda is only recommended, and not required, since not all MySQL users are affected. (It may only be a problem for larger sites.)

Herramienta para convertir tablas

Moodle incluye una herramienta de línea de comandos para convertir tablas a Barracuda.

Para ver las tablas que requieren conversión, use la opción de lista:

$ php admin/cli/mysql_compressed_rows.php --list

Aquí hay una salida de ejemplo:

mdl_data                            Compact     (needs fixing) 
mdl_data_fields                     Compact     (needs fixing)
mdl_enrol_paypal                    Compact     (needs fixing)

Para continuar con la conversión, ejecute el comando usando la opción --fix:

$ php admin/cli/mysql_compressed_rows.php --fix

La conversión de tabla exitosa se informará en la salida, por ejemplo:

mdl_data                   ... Compressed
mdl_data_fields            ... Compressed
mdl_enrol_paypal           ... Compressed

Tenga en cuenta que los comandos deben ejecutarse en su directorio moodle. Una vez que se arreglen las tablas, el mensaje de advertencia ya no se mostrará.

Para obtener más información sobre los formatos de archivo InnoDB, consulte MySQL InnoDB glossary - Antelope y MySQL InnoDB glossary - Barracuda.

Si obtiene errores debido a que no tiene privilegios suficientes para ejecutar estos comandos (esto es bastante probable), entonces la solución más fácil es generar los comandos SQL requeridos usando:

$ php admin/cli/mysql_compressed_rows.php --showsql

Luego puede copiar el SQL generado en su cliente mysql que se ejecuta como usuario 'root'.

Convertir a la nueva colación y juego de caracteres

$ php admin/cli/mysql_collation.php --collation=utf8mb4_unicode_ci

ejecutar cron via línea de comando

In versions 1.x, you could execute admin/cron.php either from command line or via the web. Since Moodle 2.0, only admin/cli/cron.php script can be run via command line.

Trabajos agendados

Los Trabajos agendados son ejecutados automáticamente por el script cron de arriba, pero los trabajos específicos que corren en cada iteración del cron son determinados por la configuración de las Trabajos agendados. Es posible anular la configuración de los trabajos agendados y ejecutar un solo trabajo agendado inmediatamente usando el script admin/tool/task/cli/schedule_task.php.

Este script acepta los siguientes argumentos:

--list - list all the known scheduled tasks. The tasks are listed by the class name used to run the task. This class name is required as the argument to the next option in order to run a specific task immediately.
--execute=<task> - Runs a single scheduled task immediately - regardless of scheduling settings. This will even run disabled tasks. Tasks will still use locking to prevent concurrent execution of the same task - even on clusters. The format of the <task> argument must be the same as returned by the --list option above.
--disable=<task> - Disables a single scheduled task (New in 4.3 onwards). The format of the <task> argument must be the same as returned by the --list option above.
--enable=<task> - Enables a single scheduled task (New in 4.3 onwards). The format of the <task> argument must be the same as returned by the --list option above.
--showsql - Shows sql queries before they are execute
--showdebugging - Shows developer debugging info

Note: You must escape the "\" with an extra \ when using the --execute command. Take the following for example:

php schedule_task.php --list

will return something like:


== List of scheduled tasks (http://yourserver.com/moodle) ==
\enrol_imsenterprise\task\cron_task                10 * * * * *      ASAP
\logstore_legacy\task\cleanup_task                 * 5 * * * *       ASAP
\logstore_standard\task\cleanup_task               * 4 * * * *       Wednesday, November 12, 2014, 4:35 AM
\mod_forum\task\cron_task                          * * * * * *       ASAP
\core\task\automated_backup_task                   50 * * * * *      ASAP

...

To run the first task in that list, you would execute

php schedule_task.php --execute='\enrol_imsenterprise\task\cron_task'

Be aware of the single quotes. Without them, you would need to use double backlashes to avoid escaping by the shell.

Transferencias de base de datos

A command line script for Transferencia de la BasedeDatos may be found in admin/tool/dbtransfer/cli/migrate.php.

Purgar cachés

Puedes purgar caches usando este script:

 php admin/cli/purge_caches.php

Matar todas las sesiones

If needed for administrative reasons, you can kill all user sessions using this script:

php admin/cli/kill_all_sessions.php

As a result, all users will be logged out from Moodle.

Corregir secuencias de curso / módulo

In rare cases (such as after upgrading from a very old version of Moodle), the course / section / module sequence data can be out of sync. This can cause various problems for affected courses, such as sections not appearing, backups failing, pages not displaying etc. There is a specific check to check for errors caused by this problem, and to fix the data in the database if they are found. To run this script please use the command below:

 php admin/cli/fix_course_sequence.php -c=* --fix

This will check every course in Moodle and report which ones had errors and were fixed.

Corregir categorías huérfanas de preguntas

When a quiz is created, a new question category for the quiz is automatically created. In versions of Moodle prior to 2.9.1, if the quiz is deleted, the question category and any questions in the category remain in database. These orphaned question categories may be fixed by running the admin/cli/fix_orphaned_question_categories.php script with the --fix option.

Buscar y reemplazar texto

This script can be used to search and replace text throughout the whole database. Use carefully and backup first always. More info in Herramienta para buscar y remplazar.

 php admin/tool/replace/cli/replace.php --search=//oldsitehost --replace=//newsitehost

Construir caché CSS del tema

If Moodle is not running in theme designer mode it will keep a copy of the compiled CSS on local disk and serve that to the browser when it requests a page. If there isn't a copy on local disk then a copy will be built the first time a page within Moodle is requested.

With this script you can pre-compile the cached CSS files for themes within Moodle to avoid having a user wait for the theme to compile during the first page request.

 php admin/cli/build_theme_css.php --themes=boost

Vea también

  • MDL-35736 - Manage plugins via command line
  • MDL-36237 - Resort course list via CLI
  • MOOSH - MOOdle SHell. It is a commandline tool that will allow you to perform most common Moodle tasks.