LinuxParty

NUESTRO SITIO necesita la publicidad para costear hosting y el dominio. Por favor considera deshabilitar tu AdBlock en nuestro sitio. También puedes hacernos una donación entrando en linuxparty.es, en la columna de la derecha.
Inicio desactivadoInicio desactivadoInicio desactivadoInicio desactivadoInicio desactivado
 

Ejecute occ como su usuario HTTP

El usuario HTTP es diferente en las distintas distribuciones de Linux. Consulte Establecer permisos de directorio seguros para saber cómo encontrar su usuario HTTP.

  • El usuario HTTP y el grupo en Debian / Ubuntu es www-data.
  • El usuario y grupo HTTP en Fedora / CentOS es apache.
  • El usuario HTTP y el grupo en Arch Linux es http.
  • El usuario HTTP en openSUSE es wwwrun y el grupo HTTP es www.

Si su servidor HTTP está configurado para usar una versión de PHP diferente a la predeterminada ( /usr/bin/php), occ debe ejecutarse con la misma versión. Por ejemplo, en CentOS 6.5 con SCL-PHP54 instalado, el comando se ve así:

sudo -u apache /opt/rh/php54/root/usr/bin/php /var/www/html/owncloud/occ

Ejecutar occ sin opciones enumera todos los comandos y opciones, como este ejemplo en Ubuntu:

sudo -u www-data php occ
ownCloud version 9.0.0

Usage:
 command [options] [arguments]

Options:
 -h, --help            Display this help message
 -q, --quiet           Do not output any message
 -V, --version         Display this application version
     --ansi            Force ANSI output
     --no-ansi         Disable ANSI output
 -n, --no-interaction  Do not ask any interactive question
     --no-warnings     Skip global warnings, show command output only
 -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output,
                       2 for more verbose output and 3 for debug

Available commands:
 check                 check dependencies of the server
                       environment
 help                  Displays help for a command
 list                  Lists commands
 status                show some status information
 upgrade               run upgrade routines after installation of
                       a new release. The release has to be
                       installed before.

Este es el mismo que sudo -u www-data php occ list. Ejecútelo con la -hopción de ayuda de sintaxis:

sudo -u www-data php occ -h

Muestra tu versión de ownCloud:

sudo -u www-data php occ -V
  ownCloud version 9.0.0

Consulta el estado de tu servidor ownCloud:

sudo -u www-data php occ status
  - installed: true
  - version: 9.0.0.19
  - versionstring: 9.0.0
  - edition:

occ tiene opciones , comandos y argumentos . Se requieren comandos. Las opciones son opcionales. Los argumentos pueden ser obligatorios u opcionales. La sintaxis genérica es:

occ [opciones] comando [argumentos]

Obtenga información detallada sobre comandos individuales con el helpcomando, como este ejemplo para el maintenance:modecomando

sudo -u www-data php occ help maintenance:mode
Usage:
 maintenance:mode [options]

Options:
     --on              enable maintenance mode
     --off             disable maintenance mode
 -h, --help            Display this help message
 -q, --quiet           Do not output any message
 -V, --version         Display this application version
     --ansi            Force ANSI output
     --no-ansi         Disable ANSI output
 -n, --no-interaction  Do not ask any interactive question
     --no-warnings     Skip global warnings, show command output only
 -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output,
                       2 for more verbose output and 3 for debug

El comando status de arriba tiene una opción para definir el formato de salida. El valor predeterminado es texto sin formato, pero también puede ser json:

sudo -u www-data php occ status --output=json
{"installed":true,"version":"9.0.0.19","versionstring":"9.0.0","edition":""}

o bien json_pretty:

sudo -u www-data php occ status --output=json_pretty
{
   "installed": true,
   "version": "9.0.0.19",
   "versionstring": "9.0.0",
   "edition": ""
}

Esta opción de salida está disponible en toda la lista y la lista de comandos similar, que incluyen status, check, app:list, config:list, encryption:statusy encryption:list-modules.

Comandos de aplicaciones

Los comandos app enumeran, habilitan y deshabilitan aplicaciones

app
 app:check-code   check code to be compliant
 app:disable      disable an app
 app:enable       enable an app
 app:getpath      Get an absolute path to the app directory
 app:list         List all available apps

Enumere todas sus aplicaciones instaladas u opcionalmente proporcione un patrón de búsqueda para restringir la lista de aplicaciones a aquellas cuyo nombre coincida con la expresión regular dada. La salida muestra si están habilitados o deshabilitados

sudo -u www-data php occ app:list [<search-pattern>]

Habilite una aplicación, por ejemplo, la aplicación Market.

sudo -u www-data php occ app:enable market
market enabled

Deshabilitar una aplicación

sudo -u www-data php occ app:disable market
market disabled

app:check-code tiene varias comprobaciones: comprueba si una aplicación utiliza la API pública ( OCP) o la API privada ( OC_) de ownCloud , y también comprueba los métodos obsoletos y la validez del  archivo info.xml. De forma predeterminada, todas las comprobaciones están habilitadas. La aplicación Activity es un ejemplo de una aplicación con el formato correcto

sudo -u www-data php occ app:check-code notifications
App is compliant - awesome job!

Si su aplicación tiene problemas, verá un resultado como este:

sudo -u www-data php occ app:check-code foo_app
Analysing /var/www/owncloud/apps/files/foo_app.php
4 errors
   line   45: OCP\Response - Static method of deprecated class must not be
   called
   line   46: OCP\Response - Static method of deprecated class must not be
   called
   line   47: OCP\Response - Static method of deprecated class must not be
   called
   line   49: OC_Util - Static method of private class must not be called

Puede obtener la ruta completa del archivo a una aplicación

sudo -u www-data php occ app:getpath notifications
/var/www/owncloud/apps/notifications

Selector de trabajos en segundo plano

Use el comando background para seleccionar qué programador desea usar para controlar los trabajos en segundo planoAjax , Webcron o Cron . Esto es lo mismo que usar la sección Cron en su página de administración de ownCloud.

background
 background:ajax       Use ajax to run background jobs
 background:cron       Use cron to run background jobs
 background:webcron    Use webcron to run background jobs

Este ejemplo selecciona Ajax:

sudo -u www-data php occ background:ajax
  Set mode for background jobs to 'ajax'

Los otros dos comandos son:

  • background:cron
  • background:webcron

Comandos de configuración

El comando config se utiliza para configurar el servidor ownCloud.

config
 config:app:delete      Delete an app config value
 config:app:get         Get an app config value
 config:app:set         Set an app config value
 config:import          Import a list of configuration settings
 config:list            List all configuration settings
 config:system:delete   Delete a system config value
 config:system:get      Get a system config value
 config:system:set      Set a system config value

Puede listar todos los valores de configuración con un comando:

sudo -u www-data php occ config:list

Por defecto, las contraseñas y otros datos confidenciales se omiten del informe, por lo que la salida se puede publicar públicamente (por ejemplo, como parte de un informe de error). Para generar un backport completo de todos los valores de configuración, es necesario establecer el --privateindicador:

sudo -u www-data php occ config:list --private

El contenido exportado también se puede volver a importar para permitir la configuración rápida de instancias similares. El comando de importación solo agregará o actualizará valores. Los valores que existen en la configuración actual, pero no en la que se está importando, no se modifican.

sudo -u www-data php occ config:import filename.json

También es posible importar archivos remotos, canalizando la entrada:

sudo -u www-data php occ config:import < local-backup.json

Si bien es posible actualización / set / eliminar las versiones y los estados de instalación de aplicaciones y la propia ownCloud,  No se recomienda hacer esto directamente. Utilice los comandos occ app:enable, occ app:disabley en su occ updatelugar.

