The owner (and group) of all files and directories in the nextcloud directory should be the web server user, e.g. www-data on Debian/Ubuntu based systems, with permissions 0640 for files and 0750 for directories.
So in order for the occ commands to work they need to be executed as the web server user:
Examples:
sudo -u www-data php /path/to/nextcloud/occ maintenance:mode --on
sudo -u www-data php /path/to/nextcloud/occ maintenance:mode --off