Seite wählen

NETWAYS Blog

How To Administrate Nextcloud Using CLI

With Nextcloud you can configure almost everything using the Webinterface.
But you may do updates and configuration also via CLI.
In this How To I’ll go over some common use-cases for the Nextcloud CLI.

Update / Upgrade

Let’s start with upgrading to the newest version. Go to the directory where your nextcloud is located – there should be a folder called ‚updater‘.

[root@nc-vm ~]# cd /var/www/nextcloud/updater
[root@nc-vm ~]# ls
index.php  updater.phar

Inside the updater folder is a file called updater.phar.
Now execute the following command.

[root@nc-vm ~]# sudo -u www-data php updater.phar
Current version is 11.0.3.
Update to Nextcloud 12.0.0 available. (channel: "stable")
Following file will be downloaded automatically: https://download.nextcloud.com/server/releases/nextcloud-12.0.0.zip
Steps that will be executed:
[ ] Check for expected files
[ ] Check for write permissions
[ ] Enable maintenance mode
[ ] Create backup
[ ] Downloading
[ ] Extracting
[ ] Replace entry points
[ ] Delete old files
[ ] Move new files in place
[ ] Done
Start update? [y/N] y

Confirm with ‚y‘ to start the update.

Info: Pressing Ctrl-C will finish the currently running step and then stops the updater.
[✔] Check for expected files
[✔] Check for write permissions
[✔] Enable maintenance mode
[✔] Create backup
[✔] Downloading
[✔] Extracting
[✔] Replace entry points
[✔] Delete old files
[✔] Move new files in place
[✔] Done
Update of code successful.
Should the "occ upgrade" command be executed? [Y/n] Y

After the new files have been moved in place you’ll have to confirm to execute the „occ upgrade“ command.

Nextcloud or one of the apps require upgrade - only a limited number of commands are available
You may use your browser or the occ upgrade command to do the upgrade
Set log level to debug
Updating database schema
Updated database
Updating federatedfilesharing ...
Updated federatedfilesharing to 1.2.0
Updating files_pdfviewer ...
Updated files_pdfviewer to 1.1.1
Updating files_texteditor ...
..
..
Checking for update of app workflowengine in appstore
Checked for update of app "workflowengine" in appstore
Starting code integrity check...
Finished code integrity check
Update successful
Maintenance mode is kept active
Reset log level
Keep maintenance mode active? [y/N] N

And finally you enter ‚N‘ to disable the maintenance mode

Maintenance mode is disabled

And that’s it. But note: even if it tells you that a lot of apps are be updated, you may find that not all of your apps have been updated.

OCC Command

Next we’ll explore the features of the occ command.

[root@nc-vm ~]# cd /var/www/nextcloud
[root@nc-vm ~]# sudo -u www-data php occ

You will get a long list of the available options and commands.

Nextcloud version 12.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:
  _completion                         BASH completion hook.
  check                               check dependencies of the server environment
  help                                Displays help for a command
  list                                Lists commands
  status                              show some status information
  ..
  ..
versions
  versions:cleanup                    Delete versions
  versions:expire                     Expires the users file versions

I won’t be able to cover all of them in this post. But I’ll go over a view of them in the following.

Reset Admin Password

This is pretty useful if you forgot your admin password and you find yourself locked out of your Nextcloud.

[root@nc-vm ~]# sudo -u www-data php /var/www/nextcloud/occ user:resetpassword admin
Enter a new password:
Confirm the new password:
Successfully reset password for admin

 

Change Log Level

Sometimes you to increase the log level to figure out what is wrong. By default the log level is set to ‚warning‘ (level 2).
To get more information you’ll have to decrease the number. So 1 is level ‚info‘ and 0 is for ‚debug‘.
You may also set it to ‚error‘ which is level 3 to get less information.

[root@nc-vm ~]# sudo -u www-data php occ log:manage --level 0
Enabled logging backend: file
Log level: Debug (0)
Log timezone: UTC

 

Encryption

For server side encryption it’s necessary to enable the encryption app first.
(In Nextcloud Version 12.0.0 and prior enryption does not work with S3 object store as primary storage.)

[root@nc-vm ~]# sudo -u www-data php occ app:enable encryption
encryption enabled

And then enable encryption

[root@nc-vm ~]# sudo -u www-data php occ encryption:enable
Encryption enabled
Default module: OC_DEFAULT_MODULE

Note that only new uploaded files will be encrypted and not the existing ones.
In order to encrypt all existing files of all users you will have to issue the following command:

[root@nc-vm ~]# sudo -u www-data php occ encryption:encrypt-all
You are about to encrypt all files stored in your Nextcloud installation.
Depending on the number of available files, and their size, this may take quite some time.
Please ensure that no user accesses their files during this time!
Note: The encryption module you use determines which files get encrypted.
Do you really want to continue? (y/n) y

Continue with ‚y‘. You may notify the users by mail about their private key passwords.
But this only works if the users have provided their email-addresses.

Encrypt all files with the Default encryption module
====================================================
Create key-pair for every user
------------------------------
This module will encrypt all files in the users files folder initially.
Already existing versions and files in the trash bin will not be encrypted.
 Key-pair created for all users
 [============================]
Start to encrypt users files
----------------------------
 all files encrypted
 [>---------------------------]
Generated encryption key passwords
----------------------------------
+-----------+----------------------+
| Username  | Private key password |
+-----------+----------------------+
| admin     | BqaK1WtI             |
+-----------+----------------------+
A list of all newly created passwords was written to data/oneTimeEncryptionPasswords.csv
Each of these users need to login to the web interface, go to the
personal settings section "basic encryption module" and
update the private key password to match the login password again by
entering the one-time password into the "old log-in password" field
and their current login password
Do you want to send the passwords directly to the users by mail? (y/n) n

 

Configuration

Usually the config file for Nextcloud is located in /var/www/nextcloud/config.
So in order to change the configuration you may edit the file /var/www/nextcloud/config/config.php with a text editor.
But you can also import a custom config file in json format. In this example I imported a config to set Ceph S3 object store as primary storage for Nextcloud:

[root@nc-vm ~]# cat objectstore.json
{"system": {
        "objectstore": {
            "class": "OC\\\\Files\\\\ObjectStore\\\\S3",
            "arguments": {
                    "bucket": "$RGW_BUCKET",
                    "autocreate": true,
                    "key": "$RGW_KEY",
                    "secret": "$RGW_SECRET",
                    "hostname": "$RGW_HOSTNAME",
                    "use_ssl": true,
                    "use_path_style": true
            }
        }
}}
[root@nc-vm ~]# sudo -u www-data php occ config:import objectstore.json
Config successfully imported from: objectstore.json

It’s also possible to view only specific sections of the config:

[root@nc-vm ~]# sudo -u www-data php occ config:system:get objectstore
class: OC\\Files\\ObjectStore\\S3
arguments:
  bucket: $RGW_BUCKET
  autocreate: true
  key: $RGW_KEY
  secret: $RGW_SECRET
  hostname: $RGW_HOSTNAME
  use_ssl: true
  use_path_style: true

 

Apps

To get a list of all installed enabled and disabled apps:

[root@nc-vm ~]# sudo -u www-data php occ app:list
Enabled:
  - activity: 2.5.2
  - bruteforcesettings: 1.0.2
  - calendar: 1.5.3
  - comments: 1.2.0
  ..
  ..
  - workflowengine: 1.2.0
Disabled:
  - admin_audit
  - encryption
  - files_external
  - previewgenerator
  - user_external
  - user_ldap

To enable/disable apps:

[root@nc-vm ~]# sudo -u www-data php occ app:enable previewgenerator
previewgenerator enabled
[root@nc-vm ~]# sudo -u www-data php occ app:disable calendar
calendar disabled

Like I mentioned before, there are many more commands and the ones I picked are just a view of them.
But I hope they were useful at least for some of you.

Gabriel Hartmann
Gabriel Hartmann
Senior Systems Engineer

Gabriel hat 2016 als Auszubildender Fachinformatiker für Systemintegrator bei NETWAYS angefangen und 2019 die Ausbildung abgeschlossen. Als Mitglied des Web Services Teams kümmert er sich seither um viele technische Themen, die mit den NETWAYS Web Services und der Weiterentwicklung der Plattform zu tun haben. Aber auch im Support engagiert er sich, um den Kunden von NWS bei Fragen und Problemen zur Seite zu stehen.

Weekly Snap: CeBIT 2014, Csync & CLI

weekly snap3 – 7 February was packed with upcoming and past events, webinars and training courses, and much ado about monitoring.
Eva counted 64 days to the OSDC with Constantino Vázquez’s talk: ‘The OpenNebula Cloud Platform for Data Center Virtualisation”, and announced the coordinates of our stand at CeBIT 2014.
Christian continued on events to introduce our first 3 webinars of the year as Thomas W reflected on our first Logastash training course.
On monitoring, Bernd compared Icinga, Nagios, Naemon, OMD, Check_MK and Shinken while Thomas G took a peek into the wonderful world of Icinga Web 2 CLI.
Finally, Matthias recommended Csync to synchronise folders in a network and Stephanie shared stories and snaps from the recent NETWAYS ski trip no. 2.