Obtener un valor de configuración único

Estos comandos obtienen el valor de una sola aplicación o configuración del sistema:

sudo -u www-data php occ config:system:get version
9.0.0.19

sudo -u www-data php occ config:app:get activity installed_version
2.2.1

Establecer un valor de configuración único

Estos comandos establecen el valor de una sola aplicación o configuración del sistema:

sudo -u www-data php occ config:system:set logtimezone
--value="Europe/Berlin"
System config value logtimezone set to Europe/Berlin

sudo -u www-data php occ config:app:set files_sharing
incoming_server2server_share_enabled --value="yes" --type=boolean
Config value incoming_server2server_share_enabled for app files_sharing set to yes

El comando config:system:set  crea el valor, si aún no existe. Para actualizar un valor existente, establezca --update-only:

sudo -u www-data php occ config:system:set doesnotexist --value="true"
--type=boolean --update-only
Value not updated, as it has not been set before.

Tenga en cuenta que para escribir un valor booleano, flotante o entero en el archivo de configuración, debe especificar el tipo en su comando. Esto se aplica solo al comando config:system:set. Se conocen los siguientes valores:

  • boolean
  • integer
  • float
  • string (default)

Cuando desee, por ejemplo, deshabilitar el modo de mantenimiento, ejecute el siguiente comando:

sudo -u www-data php occ config:system:set maintenance --value=false
--type=boolean
ownCloud is in maintenance mode - no app have been loaded
System config value maintenance set to boolean false

Establecer una matriz (Array) de valores de configuración

Algunas configuraciones (por ejemplo, la configuración del dominio de confianza) son una matriz de datos. Para establecer (y también obtener) el valor de una clave, puede especificar varios confignombres separados por espacios:

sudo -u www-data php occ config:system:get trusted_domains
localhost
owncloud.local
sample.tld

Para reemplazar sample.tld con example.com trust_domains => es necesario configurar 2:

sudo -u www-data php occ config:system:set trusted_domains 2
--value=example.com
System config value trusted_domains => 2 set to string example.com

sudo -u www-data php occ config:system:get trusted_domains
localhost
owncloud.local
example.com

Eliminar un valor de configuración único

Estos comandos eliminan la configuración de una aplicación o la configuración del sistema:

sudo -u www-data php occ config:system:delete maintenance:mode
System config value maintenance:mode deleted

sudo -u www-data php occ config:app:delete appname provisioning_api
Config value provisioning_api of app appname deleted

El comando de eliminación no se quejará de forma predeterminada si la configuración no se estableció antes. Si desea recibir una notificación en ese caso, configure la bandera --error-if-not-exists .

sudo -u www-data php occ config:system:delete doesnotexist
--error-if-not-exists
Config provisioning_api of app appname could not be deleted because it did not
exist

Comandos Dav

Un conjunto de comandos para crear libretas de direcciones, calendarios y migrar libretas de direcciones:

dav
 dav:cleanup-chunks            Cleanup outdated chunks
 dav:create-addressbook        Create a dav address book
 dav:create-calendar           Create a dav calendar
 dav:sync-birthday-calendar    Synchronizes the birthday calendar
 dav:sync-system-addressbook   Synchronizes users to the system
                               address book

Estos comandos no están disponibles en el modo de usuario único (mantenimiento) .

dav:cleanup-chunks limpia fragmentos desactualizados (archivos cargados) que tienen más de un cierto número de días. De forma predeterminada, el comando limpia fragmentos de más de 2 días. Sin embargo, al proporcionar el número de días al comando, se puede aumentar el rango. Por ejemplo, en el ejemplo siguiente, se eliminarán los fragmentos de más de 10 días.

sudo -u www-data php occ dav:cleanup-chunks 10

# example output
Cleaning chunks older than 10 days(2017-11-08T13:13:45+00:00)
Cleaning chunks for admin
   0 [>---------------------------]

La sintaxis de dav:create-addressbooky y dav:create-calendares dav:create-addressbook [user] [name]. Este ejemplo crea la libreta mollybookde direcciones para el usuario molly:

sudo -u www-data php occ dav:create-addressbook molly mollybook

Este ejemplo crea un nuevo calendario para molly:

sudo -u www-data php occ dav:create-calendar molly mollycal

Molly los verá inmediatamente en sus páginas de Calendario y Contactos. Sus calendarios y contactos existentes deberían migrar automáticamente cuando actualice. Si algo sale mal, puede intentar una migración manual. Primero elimine los calendarios o libretas de direcciones parcialmente migrados. Luego ejecute este comando para migrar los contactos del usuario:

sudo -u www-data php occ dav:migrate-addressbooks [user]

Ejecute este comando para migrar calendarios:

sudo -u www-data php occ dav:migrate-calendars [user]

dav:sync-birthday-calendara grega todos los cumpleaños a su calendario desde las libretas de direcciones compartidas con usted. Este ejemplo se sincroniza con su calendario del usuario bernie:

sudo -u www-data php occ dav:sync-birthday-calendar bernie

dav:sync-system-addressbook sincroniza a todos los usuarios con la libreta de direcciones del sistema.

sudo -u www-data php occ dav:sync-system-addressbook

Conversión de base de datos

La base de datos SQLite es buena para realizar pruebas y para servidores ownCloud con pequeñas cargas de trabajo de un solo usuario que no usan clientes de sincronización, pero los servidores de producción con múltiples usuarios deben usar MariaDB, MySQL o PostgreSQL. Puede utilizar occpara convertir de SQLite a una de estas otras bases de datos.

db
 db:convert-type           Convert the ownCloud database to the newly
                           configured one
 db:generate-change-script generates the change script from the current
                           connected db to db_structure.xml

Necesitas:

  • Su base de datos deseada y su conector PHP instalado.
  • El inicio de sesión y la contraseña de un usuario administrador de la base de datos.
  • El número de puerto de la base de datos, si es un puerto no estándar.

Este es un ejemplo que convierte SQLite a MySQL / MariaDB:

sudo -u www-data php occ db:convert-type mysql oc_dbuser 127.0.0.1
oc_database

 

Encriptación (Cifrado)

occ incluye un conjunto completo de comandos para administrar el cifrado.

encryption
 encryption:change-key-storage-root   Change key storage root
 encryption:decrypt-all               Disable server-side encryption and
                                      decrypt all files
 encryption:disable                   Disable encryption
 encryption:enable                    Enable encryption
 encryption:enable-master-key         Enable the master key. Only available
                                      for fresh installations with no existing
                                      encrypted data! There is also no way to
                                      disable it again.
 encryption:encrypt-all               Encrypt all files for all users
 encryption:list-modules              List all available encryption modules
 encryption:migrate                   initial migration to encryption 2.0
 encryption:recreate-master-key       Replace existing master key with new one.
                                      Encrypt the file system with newly created master key.
 encryption:set-default-module        Set the encryption default module
 encryption:show-key-storage-root     Show current key storage root
 encryption:status                    Lists the current status of encryption

encryption:status muestra si tiene cifrado activo y su módulo de cifrado predeterminado. Para habilitar el cifrado, primero debe habilitar la aplicación Encryption y luego ejecutar encryption:enable:

sudo -u www-data php occ app:enable encryption
sudo -u www-data php occ encryption:enable
sudo -u www-data php occ encryption:status
 - enabled: true
 - defaultModule: OC_DEFAULT_MODULE

encryption:change-key-storage-root es para mover sus claves de cifrado a una carpeta diferente. Toma un argumento, newRootque define su nueva carpeta raíz. La carpeta debe existir y la ruta es relativa a su directorio raíz de ownCloud.

sudo -u www-data php occ encryption:change-key-storage-root ../../etc/oc-keys

Puede ver la ubicación actual de su carpeta de claves:

sudo -u www-data php occ encryption:show-key-storage-root
Current key storage root:  default storage location (data/)

encryption:list-modules muestra sus módulos de cifrado disponibles. Verá una lista de módulos solo si ha habilitado la aplicación Cifrado. Úselo encryption:set-default-module [module name]para configurar el módulo deseado.

encryption:encrypt-all cifra todos los archivos de datos para todos los usuarios. Primero debe poner su servidor ownCloud en modo de usuario único para evitar cualquier actividad del usuario hasta que se complete el cifrado.

encryption:decrypt-all descifra todos los archivos de datos del usuario, u opcionalmente un solo usuario:

sudo -u www-data php occ encryption:decrypt freda

Los usuarios deben tener habilitadas las claves de recuperación en sus páginas personales. Primero debe poner su servidor ownCloud en modo de usuario único para evitar cualquier actividad del usuario hasta que se complete el descifrado.

Úselo encryption:disablepara deshabilitar su módulo de encriptación. Primero debe poner su servidor ownCloud en modo de usuario único para evitar cualquier actividad del usuario.

encryption:enable-master-keycrea una nueva clave maestra, que se utiliza para todos los datos de usuario en lugar de claves de usuario individuales. Esto es especialmente útil para habilitar el inicio de sesión único. Use esto solo en instalaciones nuevas sin datos existentes, o en sistemas donde el cifrado aún no se ha habilitado. No es posible desactivarlo.

encryption:migratemigra las claves de cifrado después de una actualización importante de la versión de ownCloud. Opcionalmente, puede especificar usuarios individuales en una lista delimitada por espacios. Consulte Configuración de cifrado para obtener más información.

encryption:recreate-master-keydescifra el sistema de archivos ownCloud, reemplaza la clave maestra existente por una nueva y cifra todo el sistema de archivos ownCloud con la nueva clave maestra. Dado el tamaño de su sistema de archivos ownCloud, esto puede tardar un tiempo en completarse. Sin embargo, si su sistema de archivos es bastante pequeño, se completará con bastante rapidez. El -yinterruptor se puede suministrar para automatizar la aceptación de la entrada del usuario.

Sincronización de federación

Sincronice las libretas de direcciones de todos los servidores de ownCloud federados:

federation:sync-addressbooks  Synchronizes address books of all
                              federated clouds

Los servidores conectados con recursos compartidos de federación pueden compartir libretas de direcciones de usuario y completar automáticamente los nombres de usuario en los cuadros de diálogo para compartir. Utilice este comando para sincronizar servidores federados:

sudo -u www-data php occ federation:sync-addressbooks

Este comando solo está disponible cuando la aplicación "Federación" ( federation) está habilitada.

Operaciones de archivo

occ tiene tres comandos para administrar archivos en ownCloud:

files
 files:cleanup              Deletes orphaned file cache entries.
 files:scan                 Rescans the filesystem.
 files:transfer-ownership   All files and folders are moved to another
                            user - outgoing shares are moved as well (incoming shares are not moved as the sharing user holds the ownership of the respective files).

Estos comandos no están disponibles en el modo modo de usuario único (mantenimiento) .

Los archivos: comando de escaneo

El files:scancomando

  • Busca archivos nuevos.
  • Analiza archivos no analizados por completo.
  • Repara agujeros de caché de archivos.
  • Actualiza la caché de archivos.

Los análisis de archivos se pueden realizar por usuario, para una lista de usuarios delimitada por espacios y para todos los usuarios.

sudo -u www-data php occ files:scan --help
 Usage:
   files:scan [options] [--] [<user_id>]...

 Arguments:
   user_id                will rescan all files of the given user(s)

 Options:
       --output[=OUTPUT]  Output format (plain, json or json_pretty, default is plain) [default: "plain"]
   -p, --path=PATH        limit rescan to this path, eg. --path="/alice/files/Music", the user_id is determined by the path and the user_id parameter and --all are ignored
   -q, --quiet            Do not output any message
       --all              will rescan all files of all known users
       --repair           will repair detached filecache entries (slow)
       --unscanned        only scan files which are marked as not fully scanned
   -h, --help             Display this help message
   -V, --version          Display this application version
       --ansi             Force ANSI output
       --no-ansi          Disable ANSI output
   -n, --no-interaction   Do not ask any interactive question
       --no-warnings      Skip global warnings, show command output only
   -v|vv|vvv, --verbose   Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Si no se usa --quiet, las estadísticas se mostrarán al final del escaneo.

La opción --path

Al usar la opción --path, la ruta debe estar en uno de los siguientes formatos:

"user_id/files/path"
"user_id/files/mount_name"
"user_id/files/mount_name/path"

Por ejemplo:

--path="/alice/files/Music"

En el ejemplo anterior, el user_id alicese determina implícitamente a partir del componente de ruta proporcionado. Los parámetros --path, --ally [user_id]son exclusivos; solo se debe especificar uno.

La Opción --repair

Como se señaló anteriormente, las reparaciones se pueden realizar para usuarios individuales, grupos de usuarios y para todos los usuarios en una instalación de ownCloud. Además, los análisis de reparación se pueden ejecutar incluso si no se sabe que ningún archivo necesita reparación y si se sabe que uno o más archivos necesitan reparación. Dos ejemplos de cuando los archivos necesitan reparación son:

  • Si las carpetas tienen la misma entrada dos veces en la interfaz de usuario web (conocida como “ carpeta fantasma ”), esto también puede generar mensajes de error extraños en el cliente de escritorio.
  • Si ingresar a una carpeta no parece conducir a esa carpeta.

El comando de reparación debe ejecutarse en modo de usuario único. Los siguientes comandos muestran cómo habilitar el modo de usuario único, ejecutar un análisis de archivo de reparación y luego deshabilitar el modo de usuario único.

sudo -u www-data php occ maintenance:singleuser --on
sudo -u www-data php occ files:scan --all --repair
sudo -u www-data php occ maintenance:singleuser --off

Le recomendamos encarecidamente que haga una copia de seguridad de la base de datos antes de ejecutar este comando.

The files:cleanup command

files:cleanup ordena la caché de archivos del servidor eliminando todas las entradas de archivos que no tienen entradas coincidentes en la tabla de almacenamiento. Puede transferir todos los archivos y recursos compartidos de un usuario a otro. Esto es útil antes de eliminar un usuario.

Por ejemplo, para mover todos los archivos de <source-user>a <destination-user>, use el siguiente comando:

sudo -u www-data php occ files:transfer-ownership <source-user> <destination-user>

También puede mover un conjunto limitado de archivos de <source-user>a <destination-user>haciendo uso del --pathconmutador, como en el ejemplo siguiente. En él, folder/to/movey cualquier archivo y carpeta dentro de él se moverá <destination-user>.

sudo -u www-data php occ files:transfer-ownership --path="folder/to/move" <source-user> <destination-user>

Al usar este comando, tenga en cuenta:

  1. El directorio proporcionado al conmutador --path debe existir dentro data/<source-user>/files.
  2. El directorio (y su contenido) no se moverá como está entre los usuarios. Que va a ser movido dentro de del usuario de destino filesdel directorio, y se coloca en un directorio que sigue el formato: transferred from <source-user> on <timestamp>. Usando el ejemplo anterior, se almacenará en:data/<destination-user>/files/transferred from <source-user> on 20170426_124510/
  3. Actualmente, las versiones de archivo no se pueden transferir. Solo la última versión de los archivos movidos aparecerá en la cuenta del usuario de destino