Auf ins Wunderland – die Icinga Web 2 CLI

Jeder kennt sie, die beiden: Alice und Bob. Heute verschonen wir Bob mit Anrufen von seiner Alice und schicken letztere zurück ins Wunderland. Dort hört sie ein paar Gerüchte über Icinga Web 2, und immer wieder spricht irgendwer von dessen CLI. Alice wundert sich, was denn eine Weboberfläche mit der Kommandozeile zu tun hätte.
Kaum hat sie das Ding endlich aufgespürt, erkundigt sich Alice freundlich wie immer, was das Ganze denn soll:

icingaweb_cli_alice_wtf

AHA, denkt sich Alice – das ist doch mal eine Ansage. Man kann über Alice ja vieles sagen, aber dumm ist sie definitiv nicht. Schnell hat sie begriffen was Sache ist, staunt darüber dass ein Web-Dings so wunderbare Tab-Vervollständigung auf der Shell hinkriegt und hangelt sich durch die Inline-Hilfe. Dabei entdeckt sie, dass noch keines der mitgelieferten Module aktiviert ist und legt einfach los:

icingaweb_cli_modules

Soweit, so gut – jetzt ist also ein Monitoring-Modul aktiv. Alice experimentiert damit weiter und kriegt immer größere Augen. Farbige Darstellung…
icingaweb_cli_monitoring
…Performance-Daten…
icingaweb_cli_monitoring_disk_usage
…sprechende Filter-Bezeichnungen, unbestätigte Probleme werden hervorgehoben dargestellt…
icingaweb_cli_unhandled
…so soll das sein! Nachdem sie den Export nach CSV und JSON getestet hat entdeckt Alice die frei definierbaren Templates. Das probiert sie gleich mal aus, sie hätte gerne eine Liste all ihrer Server mit „node“ im Namen die einen „slave-lag“ Service definiert haben und die Custom-Variable _HOST_MYSQLUSER auf „icinga“ gesetzt haben. Das Ganze im Format „host: service (output)“:

icingaweb_cli_filter_export

Dann erinnert sich Alice, dass sie eingangs in der Doku –watch und –benchmark bemerkt hatte:
icingaweb_cli_watch_commandSie schaltet ihr Terminal auf Vollbild und traut ihren Augen nicht. Wie beim klassischen „top“ sieht sie im Sekundentakt aktualisiert all die Probleme, um die sich gerade keiner kümmert.
Jetzt hat Alice endgültig genug gesehen, zückt ihr Handy und ruft Bob an: „Booooooob, schmeiß sofort den Webbrowser weg, wir hängen uns ein Terminal an die Wand!“. „Ruuuhig Alice, ganz locker bleiben“, meint Bob daraufhin trocken. „Sieh dir einfach in ein paar Wochen nochmal an, wie das neue Webfrontend aussieht. ich hab gehört dass die da grad mächtig am Schrauben sind…“

Thomas Gelf
Thomas Gelf
Principal Consultant

Der gebürtige Südtiroler Tom arbeitet als Principal Consultant für Systems Management bei NETWAYS und ist in der Regel immer auf Achse: Entweder vor Ort bei Kunden, als Trainer in unseren Schulungen oder privat beim Skifahren in seiner Heimatstadt Bozen. Neben Icinga und Nagios beschäftigt sich Tom vor allem mit Puppet.

Automatische Datenbankgenerierung mit Doctrine


Die Doctrine CLI ist ein komfortables Mittel um sich z.B. Datenbank, Modelle, Tabellen und Daten automatisch erstellen zu lassen. Voraussetzung dafür ist ein entsprechendes Skript welches die Doctrine CLI aufruft und YAML Schema Dateien. Folgendes Szenario soll Prozesse in einer SQLite Datenbank hierarchisch ablegen.
Beispielumgebung unter /tmp/blog vorbereiten:


# cd /tmp
# mkdir blog
# cd blog
# mkdir lib
# wget 
# tar xzf Doctrine-1.2.4.tgz -C lib
# mkdir sqlite models sql schema fixtures


Doctrine CLI Skript:


/tmp/blog# cat doctrine.php
<?php
$dir = realpath(dirname(__FILE__));
require_once($dir . '/lib/Doctrine-1.2.4/Doctrine.php');
spl_autoload_register(array('Doctrine', 'autoload'));
spl_autoload_register(array('Doctrine', 'modelsAutoload'));
Doctrine_Manager::connection(
    'sqlite:///' . $dir . DIRECTORY_SEPARATOR . 'sqlite' . DIRECTORY_SEPARATOR . 'data.db',
    'connection_name');
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_MODEL_LOADING,
                       Doctrine::MODEL_LOADING_CONSERVATIVE);
Doctrine_Core::loadModels($dir . DIRECTORY_SEPARATOR . 'models');
$config = array(
    'models_path' => $dir . DIRECTORY_SEPARATOR . 'models',
    'sql_path' => $dir . DIRECTORY_SEPARATOR . 'sql',
    'yaml_schema_path' => $dir . DIRECTORY_SEPARATOR . 'schema',
    'data_fixtures_path' => $dir . DIRECTORY_SEPARATOR . 'fixtures');
$cli = new Doctrine_Cli($config);
$cli->run($_SERVER['argv']);

Doctrine erwartet oder schreibt jetzt Modelle im Ordner models, Beispieldaten in fixtures, Datenbankschema in schema und die Datenbank in sqlite/data.db.
Eine Liste von verfügbaren Kommandos erhält man, wenn man das Skript ohne Argumente aufruft:


/tmp/blog# php doctrine.php
Doctrine Command Line Interface
doctrine.php compile
doctrine.php generate-yaml-models
doctrine.php rebuild-db
doctrine.php load-data
...


Unsere Datenbank soll aus 2 Tabellen bestehen - einmal der Tabelle process, in der die Prozesse gespeichert werden und process_hierarchy, in der diese verschachtelt werden:


/tmp/blog# cat schema/schema.yml
---
# schema/schema.yml
# Global parameters
connection: connection_name
# Tables
Process:
  columns:
    id:
      type: integer
      primary: true
      autoincrement: true
    name:
      type: string(255)
      notnull: true
  relations:
    Trees:
      type: many
      class: ProcessHierarchy
      local: id
      foreign: view_id
ProcessHierarchy:
  actAs:
    NestedSet:
      hasManyRoots: true
      rootColumnName: root_id
  columns:
    id:
      type: integer
      primary: true
      autoincrement: true
    process_id:
      type: integer
  relations:
    Process:
      local: process_id
      foreign: id


Beispieldaten:


/tmp/blog# cat fixtures/data.yml
---
# fixtures/data.yml
Process:
  order:
    name: Order
  logistics:
    name: Logistics
  support:
    name: Support
ProcessHierarchy:
  root:
    Process: order
    children:
      logistics:
        Process: logistics
        children:
          support:
            Process: support


Zum Abschluss erstellen wir die Datenbank:


/tmp/blog# php doctrine.php build-all-load
build-all-load - Generated models successfully from YAML schema
build-all-load - Successfully created database for connection named 'connection_name'
build-all-load - Created tables successfully
build-all-load - Data was successfully loaded
/tmp/blog# php doctrine.php dql "from ProcessHierarchy h join h.Process p"
dql - executing: "from ProcessHierarchy h join h.Process p" ()
dql -   id: '4'
dql -   process_id: '4'
dql -   root_id: '4'
dql -   lft: '1'
dql -   rgt: '6'
dql -   level: '0'
dql -   Process:
dql -     id: '4'
dql -     name: Order
dql - -
dql -   id: '5'
dql -   process_id: '5'
dql -   root_id: '4'
dql -   lft: '2'
dql -   rgt: '5'
dql -   level: '1'
dql -   Process:
dql -     id: '5'
dql -     name: Logistics
dql - -
dql -   id: '6'
dql -   process_id: '6'
dql -   root_id: '4'
dql -   lft: '3'
dql -   rgt: '4'
dql -   level: '2'
dql -   Process:
dql -     id: '6'
dql -     name: Support

Eric Lippmann
Eric Lippmann
CTO

Eric kam während seines ersten Lehrjahres zu NETWAYS und hat seine Ausbildung bereits 2011 sehr erfolgreich abgeschlossen. Seit Beginn arbeitet er in der Softwareentwicklung und dort an den unterschiedlichen NETWAYS Open Source Lösungen, insbesondere inGraph und im Icinga Team an Icinga Web. Darüber hinaus zeichnet er für viele Kundenentwicklungen in der Finanz- und Automobilbranche verantwortlich.