Archivos externos

Estos comandos reemplazan el data/mount.jsonarchivo de configuración utilizado en las versiones de ownCloud anteriores a la 9.0.

Comandos para administrar el almacenamiento externo:

files_external
 files_external:applicable  Manage applicable users and groups for a mount
 files_external:backends    Show available authentication and storage backends
 files_external:config      Manage backend configuration for a mount
 files_external:create      Create a new mount configuration
 files_external:delete      Delete an external mount
 files_external:export      Export mount configurations
 files_external:import      Import mount configurations
 files_external:list        List configured mounts
 files_external:option      Manage mount options for a mount
 files_external:verify      Verify mount configuration

Estos comandos replican la funcionalidad en la GUI web ownCloud, más dos características nuevas: files_external:exporty files_external:import.

Úselo files_external:exportpara exportar todos los montajes de administración a stdout y files_external:export [user_id]para exportar los montajes del usuario de ownCloud especificado.

Estos comandos solo están disponibles cuando la aplicación "Soporte de almacenamiento externo" ( files_external) está habilitada. No está disponible en el modo de usuario único (mantenimiento) .

Comandos de grupo

Los comandos de grupo proporcionan una gama de funciones para administrar grupos ownCloud. Esto incluye la creación y eliminación de grupos y la gestión de la pertenencia a grupos. Los nombres de los grupos distinguen entre mayúsculas y minúsculas, por lo que "Finanzas" y "finanzas" son dos grupos diferentes.

La lista completa de comandos es:

group
 group:add                           adds a group
 group:add-member                    add members to a group
 group:delete                        deletes the specified group
 group:list                          list groups
 group:list-members                  list group members
 group:remove-member                 remove member(s) from a group

Crear grupos

Puede crear un nuevo grupo con el group:addcomando. La sintaxis es:

group:add groupname

Este ejemplo agrega un nuevo grupo, llamado "Finance":

sudo -u www-data php occ group:add Finance
  Created group "Finance"

Listado de grupos

Puede enumerar los nombres de los grupos existentes con el comando group:list. La sintaxis es:

group:list [options] [<search-pattern>]

search-pattern Lista los grupos que contienen la cadena. La coincidencia no distingue entre mayúsculas y minúsculas. Si no proporciona un patrón de búsqueda, se enumeran todos los grupos.

Este ejemplo enumera los grupos que contienen la cadena de finance:

sudo -u www-data php occ group:list finance
 - All-Finance-Staff
 - Finance
 - Finance-Managers

La salida se puede formatear en JSON con la opción de salida jsono json_pretty:

sudo -u www-data php occ --output=json_pretty group:list finance
 [
   "All-Finance-Staff",
   "Finance",
   "Finance-Managers"
 ]

Listado de miembros del grupo

Puede enumerar los ID de usuario de los miembros del grupo con el group:list-memberscomando. La sintaxis es:

group:list-members [options] <group>

Este ejemplo enumera los miembros del grupo Finance:

sudo -u www-data php occ group:list-members Finance
 - aaron: Aaron Smith
 - julie: Julie Jones

La salida se puede formatear en JSON con la opción de salida jsono json_pretty:

sudo -u www-data php occ --output=json_pretty group:list-members Finance
 {
   "aaron": "Aaron Smith",
   "julie": "Julie Jones"
 }

Agregar miembros a grupos

Puede agregar miembros a un grupo existente con el group:add-membercomando. Los miembros deben ser usuarios existentes. La sintaxis es:

group:add-member [-m|--member [MEMBER]] <group>

Este ejemplo agrega los miembros "aaron" y "julie" al grupo "Finanzas":

sudo -u www-data php occ group:add-member --member aaron --member julie Finance
  User "aaron" added to group "Finance"
  User "julie" added to group "Finance"

Puede intentar agregar miembros que ya están en el grupo, sin error. Esto le permite agregar miembros de una manera programada sin necesidad de saber si el usuario ya es miembro del grupo. Por ejemplo:

sudo -u www-data php occ group:add-member --member aaron --member julie --member fred Finance
  User "aaron" is already a member of group "Finance"
  User "julie" is already a member of group "Finance"
  User fred" added to group "Finance"

Eliminar miembros de grupos

Puede eliminar miembros de un grupo con el comando group:remove-member. La sintaxis es:

group:remove-member [-m|--member [MEMBER]] <group>

Este ejemplo elimina a los miembros "aaron" y "julie" del grupo "Finance":

sudo -u www-data php occ group:remove-member --member aaron --member julie Finance
  Member "aaron" removed from group "Finance"
  Member "julie" removed from group "Finance"

Puede intentar eliminar miembros que ya se han eliminado del grupo, sin error. Esto le permite eliminar miembros de forma programada sin necesidad de saber si el usuario sigue siendo miembro del grupo. Por ejemplo:

sudo -u www-data php occ group:remove-member --member aaron --member fred Finance
  Member "aaron" could not be found in group "Finance"
  Member "fred" removed from group "Finance"

Eliminar un grupo

Para eliminar un grupo, use el comando group:delete, como en el siguiente ejemplo:

sudo -u www-data php occ group:delete Finance

Verificación de integridad

Las aplicaciones que tienen una etiqueta oficial DEBEN estar firmadas con código. Las aplicaciones oficiales sin firmar ya no se podrán instalar. La firma de código es opcional para todas las aplicaciones de terceros.

integrity
 integrity:check-app                 Check app integrity using a signature.
 integrity:check-core                Check core integrity using a signature.
 integrity:sign-app                  Signs an app using a private key.
 integrity:sign-core                 Sign core using a private key

Después de crear su clave (key) de firma, firme su aplicación como este ejemplo:

sudo -u www-data php occ integrity:sign-app --privateKey=/Users/lukasreschke/contacts.key --certificate=/Users/lukasreschke/CA/contacts.crt --path=/Users/lukasreschke/Programming/contacts

Verifica tu aplicación:

sudo -u www-data php occ integrity:check-app --path=/pathto/app appname

Cuando no devuelve nada, su aplicación está firmada correctamente. Cuando devuelve un mensaje, hay un error. Consulte Firma de código en el manual del desarrollador para obtener información más detallada.

integrity:sign-core es solo para desarrolladores principales de ownCloud.

Consulte Firma de código para obtener más información.

 



10n, Create Javascript Translation Files for Apps

This command is for app developers to update their translation mechanism from ownCloud 7 to ownCloud 8 and later.

LDAP Commands

These commands are only available when the “LDAP user and group backend” app (user_ldap) is enabled.

These LDAP commands appear only when you have enabled the LDAP app. Then you can run the following LDAP commands with occ:

ldap
 ldap:check-user               checks whether a user exists on LDAP.
 ldap:create-empty-config      creates an empty LDAP configuration
 ldap:delete-config            deletes an existing LDAP configuration
 ldap:search                   executes a user or group search
 ldap:set-config               modifies an LDAP configuration
 ldap:show-config              shows the LDAP configuration
 ldap:test-config              tests an LDAP configuration
 ldap:update-group             update the specified group membership
                               information stored locally

Search for an LDAP user, using this syntax:

sudo -u www-data php occ ldap:search [--group] [--offset="..."]
[--limit="..."] search

Searches will match at the beginning of the attribute value only. This example searches for givenNames that start with “rob”:

sudo -u www-data php occ ldap:search "rob"

This will find robbie, roberta, and robin. Broaden the search to find, for example, jeroboam with the asterisk wildcard:

sudo -u www-data php occ ldap:search "*rob"

User search attributes are set with ldap:set-config (below). For example, if your search attributes are givenName and sn you can find users by first name + last name very quickly. For example, you’ll find Terri Hanson by searching for te ha. Trailing whitespace is ignored.

Check if an LDAP user exists. This works only if the ownCloud server is connected to an LDAP server.

sudo -u www-data php occ ldap:check-user robert

ldap:check-user will not run a check when it finds a disabled LDAP connection. This prevents users that exist on disabled LDAP connections from being marked as deleted. If you know for certain that the user you are searching for is not in one of the disabled connections, and exists on an active connection, use the --force option to force it to check all active LDAP connections.

sudo -u www-data php occ ldap:check-user --force robert

ldap:create-empty-config creates an empty LDAP configuration. The first one you create has no configID, like this example:

sudo -u www-data php occ ldap:create-empty-config
  Created new configuration with configID ''

This is a holdover from the early days, when there was no option to create additional configurations. The second, and all subsequent, configurations that you create are automatically assigned IDs.

sudo -u www-data php occ ldap:create-empty-config
   Created new configuration with configID 's01'

Then you can list and view your configurations:

sudo -u www-data php occ ldap:show-config

And view the configuration for a single configID:

sudo -u www-data php occ ldap:show-config s01

ldap:delete-config [configID] deletes an existing LDAP configuration.

sudo -u www-data php occ ldap:delete  s01
Deleted configuration with configID 's01'

The ldap:set-config command is for manipulating configurations, like this example that sets search attributes:

sudo -u www-data php occ ldap:set-config s01 ldapAttributesForUserSearch
"cn;givenname;sn;displayname;mail"

The command takes the following format:

ldap:set-config <configID> <configKey> <configValue>

All of the available keys, along with default values for configValue, are listed in the table below.

Configuration Setting
hasMemberOfFilterSupport  
hasPagedResultSupport  
homeFolderNamingRule  
lastJpegPhotoLookup 0
ldapAgentName cn=admin,dc=owncloudqa,dc=com
ldapAgentPassword *
ldapAttributesForGroupSearch  
ldapAttributesForUserSearch  
ldapBackupHost  
ldapBackupPort  
ldapBase dc=owncloudqa,dc=com
ldapBaseGroups dc=owncloudqa,dc=com
ldapBaseUsers dc=owncloudqa,dc=com
ldapCacheTTL 600
ldapConfigurationActive 1
ldapDynamicGroupMemberURL  
ldapEmailAttribute  
ldapExperiencedAdmin 0
ldapExpertUUIDGroupAttr  
ldapExpertUUIDUserAttr  
ldapExpertUsernameAttr ldapGroupDisplayName cn
ldapGroupFilter ldapGroupFilterGroups
ldapGroupFilterMode 0
ldapGroupFilterObjectclass  
ldapGroupMemberAssocAttr uniqueMember
ldapHost ldap://host
ldapIgnoreNamingRules  
ldapLoginFilter (&((objectclass=inetOrgPerson))(uid=%uid))
ldapLoginFilterAttributes  
ldapLoginFilterEmail 0
ldapLoginFilterMode 0
ldapLoginFilterUsername 1
ldapNestedGroups 0
ldapOverrideMainServer  
ldapPagingSize 500
ldapPort 389
ldapQuotaAttribute  
ldapQuotaDefault  
ldapTLS 0
ldapUserDisplayName displayName
ldapUserDisplayName2  
ldapUserFilter ((objectclass=inetOrgPerson))
ldapUserFilterGroups  
ldapUserFilterMode 0
ldapUserFilterObjectclass inetOrgPerson
ldapUuidGroupAttribute auto
ldapUuidUserAttribute auto
turnOffCertCheck 0
useMemberOfToDetectMembership 1

ldap:test-config tests whether your configuration is correct and can bind to the server.

sudo -u www-data php occ ldap:test-config s01
The configuration is valid and the connection could be established!

ldap:update-group updates the specified group membership information stored locally.

The command takes the following format:

ldap:update-group <groupID> <groupID <groupID> ...>

The command allows for running a manual group sync on one or more groups, instead of having to wait for group syncing to occur. If users have been added or removed from these groups in LDAP, ownCloud will update its details. If a group was deleted in LDAP, ownCloud will also delete the local mapping info about this group.

New groups in LDAP won’t be synced with this command. The LDAP TTL configuration (by default 10 minutes) still applies. This means that recently deleted groups from LDAP might be considered as “active” and might not be deleted in ownCloud immediately.

Configuring the LDAP Refresh Attribute Interval

You can configure the LDAP refresh attribute interval, but not with the ldap commands. Instead, you need to use the config:app:set command, as in the following example, which takes a number of seconds to the --value switch.

occ config:app:set user_ldap updateAttributesInterval --value=7200

In the example above, the interval is being set to 7200 seconds. Assuming the above example was used, the command would output the following:

Config value updateAttributesInterval for app user_ldap set to 7200

If you want to reset (or unset) the setting, then you can use the following command:

occ config:app:delete user_ldap updateAttributesInterval

Logging Commands

These commands view and configure your ownCloud logging preferences.

log
 log:manage     manage logging configuration
 log:owncloud   manipulate ownCloud logging backend

Run log:owncloud to see your current logging status:

sudo -u www-data php occ log:owncloud
Log backend ownCloud: enabled
Log file: /opt/owncloud/data/owncloud.log
Rotate at: disabled

Use the --enable option to turn on logging. Use --file to set a different log file path. Set your rotation by log file size in bytes with --rotate-size; 0 disables rotation. log:manage sets your logging backend, log level, and timezone. The defaults are owncloud, Warning, and UTC. Available options are:

  • –backend [owncloud, syslog, errorlog]
  • –level [debug, info, warning, error, fatal]

Maintenance Commands

Use these commands when you upgrade ownCloud, manage encryption, perform backups and other tasks that require locking users out until you are finished:

maintenance
 maintenance:data-fingerprint        update the systems data-fingerprint after
                                     a backup is restored
 maintenance:mimetype:update-db      Update database mimetypes and update
                                     filecache
 maintenance:mimetype:update-js      Update mimetypelist.js
 maintenance:mode                    set maintenance mode
 maintenance:repair                  repair this installation
 maintenance:singleuser              set single user mode
 maintenance:update:htaccess         Updates the .htaccess file

maintenance:mode locks the sessions of all logged-in users, including administrators, and displays a status screen warning that the server is in maintenance mode. Users who are not already logged in cannot log in until maintenance mode is turned off. When you take the server out of maintenance mode logged-in users must refresh their Web browsers to continue working.

sudo -u www-data php occ maintenance:mode --on
sudo -u www-data php occ maintenance:mode --off

Putting your ownCloud server into single-user mode allows admins to log in and work, but not ordinary users. This is useful for performing maintenance and troubleshooting on a running server.

sudo -u www-data php occ maintenance:singleuser --on
Single user mode enabled

Turn it off when you’re finished:

sudo -u www-data php occ maintenance:singleuser --off
Single user mode disabled

Run maintenance:data-fingerprint to tell desktop and mobile clients that a server backup has been restored. Users will be prompted to resolve any conflicts between newer and older file versions.

Run maintenance:data-fingerprint to tell desktop and mobile clients that a server backup has been restored. This command changes the ETag for all files in the communication with sync clients, informing them that one or more files were modified. After the command completes, users will be prompted to resolve any conflicts between newer and older file versions.

The maintenance:repair command runs automatically during upgrades to clean up the database, so while you can run it manually there usually isn’t a need to.

sudo -u www-data php occ maintenance:repair

maintenance:mimetype:update-db updates the ownCloud database and file cache with changed mimetypes found in config/mimetypemapping.json. Run this command after modifying config/mimetypemapping.json. If you change a mimetype, run maintenance:mimetype:update-db --repair-filecache to apply the change to existing files.

Market

The market commands install, list, and upgrade applications from the ownCloud Marketplace.

market
  market:install    Install apps from the marketplace. If already installed and
                    an update is available the update will be installed.
  market:list       Lists apps as available on the marketplace.
  market:upgrade    Installs new app versions if available on the marketplace

The user running the update command, which will likely be your webserver user, needs write permission for the /apps folder. If they don’t have write permission, the command may report that the update was successful, but it may silently fail.

These commands are not available in single-user (maintenance) mode.

Reports

If you’re working with ownCloud support and need to send them a configuration summary, you can generate it using the configreport:generate command. This command generates the same JSON-based report as the Admin Config Report, which you can access under admin -> Settings -> Admin -> Help & Tips -> Download ownCloud config report.

From the command-line in the root directory of your ownCloud installation, run it as your webserver user as follows, (assuming your webserver user is www-data):

sudo -u www-data occ configreport:generate

This will generate the report and send it to STDOUT. You can optionally pipe the output to a file and then attach it to an email to ownCloud support, by running the following command:

sudo -u www-data occ configreport:generate > generated-config-report.txt

Alternatively, you could generate the report and email it all in one command, by running:

sudo -u www-data occ configreport:generate | mail -s "configuration report" \
    -r <the email address to send from> \
    Esta dirección de correo electrónico está siendo protegida contra los robots de spam. Necesita tener JavaScript habilitado para poder verlo.

These commands are not available in single-user (maintenance) mode.

Security

Use these commands when you manage security related tasks

Routes dispays all routes of ownCloud. You can use this information to grant strict access via firewalls, proxies or loadbalancers etc.

security:routes [options]

Options:

--output        Output format (plain, json or json-pretty, default is plain)
--with-details  Adds more details to the output

Example 1:

sudo  -uwww-data ./occ security:routes
+-----------------------------------------------------------+-----------------+
| Path                                                      | Methods         |
+-----------------------------------------------------------+-----------------+
| /apps/federation/auto-add-servers                         | POST            |
| /apps/federation/trusted-servers                          | POST            |
| /apps/federation/trusted-servers/{id}                     | DELETE          |
| /apps/files/                                              | GET             |
| /apps/files/ajax/download.php                             |                 |
...

Example 2:

sudo  -uwww-data ./occ security:routes --output=json-pretty
[
  {
      "path": "\/apps\/federation\/auto-add-servers",
      "methods": [
          "POST"
      ]
  },
...

Example 3:

sudo  -uwww-data ./occ security:routes --with-details
+---------------------------------------------+---------+-------------------------------------------------------+--------------------------------+
| Path                                        | Methods | Controller                                            | Annotations                    |
+---------------------------------------------+---------+-------------------------------------------------------+--------------------------------+
| /apps/files/api/v1/sorting                  | POST    | OCA\Files\Controller\ApiController::updateFileSorting | NoAdminRequired                |
| /apps/files/api/v1/thumbnail/{x}/{y}/{file} | GET     | OCA\Files\Controller\ApiController::getThumbnail      | NoAdminRequired,NoCSRFRequired |
...

The following commands manage server-wide SSL certificates. These are useful when you create federation shares with other ownCloud servers that use self-signed certificates.

security:certificates         list trusted certificates
security:certificates:import  import trusted certificate
security:certificates:remove  remove trusted certificate

This example lists your installed certificates:

sudo -u www-data php occ security:certificates

Import a new certificate:

sudo -u www-data php occ security:certificates:import /path/to/certificate

Remove a certificate:

sudo -u www-data php occ security:certificates:remove [certificate name]

Ransomware Protection

Use these commands to help users recover from a Ransomware attack. You can find more information about the application in the documentation.

Ransomware Protection (which is an Enterprise app) needs to be installed and enabled to be able to use these commands.

occ ransomguard:scan <timestamp> <user>    Report all changes in a user's account, starting from timestamp.
occ ransomguard:restore <timestamp> <user> Revert all operations in a user account after a point in time.

Sharing

This is an occ command to cleanup orphaned remote storages. To explain why this is necessary, a little background is required. While shares are able to be deleted as a normal matter of course, remote storages with “shared::” are not included in this process.

This might not, normally, be a problem. However, if a user has re-shared a remote share which has been deleted it will. This is because when the original share is deleted, the remote re-share reference is not. Internally, the fileid will remain in the file cache and storage for that file will not be deleted.

As a result, any user(s) who the share was re-shared with will now get an error when trying to access that file or folder. That’s why the command is available.

So, to cleanup all orphaned remote storages, run it as follows:

sudo -u www-data php sharing:cleanup-remote-storages

You can also set it up to run as a background job

These commands are not available in single-user (maintenance) mode.

Shibboleth Modes (Enterprise Edition only)

shibboleth:mode sets your Shibboleth mode to notactive, autoprovision, or ssoonly:

shibboleth:mode [mode]

These commands are only available when the “Shibboleth user backend” app (user_shibboleth) is enabled.

Trashbin

These commands are only available when the “Deleted files” app (files_trashbin) is enabled. These commands are not available in single-user (maintenance) mode.

trashbin
 trashbin:cleanup   Remove deleted files
 trashbin:expire    Expires the users trash bin

The trashbin:cleanup command removes the deleted files of the specified users in a space-delimited list, or all users if none are specified. This example removes all the deleted files of all users:

sudo -u www-data php occ trashbin:cleanup
Remove all deleted files
Remove deleted files for users on backend Database
 freda
 molly
 stash
 rosa
 edward

This example removes the deleted files of users “”molly”” and “”freda”“:

sudo -u www-data php occ trashbin:cleanup molly freda
Remove deleted files of   molly
Remove deleted files of   freda

trashbin:expire deletes only expired files according to the trashbin_retention_obligation setting in config.php (see the Deleted Files section in Config.php Parameters). The default is to delete expired files for all users, or you may list users in a space-delimited list.

User Commands

The user commands provide a range of functionality for managing ownCloud users. This includes: creating and removing users, resetting user passwords, displaying a report which shows how many users you have, and when a user was last logged in.

The full list, of commands is:

user
 user:add                            adds a user
 user:delete                         deletes the specified user
 user:disable                        disables the specified user
 user:enable                         enables the specified user
 user:inactive                       reports users who are known to owncloud,
                                     but have not logged in for a certain number of days
 user:lastseen                       shows when the user was logged in last time
 user:list                           list users
 user:list-groups                    list groups for a user
 user:report                         shows how many users have access
 user:resetpassword                  Resets the password of the named user
 user:setting                        Read and modify user settings
 user:sync                           Sync local users with an external backend service

Creating Users

You can create a new user with the user:add command. This command lets you set the following attributes:

  • uid: The uid is the user’s username and their login name
  • display name: This corresponds to the Full Name on the Users page in your ownCloud Web UI
  • email address
  • group
  • login name
  • password

The command’s syntax is:

user:add [--password-from-env] [--display-name [DISPLAY-NAME]] [--email [EMAIL]] [-g|--group [GROUP]] [--] <uid>

This example adds new user Layla Smith, and adds her to the users and db-admins groups. Any groups that do not exist are created.

sudo -u www-data php occ user:add --display-name="Layla Smith" \
  --group="users" --group="db-admins" --email=Esta dirección de correo electrónico está siendo protegida contra los robots de spam. Necesita tener JavaScript habilitado para poder verlo. layla
  Enter password:
  Confirm password:
  The user "layla" was created successfully
  Display name set to "Layla Smith"
  Email address set to "Esta dirección de correo electrónico está siendo protegida contra los robots de spam. Necesita tener JavaScript habilitado para poder verlo."
  User "layla" added to group "users"
  User "layla" added to group "db-admins"

After the command completes, go to your Users page, and you will see your new user.

Setting a User’s Password

password-from-env allows you to set the user’s password from an environment variable. This prevents the password from being exposed to all users via the process list, and will only be visible in the history of the user (root) running the command. This also permits creating scripts for adding multiple new users.

To use password-from-env you must run as “real” root, rather than sudo, because sudo strips environment variables. This example adds new user Fred Jones:

export OC_PASS=newpassword
su -s /bin/sh www-data -c 'php occ user:add --password-from-env
  --display-name="Fred Jones" --group="users" fred'
The user "fred" was created successfully
Display name set to "Fred Jones"
User "fred" added to group "users"

You can reset any user’s password, including administrators (see Resetting a Lost Admin Password):

sudo -u www-data php occ user:resetpassword layla
  Enter a new password:
  Confirm the new password:
  Successfully reset password for layla

You may also use password-from-env to reset passwords:

export OC_PASS=newpassword
su -s /bin/sh www-data -c 'php occ user:resetpassword --password-from-env
  layla'
  Successfully reset password for layla

Deleting A User

To delete a user, you use the user:delete command, as in the example below:

sudo -u www-data php occ user:delete fred

Listing Users

You can list existing users with the user:list command. The syntax is:

user:list [options] [<search-pattern>]

User IDs containing the search-pattern string are listed. Matching is not case-sensitive. If you do not provide a search-pattern then all users are listed.

This example lists user IDs containing the string ron:

sudo -u www-data php occ user:list ron
 - aaron: Aaron Smith

The output can be formatted in JSON with the output option json or json_pretty:

sudo -u www-data php occ --output=json_pretty user:list
 {
   "aaron": "Aaron Smith",
   "herbert": "Herbert Smith",
   "julie": "Julie Jones"
 }

Listing Group Membership of a User

You can list the group membership of a user with the user:list-groups command. The syntax is:

user:list-groups [options] <uid>

This example lists group membership of user julie:

sudo -u www-data php occ user:list-groups julie
 - Executive
 - Finance

The output can be formatted in JSON with the output option json or json_pretty:

sudo -u www-data php occ --output=json_pretty user:list-groups julie
 [
   "Executive",
   "Finance"
 ]

Finding The User’s Last Login

To view a user’s most recent login, use the user:lastseen command, as in the example below:

sudo -u www-data php occ user:lastseen layla
  layla's last login: 09.01.2015 18:46

User Application Settings

To manage application settings for a user, use the user:setting command. This command provides the ability to:

  • Retrieve all settings for an application
  • Retrieve a single setting
  • Set a setting value
  • Delete a setting

If you run the command and pass the help switch (--help), you will see the following output, in your terminal:

$ ./occ user:setting --help
Usage:
  user:setting [options] [--] <uid> [<app>] [<key>]

Arguments:
  uid                                User ID used to login
  app                                Restrict the settings to a given app [default: ""]
  key                                Setting key to set, get or delete [default: ""]

If you’re new to the user:setting command, the descriptions for the app and key arguments may not be completely transparent. So, here’s a lengthier description of both.

Argument Description
app When an value is supplied, user:setting limits the settings displayed, to those for that, specific, application — assuming that the application is installed, and that there are settings available for it. Some example applications are “core”, “files_trashbin”, and “user_ldap”. A complete list, unfortunately, cannot be supplied, as it is impossible to know the entire list of applications which a user could, potentially, install.
key This value specifies the setting key to be manipulated (set, retrieved, or deleted) by the user:setting command.

Retrieving User Settings

To retrieve all settings for a user, you need to call the user:setting command and supply the user’s username, as in the example below.

sudo -u www-data php occ user:setting layla
  - core:
    - lang: en
  - login:
    - lastLogin: 1465910968
  - settings:
    - email: Esta dirección de correo electrónico está siendo protegida contra los robots de spam. Necesita tener JavaScript habilitado para poder verlo.

Here, we see that the user has settings for the application core, when they last logged in, and what their email address is.

To retrieve the user’s settings for a specific application, you have to supply the username and the application’s name, which you want to retrieve the settings for; such as in the example below:

sudo -u www-data php occ user:setting layla core
 - core:
    - lang: en

In the output, you can see that one setting is in effect, lang, which is set to en. To retrieve the value of a single application for a user, use the user:setting command, as in the example below.

sudo -u www-data php occ user:setting layla core lang

This will display the value for that setting, such as en.

Setting a Setting

To set a setting, you need to supply four things; these are:

  • the username
  • the application (or setting category)
  • the --value switch
  • the, quoted, value for that setting

Here’s an example of how you would set the email address of the user layla.

sudo -u www-data php occ user:setting layla settings email --value "Esta dirección de correo electrónico está siendo protegida contra los robots de spam. Necesita tener JavaScript habilitado para poder verlo."

Deleting a Setting

Deleting a setting is quite similar to setting a setting. In this case, you supply the username, application (or setting category) and key as above. Then, in addition, you supply the --delete flag.

sudo -u www-data php occ user:setting layla settings email --delete

Generating a User Count Report

Generate a simple report that counts all users, including users on external user authentication servers such as LDAP.

sudo -u www-data php occ user:report
+------------------+----+
| User Report      |    |
+------------------+----+
| Database         | 12 |
| LDAP             | 86 |
|                  |    |
| total users      | 98 |
|                  |    |
| user directories | 2  |
+------------------+----+

Syncing User Accounts

This command syncs users stored in external backend services, such as LDAP, Shibboleth, and Samba, with ownCloud’s, internal, user database. However, it’s not essential to run it regularly, unless you have a large number of users whose account properties have changed in a backend outside of ownCloud. When run, it will pick up changes from alternative user backends, such as LDAP where properties like cn or display name have changed, and sync them with ownCloud’s user database. If accounts are found that no longer exist in the external backend, you are given the choice of either removing or disabling the accounts.

It’s also one of the commands that you should run on a regular basis to ensure that your ownCloud installation is running optimally.

This command replaces the old show-remnants functionality, and brings the LDAP feature more in line with the rest of ownCloud’s functionality.

Below are examples of how to use the command with an LDAP, Samba, and Shibboleth backend.

LDAP

sudo -u www-data ./occ user:sync "OCA\User_LDAP\User_Proxy"

Samba

sudo -u www-data ./occ user:sync "OCA\User\SMB" -vvv

Shibboleth

sudo -u www-data ./occ user:sync "OCA\User_Shibboleth\UserBackend"

Syncing via cron job

Here is an example for syncing with LDAP four times a day on Ubuntu:

crontab -e -u www-data

* */6 * * * /usr/bin/php /var/www/owncloud/occ user:sync -vvv --missing-account-action="remove" -n "OCA\User_LDAP\User_Proxy"

Versions

versions
 versions:cleanup   Delete versions
 versions:expire    Expires the users file versions

versions:cleanup can delete all versioned files, as well as the files_versions folder, for either specific users, or for all users. The example below deletes all versioned files for all users:

sudo -u www-data php occ versions:cleanup
Delete all versions
Delete versions for users on backend Database
  freda
  molly
  stash
  rosa
  edward

You can delete versions for specific users in a space-delimited list:

sudo -u www-data php occ versions:cleanup freda molly
Delete versions of   freda
Delete versions of   molly

versions:expire deletes only expired files according to the versions_retention_obligation setting in config.php (see the File versions section in Config.php Parameters). The default is to delete expired files for all users, or you may list users in a space-delimited list.

These commands are only available when the “Versions” app (files_versions) is enabled. These commands are not available in single-user (maintenance) mode.

Command Line Installation

ownCloud can be installed entirely from the command line. After downloading the tarball and copying ownCloud into the appropriate directories, or after installing ownCloud packages (See Preferred Installation Method and Manual Installation on Linux) you can use occ commands in place of running the graphical Installation Wizard.

These instructions assume that you have a fully working and configured webserver. If not, please refer to the documentation on configuring the Apache web server for detailed instructions.

Apply correct permissions to your ownCloud directories; see Set Strong Directory Permissions. Then choose your occ options. This lists your available options:

sudo -u www-data php /var/www/owncloud/occ
ownCloud is not installed - only a limited number of commands are available
ownCloud version 9.0.0

Usage:
 [options] command [arguments]

Options:
 --help (-h)           Display this help message
 --quiet (-q)          Do not output any message
 --verbose (-v|vv|vvv) Increase the verbosity of messages: 1 for normal
 output,  2 for more verbose output and 3 for debug
 --version (-V)        Display this application version
 --ansi                Force ANSI output
 --no-ansi             Disable ANSI output
 --no-interaction (-n) Do not ask any interactive question

Available commands:
 check                 check dependencies of the server environment
 help                  Displays help for a command
 list                  Lists commands
 status                show some status information
 app
 app:check-code        check code to be compliant
 l10n
 l10n:createjs         Create javascript translation files for a given app
 maintenance
 maintenance:install   install ownCloud

Display your maintenance:install options:

sudo -u www-data php occ help maintenance:install
ownCloud is not installed - only a limited number of commands are available
Usage:
 maintenance:install [--database="..."] [--database-name="..."]
[--database-host="..."] [--database-user="..."] [--database-pass[="..."]]
[--database-table-prefix[="..."]] [--admin-user="..."] [--admin-pass="..."]
[--data-dir="..."]

Options:
 --database               Supported database type (default: "sqlite")
 --database-name          Name of the database
 --database-host          Hostname of the database (default: "localhost")
 --database-user          User name to connect to the database
 --database-pass          Password of the database user
 --database-table-prefix  Prefix for all tables (default: oc_)
 --admin-user             User name of the admin account (default: "admin")
 --admin-pass             Password of the admin account
 --data-dir               Path to data directory (default:
                          "/var/www/owncloud/data")
 --help (-h)              Display this help message
 --quiet (-q)             Do not output any message
 --verbose (-v|vv|vvv)    Increase the verbosity of messages: 1 for normal
  output, 2 for more verbose output and 3 for debug
 --version (-V)           Display this application version
 --ansi                   Force ANSI output
 --no-ansi                Disable ANSI output
 --no-interaction (-n)    Do not ask any interactive question

This example completes the installation:

cd /var/www/owncloud/
sudo -u www-data php occ maintenance:install --database
"mysql" --database-name "owncloud"  --database-user "root" --database-pass
"password" --admin-user "admin" --admin-pass "password"
ownCloud is not installed - only a limited number of commands are available
ownCloud was successfully installed

Supported databases are:

- sqlite (SQLite3 - ownCloud Community edition only)
- mysql (MySQL/MariaDB)
- pgsql (PostgreSQL)
- oci (Oracle - ownCloud Enterprise edition only)

Command Line Upgrade

These commands are available only after you have downloaded upgraded packages or tar archives, and before you complete the upgrade. List all options, like this example on CentOS Linux:

sudo -u www-data php occ upgrade -h
Usage:
 upgrade [options]

Options:
     --no-app-disable  skips the disable of third party apps
 -h, --help            Display this help message
 -q, --quiet           Do not output any message
 -V, --version         Display this application version
     --ansi            Force ANSI output
     --no-ansi         Disable ANSI output
 -n, --no-interaction  Do not ask any interactive question
     --no-warnings     Skip global warnings, show command output only
 -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Help:
 run upgrade routines after installation of a new release. The release has to be installed before.

When you are performing an update or upgrade on your ownCloud server (see the Maintenance section of this manual), it is better to use occ to perform the database upgrade step, rather than the Web GUI, in order to avoid timeouts. PHP scripts invoked from the Web interface are limited to 3600 seconds. In larger environments this may not be enough, leaving the system in an inconsistent state. After performing all the preliminary steps (see How to Upgrade Your ownCloud Server) use this command to upgrade your databases, like this example on CentOS Linux:

sudo -u www-data php occ upgrade
ownCloud or one of the apps require upgrade - only a limited number of
commands are available
Turned on maintenance mode
Checked database schema update
Checked database schema update for apps
Updated database
Updating <gallery> ...
Updated <gallery> to 0.6.1
Updating <activity> ...
Updated <activity> to 2.1.0
Update successful
Turned off maintenance mode

Note how it details the steps. Enabling verbosity displays timestamps:

sudo -u www-data php occ upgrade -v
ownCloud or one of the apps require upgrade - only a limited number of commands are available
2015-06-23T09:06:15+0000 Turned on maintenance mode
2015-06-23T09:06:15+0000 Checked database schema update
2015-06-23T09:06:15+0000 Checked database schema update for apps
2015-06-23T09:06:15+0000 Updated database
2015-06-23T09:06:15+0000 Updated <files_sharing> to 0.6.6
2015-06-23T09:06:15+0000 Update successful
2015-06-23T09:06:15+0000 Turned off maintenance mode

If there is an error it throws an exception, and the error is detailed in your ownCloud logfile, so you can use the log output to figure out what went wrong, or to use in a bug report.

Turned on maintenance mode
Checked database schema update
Checked database schema update for apps
Updated database
Updating <files_sharing> ...
Exception
ServerNotAvailableException: LDAP server is not available
Update failed
Turned off maintenance mode

Two-factor Authentication

If a two-factor provider app is enabled, it is enabled for all users by default (though the provider can decide whether or not the user has to pass the challenge). In the case of an user losing access to the second factor (e.g., a lost phone with two-factor SMS verification), the admin can temporarily disable the two-factor check for that user via the occ command:

sudo -u www-data php occ twofactor:disable <username>

To re-enable two-factor authentication again, use the following commmand:

sudo -u www-data php occ twofactor:enable <username>

Disable Users

Admins can disable users via the occ command too:

sudo -u www-data php occ user:disable <username>

Use the following command to enable the user again:

sudo -u www-data php occ user:enable <username>

Once users are disabled, their connected browsers will be disconnected.

Finding Inactive Users

To view a list of users who’ve not logged in for a given number of days, use the user:inactive command The example below searches for users inactive for five days, or more.

sudo -u www-data php occ user:inactive 5

By default, this will generate output in the following format:

- 0:
  - uid: admin
  - displayName: admin
  - inactiveSinceDays: 5

You can see the user’s user id, display name, and the number of days they’ve been inactive. If you’re passing or piping this information to another application for further processing, you can also use the --output switch to change its format. The switch supports three options, these are:

Setting Description
plain This is the default format.
json This will render the output as a JSON-encoded, but not formatted, string.
[{"uid":"admin","displayName":"admin","inactiveSinceDays":5}]
  • json_pretty: This will render the output as a JSON-encoded string, formatted for ease of readability.
[
    {
        "uid": "admin",
        "displayName": "admin",
        "inactiveSinceDays": 5
    }
]

Pin It

Escribir un comentario


Código de seguridad
Refescar



Redes:



 

Suscribete / Newsletter

Suscribete a nuestras Newsletter y periódicamente recibirás un resumen de las noticias publicadas.

Donar a LinuxParty

Probablemente te niegues, pero.. ¿Podrías ayudarnos con una donación?


Tutorial de Linux

Filtro por Categorías