📜 ⬆️ ⬇️

The history of creating a home cloud. Part 3. Creating a personal cloud - installing and configuring Nextcloud

On the way to creating our own cloud service, we have mastered the Debian system and created a web server . Now it's time for the final step - creating and configuring a personal cloud based on Nextcloud server.





Table of contents


Part 1. Setting up a Debian environment for everyday use.
Part 2. Creating a server - setting LAMP in Debian
Part 3. Creating a personal cloud - installing and configuring Nextcloud
Part 4. Update 2018 - Debian 9 and Nextcloud 13



Quick chapter navigation


Foreword
Preparing the server for the installation of Nextcloud
Install Nextcloud
Organization of Nextcloud storage
Setting up access to the Nextcloud virtual machine from the local network
Setting up Nextcloud
Additional "fine" setting Nextcloud
Protection for Nextcloud
Synchronization with the cloud of smartphones
Synchronization with the personal computer cloud
Afterword



Foreword


Here we come to the very thing for which everything was started and why we did not move quickly. This part will describe the installation and some points in setting up a Nextcloud server in a VMWare virtual machine, as well as some experience with it in the form of synchronizing the contents of a pair of smartphones and folders on a Windows desktop computer. The following instructions for installing Nextcloud imply that the service is deployed on a server that was created according to the instructions in the previous part of my story.

Initially, this chapter was planned for a short one, since I wanted to confine myself to a description of the installation and configuration of Nextcloud, essentially completing this story about “just entering Linux for a specific task”. But, thinking that it might seem interesting to someone, then I decided to show how I decided to synchronize the folders of my home computer, so this final chapter smoothly flowed from clear instructions on what to do and, in fact, programming. This explains some "vinaigrette" in this part - it begins with the work and settings in Linux, flowing to the level of network settings and virtual software, and ends with the planning of crutches in Windows. On the other hand, this series of articles has the title “History of creation ...” and I nevertheless decided to tell it to the end.

Note
Upon further reading in constructions of the form http: // 127.0.0.1 (https: // 127.0.0.1), the space after http: // (https: //) must be removed when entering into the address bar of the browser. A space is inserted when publishing this article in order to prevent the text engine from automatically converting text into links.



Preparing the server for the installation of Nextcloud


Nextcloud is a web application that has a set of files and works with the MySQL database. The web application is installed as a regular site, for installation of which you need to upload the engine files to the server, run the installation file and specify the details of access to the database previously created for this site during the installation.

Create a directory where Nextcloud files will be placed:
# mkdir / var / www / nextcloud

I decided to refuse HTTP, leaving access only via HTTPS. To do this, you need to configure apache.

Open the file:
# nano /etc/apache2/sites-available/default-ssl.conf
And before the tag add the following content:

<Directory /var/www/nextcloud> Options FollowSymLinks AllowOverride All Require all granted </Directory> 


Disable HTTP configuration:
# a2dissite 000-default.conf

Close port 80:
# ufw delete allow 80

And restart the web server:
# service apache2 restart

Now you need to create a database for nextcloud. Enter mysql by entering the password from the mysql superuser:
# mysql -u root -p

Create a database called nextcloud:
mysql> CREATE DATABASE `nextcloud`;

Create a user with the name nextcloud and the trivial password nc123:
mysql> CREATE USER 'nextcloud' @ 'localhost' IDENTIFIED BY 'nc123';

We give full access to the nextcloud user to the nextcloud database:
mysql> GRANT ALL PRIVILEGES ON `nextcloud`. * TO 'nextcloud' @ 'localhost';

Update privilege table:
mysql> FLUSH PRIVILEGES;

Exit mysql:
mysql: mysql> exit

In addition, you need to install additional modules for PHP:
# apt-get install curl libcurl3 libcurl3-dev php5-curl
# a2enmod rewrite

In the first part of this story we opened ports for network and mail interaction, but under our target task they are not required and it is better to close them. Delete the rules:
# ufw delete allow 138 / udp
# ufw delete allow 139 / udp
# ufw delete allow 139 / tcp
# ufw delete allow 445 / tcp
# ufw delete allow 25
# ufw delete allow 465
# ufw delete allow 110
# ufw delete allow 143
# ufw delete allow 993



Install Nextcloud


Download files and unpack them into the intended directory:
# wget download.nextcloud.com/server/releases/nextcloud-11.0.2.tar.bz2
# tar xjf nextcloud-11.0.2.tar.bz2 -C / var / www

Change permissions on a folder:
# chmod 755 / var / www / nextcloud

And we assign the web server as the owner of this folder so that there are no problems with writing to it:
# chown -R www-data: www-data / var / www / nextcloud

Everything! The service is installed, if you type in the browser https: // 127.0.0.1/nextcloud, the installation wizard will open. But let's wait with this, having previously prepared a place to store user data.

It is worth mentioning that the version of Nextcloud 11.0.2 is currently rather outdated and contains vulnerabilities that are not found in newer and current versions, so if you install the 11.x branch, it is better to install a more recent version (at the beginning of 2018 it’s version 11.0.7).



Organization of Nextcloud storage


This part is optional and can be skipped without problems - everything will work without it. However, if you go to make a directory with data outside of the virtual machine, I recommend to get acquainted with it.

By default, synchronized content will be stored in the / var / www / nextcloud / nxcdata directory. This option did not suit me at once for several reasons. On the one hand, I would not want a permanent increase in the size of a virtual disk file. On the other hand, I would like to have a separate and independent of the virtual machine storage solution. The simplest thing that immediately comes to mind is the use of a USB drive. In case of insufficient space, the disc can be simply replaced. If necessary, you can connect it to another computer and download the necessary files. Mobile and convenient. However, I did not want to use USB 2.0 due to the relatively small bandwidth by modern standards, and with USB 3.0 I did not succeed - virtualization software (WMVare and VirtualBox) did not want to normally forward devices connected via a USB 3.0 controller.

My appetites, in the process of creating the cloud, increased and I didn’t have at least one terabyte, so, in the end, I decided to connect a regular two-terabyte hard drive that was already located and connected inside the computer to the virtual machine. If necessary, it is easily pulled out and connected via the existing SATA <-> USB 3.0 adapter.

So, the main idea is to organize a fixed point for connecting a directory with user content outside the / var / www / nextcloud directory, in which a symbolic link is created with the name nxcdata, referring to the real data directory that can be connected in various ways on various media.

Create a directory:
# mkdir / mnt / nxcdata

We change the rights:
# chmod 770 / mnt / nxcdata

Making the owner of a web server:
# chown www-data: www-data / mnt / nxcdata

I can place data anywhere and anywhere, the main thing is to place the symbolic link to this directory in the / mnt / nxcdata directory and call it nxcdata, i.e. the full path will look like / mnt / nxcdata / nxcdata.

First, I tested the solution for the local folder I created in my home directory.

Created a folder in the right place:
$ mkdir / home / user / nxcdata

Changed rights:
# chmod 755 / home / user / nxcdata

Owned a web server:
# chown -R www-data: www-data / home / user / nxcdata

Created a symbolic link:
# ln -s / home / user / nxcdata / mnt / nxcdata / nxcdata

This solution was workable, so you can move on. The external data directory can be connected in two ways - through the VMWare Shared service or directly as a physical disk or partition. It is necessary to understand that the first solution is possible only if there are installed vmware tools, which are easily installed only if there is a graphical interface of the operating system (otherwise, you will have to edit the installation scripts of vmware tools). If we abandon the graphical interface, then there remains only the option of connecting the disk directly to the virtual machine, but with this decision I had to suffer a lot. After a while, I nevertheless found a stably working version, taking into account which a universal script was invented, incorporating both connection options.

For the folder that is connected via VMWare Shared Folders in the Shared Folders section of the virtual machine settings, you need to connect the necessary folder from the host system and name it vmw-nxcdata. This folder can refer to a directory on the hard disk or directly to the root directory of a disk on the host system.

The connected folder will automatically appear in the virtual system along the path / mnt / hgfs / vmw-nxcdata. However, the problem is that the web server will not have enough rights to write files along this path and it will not be possible to reassign the rights for this directory using standard system tools. So I had to figure out how to manually mount these resources.

Create a folder:
# mkdir / mnt / vmw-nxcdata

Perform mounting using the vmhgfs module, which was installed along with the vmware-tools:
# mount -t vmhgfs -o uid = www-data, gid = www-data, fmask = 007, dmask = 007 .host: / vmw-nxcdata / mnt / vmw-nxcdata

Mounting needs to be done with exactly these parameters to ensure smooth operation of the web server in the future. Initially, I mounted without specifying uid / gid and masks, but this didn’t lead to anything good, since I could no longer change the permissions after mounting. After the mount has been completed, the following can be issued: “Could not add entry to mtab, continuing” - however, it will be mounted and work.

Great, we have mounted the directory. Now you can place a symbolic link to this directory in / mnt / nxcdata. But I would not like to do this manually every time you start or restart the server. The easiest way is to enter the above command in the /etc/rc.local file for mounting to the “exit 0” line. However, I wanted to ensure that when the virtual machine was turned off, automatic guaranteed unmounting occurred for reliable data integrity. And I decided to do everything at the level of services and deal a little with the mechanisms of init / update-rc, the more I was curious and it turned out to be quite interesting.

The meaning of the following steps is to create a system service that would be called and executed predefined commands when the system is turned on or off. The service is described by a script compiled according to certain rules and is located in /etc/init.d. The INIT INFO block is located at the very beginning of the script and contains service information in which I would like to note the Default-Start and Default-Stop directives - they set the execution levels at which the script should be started or stopped by default.

Fulfillment levels:

0 - script execution at system shutdown
1 - script execution when starting the system in single user mode
2 - script execution when starting the system in multiuser mode
3 - 5 - reserved
6 - script execution when rebooting the system

After writing the script, it is activated using the update-rc mechanism, which, in fact, creates links to the script in the required directories /etc/rc0.d - /etc/rc6.d, the contents of which correspond to the tasks performed at launch levels. Links can be created independently, but, in contrast to enabling or disabling apache web server configurations, many nuances need to be taken into account here, so you need to enable or disable the service through update-rc.

So, create the file:
# nano /etc/init.d/nxcdata_automount.sh

And write to it the following content:

 #!/bin/sh # nxcdata_automount.sh 1.0 ### BEGIN INIT INFO # Provides: myscript # Required-Start: # Required-Stop: # Default-Start: 1 2 3 4 5 # Default-Stop: 0 6 # Short-Description: nxcdata_automount.sh 1.0 # Description: nxcdata_automount.sh 1.0 ### END INIT INFO . /lib/lsb/init-functions # Start actions perform_start() { log_daemon_msg «Start nxcdata_automount» sleep 30 mount -t vmhgfs -o uid=www-data,gid=www-data,fmask=007,dmask=007 .host:/vmw-nxcdata /mnt/vmw-nxcdata #mount -t ntfs-3g -o uid=www-data,gid=www-data,fmask=007,dmask=007 /dev/sdb1 /mnt/sdb1 #mount -t ext4 /dev/sdb1 /mnt/sdb1 sleep 5 service fail2ban restart log_end_msg 0 return 0 } # Stop actions perform_stop() { log_daemon_msg «Stop nxcdata_automount» umount /mnt/nxcdata log_end_msg 0 return 0 } case $1 in start) perform_start ;; stop) perform_stop ;; *) echo “Usage: /etc/init.d/myscript {start|stop}” exit 3 ;; esac 


Pay attention to a couple of commented commands in the perform_start section - this is our reserve for the future. Also, after the mount is completed, the fail2ban service is restarted.

The paradox is that after a year I don’t remember why I did it, but I strongly doubt that this was done just like that. Obviously, after the mount was completed, for some unknown reason, the service crashed or failed to start up initially and had to be restarted manually.

After such a distraction, we continue the setting further. Create a symbolic link:
# ln -s / mnt / vmw-nxcdata / mnt / nxcdata / nxcdata

Making our script executable:
# chmod + x /etc/init.d/nxcdata_automount.sh

Add the script to autoload:
# update-rc.d nxcdata_automount.sh defaults

Reboot the system and make sure that the automount is successful and everything is available along the necessary paths.

To remove the script you will need to execute a couple of commands:
# update-rc.d -f nxcdata_automount.sh remove
# rm -f /etc/init.d/nxcdata_automount.sh

In the case of mounting the disk not through VMWare Shared Folders, but directly you should perform the actions similar to that when mounting through VMWare Shared Folders, but taking into account the fact that a full-fledged second disk appears in the system. How to recognize the drive letter?

Most Linux block devices are connected via the SCSI interface, so in most cases the disks will start with the letters sd. The third letter in the disk name means its ordinal number in the system and is alphabetically designated: sda - the first disk, sdb - the second disk, sdc - the third one, and so on. Next comes the number that identifies the partition number on the disk: sda1, sda2, and so on. The easiest way to see all mounted disks is to look at the contents of the / dev / directory and filter the sd devices:

$ ls -l / dev / | grep sd

For example, we need to connect the sdb1 drive with the NTFS file system.

Create a directory and mount the disk into it:
# mkdir / mnt / sdb1
# mount -t ext4 / dev / sdb1 / mnt / sdb1

Create a directory for the data, set its rights and user:
# mkdir / mnt / sdb1 / nxcdata & chmod 770 / mnt / sdb1 / nxcdata & chown -R www-data: www-data / mnt / sdb1 / nxcdata

Next, you also need to create a script for automounting and correct the mount command in the script (examples of connecting a disk with NTFS and EXT4 are already in the script and commented out) and add the script to autoload.

B create a symbolic link to the data directory:
# ln -s / mnt / sdb1 / nxcdata / mnt / nxcdata / nxcdata

In fact, this whole mess with a bunch of nxcdata directories is designed for one thing: to ensure a simple transfer of the data directory in the future - you will not need to edit the configuration in the Nextcloud engine and generally go into it - all you need to do is plug in a new disk, copy to data from it and re-create the symbolic link leading to the new data directory. In this case, all actions do not go beyond the directory / mnt. So everything turned out to be complicated evolutionarily, I just did not want to lose the solutions I had worked out.

What is the best way to take out data outside the virtual machine? I will share my experience on which version I stopped and why.

USB drives were automatically captured when the virtual machine was loaded, they were correctly and fully forwarded inside and everything always worked, but only until the drive was disconnected from the system for some reason. It helped reboot or physically disconnect and connect the drive. The solution turned out to be unreliable. There was no such problem with flash drives, but I was absolutely not satisfied with their volume and speed of work. Perhaps it was worth trying an external drive with autonomous power.

Forwarding directories through VMWare Shared Folders worked stably and perfectly. This solution fully satisfied the task of synchronizing two smartphones. Everything worked for several days, tens of gigabytes of data were downloaded. However, when I decided to add data from a computer to the cloud, then suddenly a problem was discovered related to long paths and file names. In theory, the limit on the length of a file or folder name in NTFS is 255 characters, but in practice the Windows API limits it to 244 characters. In theory, the limit on the path to a file or folder in NTFS is 32,767 characters, but in practice the Windows API limits it to 245 characters. Considering that I am a big fan of structuring information, the length of the path I can have is very long. The unabridged title of books can also easily be 100-150 characters, taking into account the spaces. This limitation is a well-known VMWare Shared Folders problem that did not cure even when using Windows 10 with all sorts of clever keys in the registry to remove the 255-character limit. Possible reason for the limitations of vmhgfs. From this convenient method of connection had to be abandoned. The reason is established exactly - a problem in the virtual file system that is used in the VMWare Shared Folders mechanism.

The next solution is to connect the hard disk directly to the virtual machine. Here, too, everything did not go smoothly. The data structure (or file system, and this manifested itself for both NTFS and EXT2 / 3/4) constantly broke down either by “capturing” the disk or its partition with software of the virtual machine, or by returning it to the host system even if I translated disk offline on the host system. In some modes, I don’t have to write or read data - I couldn’t even properly format the forwarded hard disk or partition. However, it was possible to find a workable mode: a physical hard disk with a single partition, formatted in NTFS, in a particular connection mode was connected to the virtual machine: SATA / Independent / Persistent / Use individual partition. The nxcdata folder containing the data must be located on the hard disk.



Setting up access to the Nextcloud virtual machine from the local network


We have no problems opening sites within a virtual machine or from a host system. But how to open the created site from another computer on the local network? Let's look at the structure of our network, shown below.



The picture shows that the router is connected to the Internet directly and configured so that it automatically distributes IP addresses to connected devices in the range 192.168.0.2-192.168.0.254. The address 192.168.0.2 was received by our computer, and 192.168.0.3 - the second computer on which we make the server. However, virtualization software is installed on the second computer, which created its virtual router and configured its DHCP on the subnet 192.168.233.0/24. Our virtual server received an IP of 192.168.133.138.

I can easily open the site inside the virtual machine 192.168.233.138. I can easily open the site from the 192.168.0.3 machine by simply entering the desired IP address in the browser - the virtualization software has already taken care of correctly configuring the network environment on the host machine. But how can I get to the site from a computer 192.168.0.2? If I enter the IP address 192.168.233.138, then nothing will open to me, since neither my computer nor the real router knows anything about this subnet. If I enter the address 192.168.0.3, then nothing will open to me either, since there really is no site on this computer - it is inside its virtual machine.

To resolve this issue, you need to configure the virtual router of the computer 192.168.0.3. We already know that accessing sites goes through ports 80 and 443. When accessing these ports to machine 192.168.0.3, you need to build routing so that requests are forwarded to the virtual machine 192.168.233.138. Fortunately for this we have available tools. VMWare Workstation has the Virtual Network Editor tool, which can be opened from the virtual machine menu (Edit -> Virtual Network Editor).



This tool allows quite flexible management of network parameters. We need to select the VMNet8 virtual network card and click on the “NAT Settings ...” button that has become available. In the window that opens, you need to add rules to create the desired routing.



Specify the port of the host system and then write the IP address and port of the virtual machine where the requests should be redirected. For forwarding HTTPS traffic, you must specify the port 443 of the host system and port 443 and the address 192.168.233.138 of the virtual machine. After creating the rules, click "OK" in all windows - the virtual network environment is automatically reconfigured.

After these changes, our sites will begin to open from the machine 192.168.0.2 when accessing the address 192.168.0.3.

Such settings for port forwarding are available not only for VMWare, but also for VirtualBox (Settings → Network → select the required adapter → Advanced → Port forwarding). However, in the process of experimenting to connect a hard disk to this stage, I found a free VMWare Player installed, in which the Virtual Network Editor was not. I found nothing on the Internet about port forwarding for VMWare Player and I had to use the trial version of VMWare Workstation - when installing the product, it is given 30 days of its free use. After 30 days, you can remove the product, clean the registry and reinstall it, but such attention to the server is somehow redundant and clearly undesirable. And then I went for a little (or big) trick. В наборе файлов VMWare Workstation присутствует утилита vmnetcfg, которая по сути и запускается через пункт Virtual Network Editor. Однако в наборе файлов VMWare Player её не было. Но при установке VMWare Player как-то же конфигурирует своё сетевое окружение? Я просто взял эту утилиту и скопировал в папку с VMWare Player, после чего запустил. Удивительно, но всё получилось. Возможно, тонкие сетевые настройки в среде VMWare Player работать не будут, но проброс портов обеспечивается, а большего мне и не нужно.

Для доступа к нашему серверу из интернета нужно аналогично пробросить порты на маршрутизаторе, который подключен к интернету. В прошивках подавляющего большинства маршрутизаторов есть секция Port Forwarding, в которой и можно настроить маршрутизацию, указав внешний порт и порт и IP адрес внутренней машины. Однако есть небольшой нюанс. Если провайдер нам выдал реальный IP адрес или мы его купили у него, то тогда проблем не будет – с компьютера из любой точки планеты вводим этот IP адрес, реальный маршрутизатор перенаправит траффик на компьютер с виртуальной машиной, на котором виртуальный маршрутизатор перенаправит траффик непосредственно в виртуальную машину. А вот что делать тому, у кого нет возможности получить реальный IP адрес и он получает динамические адреса или оказывается за NAT провайдера, получая «серые» IP адреса? Мне такую задачу решать не пришлось, так как у меня есть статичный «белый» IP. Тому, кому придётся решать такую задачу так или иначе придётся разбираться с этой проблемой. Я бы советовал посмотреть в сторону dyndns или freedns.afraid.org в случае динамических адресов, либо купить дешевый VDS попробовать придумать какую-то маршрутизацию самому, так как в любом случае без внешнего сервера с статичным IP адресом подобную проблему не решить.

После конфигурирования маршрутизации я зафиксировал IP адреса компьютеров 192.168.0.3 и 192.168.233.138, прописав их в настройках сетевых карт указанных машин вручную для того, чтобы исключить их автоматическое переназначение.



Настройка Nextcloud


Теперь пришла пора открыть в браузере https:// 127.0.0.1/nextcloud внутри виртуальной машины, https:// 192.168.233.138/nextcloud с хостовой системы или, исходя из вышеописанной настроенной маршрутизации, https:// 192.168.0.3/nextcloud с любого компьютера в локальной сети.

Далее задаём логин/пароль для администратора, доступ к ранее созданной БД, а в качестве места хранения указываем полный путь к директории nxcdata: /mnt/nxcdata/nxcdata. Данный этап настройки ничем не отличается от установки какого-нибудь сайта.

В настройках админки я сделал следующие нехитрые изменения:

— Personal → выбрал русский язык и указал e-mail для администратора user@localhost
— Администрирование → Общий доступ → отключил все пункты
— Администрирование → Usage survey → отключил все пункты
— Администрирование → Дополнительные настройки → Управление файлами: «Максимальный размер загружаемого файла» установил в 25 GB
— Пользователи → создал группу users и добавил в неё нового пользователя user

После настройки нужно включить кеширование.

Открываем файл:
# nano /var/www/nextcloud/config/config.php

И в самый конец, перед «);» добавляем нижеследующее:

'memcache.local' => '\OC\Memcache\Memcached',
'memcache.distributed' => '\OC\Memcache\Memcached',
'memcached_servers' => array(
array('localhost', 11211),
),


Теперь нужно разрешить внешний доступ к сайту на уровне его «движка».

Открываем файл:
# nano /var/www/nextcloud/config/config.php

В секцию trusted_domains нужно в массив IP адрес сервера, добавить адрес, на котором установлен Nexcloud. Секция trusted_domains в нашем случае будет выглядеть следующим образом:

'trusted_domains' =>
array (
0 => '127.0.0.1',
1 => '192.168.233.138',
),


Теперь можно проверить работоспособность сервиса – открываем сайт и авторизуемся под пользователем user. Если авторизация прошла успешно, то значит сервис готов к бою – можно ставить приложение для синхронизации на компьютеры и смартфоны, для доступа ввести IP адрес 192.168.0.3 и реквизиты доступа аккаунта, созданные под каждое устройство.
К счастью или к сожалению, мне не пришлось пользовался всем потенциалом созданного сервиса, так как изначально мне нужна была система резервного копирования с верификацией и стартово я вообще хотел обойтись только subversion, но скорость коммитов особенно большого количества мелких файлов меня сильно опечалила. Я сделал всё на вырост, но попользоваться этим так и не собрался, а потом стало как-то совсем не до облака.

A more detailed overview of the use of the service was made by the user wtigga at the end of 2017 in his article “How to download a VPS: your Nextcloud cloud” . The article, from the user's point of view, gives an overview of the newer Nextcloud server, version 12.



Additional "fine" setting Nextcloud


During the operation of the cloud during the first month of operation, some problems surfaced, which I had to solve with the help of the community or independently. I must say that I used the service very hard and essentially checked it for stress resistance. Synchronizing several gigabytes of data from the phones and up to a million small files from a computer in the evening was a common thing. In general, the service made a very positive impression on me.

Я бы не сказал, что нижеизложенные решения правильны и красивы, но эти костыли работают по крайней мере для версии 11.0.2, иначе сервисом пользоваться было бы невозможно. В версии 12.х возможно что-то было улучшено и исправлено, поэтому я бы не рекомендовал эти настройки прописывать сразу в рамках стартовой настройки, в то время как для линейки 11.x их можно применять сразу.

Проблема 1

При синхронизации возникает ошибка типа «file is locked». Синхронизация останавливается. Проблема известна — необходимо очистить содержимое таблицы oc_file_locks выполнив из консоли mysql (при авторизации пользователя nextcloud) к ней следующий запрос:
mysql > DELETE FROM oc_file_locks WHERE 1

Так как такие ошибки нередки, то я не придумал ничего лучше, как создать скрипт и положить его прямо в папку суперпользователя:
# nano /root/empty_oc_file_locks

Содержимое скрипта:

 #!/bin/bash mysql -unextcloud > -pnc123 -D nextcloud <<MY_QUERY DELETE FROM oc_file_locks WHERE 1 MY_QUERY 


Скрипт можно выполнять вручную, но это же не наш метод. Я решил запускать его автоматически каждые 15 минут используя cron (https://ru.wikipedia.org/wiki/Cron ).
Для этого нужно создать файл:
# nano /root/crontab

Со следующим содержимым:

*/15 * * * * root bash /root/empty_oc_file_locks


Теперь нужно внести изменения в планировщик:
# crontab /root/crontab

Проверить наличие изменений можно так:
# crontab -l

Проблема 2

При синхронизации по webDAV в логах (смотреть в панели администрирования, авторизовавшись администратором) могут появляться следующие ошибки:

Error PHP reset() expects parameter 1 to be array, null given at /var/www/nextcloud/apps/files_versions/lib/Storage.php#783
Error PHP ksort() expects parameter 1 to be array, null given at /var/www/nextcloud/apps/files_versions/lib/Storage.php#782
Error PHP Invalid argument supplied for foreach() at /var/www/nextcloud/apps/files_versions/lib/Storage.php#759
Error PHP Undefined index: by_file at /var/www/nextcloud/apps/files_versions/lib/Storage.php#759
Error PHP Undefined index: all at /var/www/nextcloud/apps/files_versions/lib/Storage.php#757


This time the community did nothing and had to be investigated alone. The reason was the error "Undefined index ... Storage.php # 757", which cascadingly pulls a few more errors. We look at the code of this file. The whole problem was in quota. On this line in the code (Storage.php # 757) the free space is calculated taking into account the volume of archive files. Something goes wrong in the calculation, although the quota is set to "unlimited". To fix an error in the administration panel, I set an “infinite but numeric” quota for each user, for example, 100TB.

Problem 3

The problem with synchronizing .htaccess files - they just do not sync! And I was not alone, in some forums asked similar questions. However, I did not meet the ready solution. I had to think again myself. As a result of googling, viewing logs, analyzing the code, I did not think of anything better than how to correct the nextcloud engine file.
In the /var/www/nextcloud/lib/private/Files/filesystem.php file, we are looking for the following line: And we bring it to the following form:

$blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array('.htaccess'));




$blacklist = \OC::$server->getConfig()->getSystemValue('blacklisted_files', array(''));




Protection for Nextcloud


Защитить наш сервис от подбора паролей к админке можно с помощью fail2ban. Для этого нужно описать характерное выражение, встречающееся в логах nextcloud при неудачной авторизации, по которому будет срабатывать соответствующий триггер.

Создаём файл:
# nano /etc/fail2ban/filter.d/nextcloud.conf

С нижеприведённым содержимым:

[Definition]
failregex={«reqId»:".*",«remoteAddr»:".*",«app»:«core»,«message»:«Login failed: '.*' \(Remote IP: ''\)»,«level»:2,«time»:".*"}
ignoreregex =

Открываем файл:
# nano /etc/fail2ban/jail.local

И в конец файла добавляем нижеприведённое:

# выявляем неудачные попытки ввода пароля к nextcloud
[nextcloud]
enabled = true
port = http,https
protocol = tcp
filter = nextcloud
logpath = /var/log/nextcloud.log


Перезагружаем сервис:
# service fail2ban restart

Проверяем наличие активного фильтра:
# fail2ban-client status nextcloud

Не забываем, что в соответствии с настройками fail2ban из предыдущей части при неудачном вводе пароля шесть раз подряд в течение 12 часов ваш IP заблокируется ни много ни мало на 30 дней. Я как-то потратил два вечера из-за ошибочного ввода пароля на одном из телефонов, пока не выяснил этот простой факт в логах системы.



Синхронизация с облаком смартфонов


Для синхронизации содержимого телефонов, работающих под Android, существует замечательное приложение FolderSync. Программа полностью оправдывает свою небольшую цену.

Для начала необходимо создать новую учётную запись, в которой в качестве адреса сервера указать https:// 192.168.0.3/nextcloud, ввести логин и пароль от предварительно созданной учётной записи и разрешить самоподписной сертификат. Нажимаем кнопку «Тест» и убеждаемся, что соединение с сервером в порядке.

Далее нужно создать задание. В задании указываем ранее созданную учётную запись и выбираем тип синхронизации – «На удалённую папку». Указываем удалённую папку (создать её можно прямо из приложения» и выбираем локальную папку для синхронизации. Расписание я установил в 2 часа ночи каждый день. В настройках синхронизации у меня было включено «Синхронизация подпапок» и «Синхронизация включенных папок», так же я выбрал опцию всегда заменять старые файлы и в случае конфликтов разрешил по умолчанию использовать локальный файл. В разделе «Соединения» я отключил все соединения кроме Wi-Fi, причём прописал SSID своей домашней Wi-Fi сети в раздел «Разрешённые WiFi SSID'ы» — приложение будет выполнять синхронизацию только в моей домашней сети и не пытаться искать сервер в других сетях. Остальные настройки я оставил по умолчанию. Здесь же можно добавить фильтрацию. Я создал новый фильтр «Имя папки содержит» и указал значение [nosync]. Таким образом, я могу исключить из синхронизации некоторые папки в указанной локальной папке, просто добавляя в конец их названия «[nosync]».

This setting was made for local folders such as DCIM, Download, Telegram, viber, WhatsApp. Plus a couple of my user folders of several gigabytes. Once a day, the contents of these folders are synchronized with the server, and the old versions of the files on the server are not deleted, but renamed and moved to the archive. This allowed me to quickly restore an accidentally deleted file or roll back changes to some other files.



Synchronization with the personal computer cloud


Я не считаю себя настоящим программистом. Последние десять лет я программирую на таких языках программирования, которые применяются разве что при разработке процессоров или чипсетов. Ввиду того, что я уже как лет 15 ничего не делал на Си/Си++, но что-то автоматизировать на компьютере мне требовалось, я довольно активно применял скриптовые языки типа BAT/CMD или такой софт как Sign 0f Mistery или xStarter. Когда-то я узнал и попробовал что такое AutoIt и это стало новой эрой в моей автоматизации на ПК.

After I was convinced of the stability and reliability of the synchronization system on smartphones, I thought that it would be nice to synchronize data on my home computer. Nextcloud has its own client for Windows and, of course, it has become the first candidate for testing. Synchronize I was going to a terabyte order data volume, consisting of hundreds of thousands of files of different sizes. The data was different: music, pictures, documents, e-books, distributions, backup copies of sites and so on and so forth. It would be reasonable to reduce all this to synchronization of more critical data, such as documents, for example, but I was excited about excitement and wanted to check the service for strength.

Спустя десяток часов после начала синхронизации, а по сути первой закачки контента на сервер, клиент запнулся о файл с длинным именем. В то время на сервере я еще использовал подключение внешнего хранилища через VMWare Shared Folders и мне пришлось перепробовать с десяток клиентов, а потом ставить простые эксперименты по ручному копированию файлов на сервер, чтобы понять, что проблема – на стороне сервера. Так, спустя неделю удачного запуска сервиса, пришлось откатываться на резервную виртуальную машину и отказаться от механизма VMWare Shared Folders, начиная всё сначала. В конце концов, я убрал это узкое место на стороне сервера, протестировал надёжность решения неделей синхронизации смартфонов и решил вновь вернуться к домашнему компьютеру. На этот раз клиент не споткнулся о злополучный файл и я уже было возрадовался, однако спустя полсуток синхронизации мелких файлов клиент опять подвис. Теперь выяснилось, что слишком длинный путь именно на стороне домашнего компьютера и клиент Nextcloud не может его корректно обработать. К сожалению, с родным клиентом Nextcloud работы не получилось, да и информативность его была не совсем высока, поэтому от него пришлось отказаться.

Какое-то время я потратил на то, чтобы найти удобную программу для синхронизации, поддерживающее управление через командную строку. Мне хотелось на каждую крупную папку на компьютере сделать своё задание и запускать их в пакетном режиме. Ранее у меня уже был сделан и отработан набор BAT файлов для синхронизации, используя сценарии и управление FreeFileSync через командную строку. Проблема длинных путей или имён файлов решалась заданием локальных папок вида «\\?\D:\Info», т.е. по сути обращением к локальной папке как к сетевой. Однако, что такое webdav FreeFileSync не знает. Полных аналогов FolderSync для Windows, к сожалению, не нашлось, но не раз на форумах вместо неё рекомендовали GoodSync и, после кастинга десятка других программ, я решил попробовать его. К сожалению, GoodSync стоит на порядок дороже, но разовая трата 15$ ради сохранности своих драгоценных данных, в принципе, посильная трата. Программа имеет тестовый режим, поэтому сначала можно убедиться в её работоспособности и стабильности.

GoodSync was pretty friendly software. There is a special portable version called GoodSync2Go. Here she is and interested me. When installing, you need to select the drive letter and the program is installed on it in the GoodSync folder. I created the Sync folder in the root directory of the disk, say D, and moved the created GoodSync folder with all its contents to it.

[ This text was written specifically for the site geektimes.ru by AlexanderS .
Reference to the source is optional, but its mention is highly desirable!
]

After installation, the program needs to create tasks: specify a local folder and a remote folder for synchronization. In the parameters of the task, I chose synchronization from left to right with the choice of options "Synchronous deletion" and "Save previous versions of deleted / replaced files." In the settings of the left side, I chose "Safe Copy" and "Do not create the _gsdata_ folder", the right side - "Safe Copy" and "Fast Predalizatsii on timestamps." Thus, jobs are created for each desired folder. Suppose I set up a task for the Info folder and called it “bck_Info”.
Next, in the D: \ Sync folder, the bck_Info.bat file is created with the following contents:

 @set dir=%~dp0 @%dir%GoodSync\GoodSync2Go-v10.exe /miniwin /exit sync "%~n0" 


Это скриптовый язык BAT. В первой строчке кода в переменную устанавливается текущий путь для запущенного скрипта. Вторая строчка запускает по этому пути из папки GoodSync файл GoodSync2Go-v10.exe, в котором должно выполнится задание с названием имени этого файла (bck_Info), окно выполнения задания минимизируется, по завершению задания программа должна автоматически закрыться. Я могу скопировать этот скрипт несколько раз, каждый раз меняя только его название на имя ранее созданного задания в GoodSync. Таким образом, просто щёлкая кнопкой Enter по BAT файлу я могу запускать синхронизацию нужных мне папок индивидуально.

Для добавления нового задания в FreeFileSync я мог просто скопировать xml файл сценария и вручную поправить его, т.е. запуска графической оболочки программы не требовалось вообще. В GoodSync же все задания прописываются в файле D:\Sync\GoodSync\GoodSync\Profile\jobs.tic и для добавления нового задания нужно будет отрыть программу и создать его, т.к. править этот файл несколько проблематично и неизвестно к чему это может привести.
Для синхронизации всех папок теперь можно написать простой скрипт bck_all.bat:

 @set dir=%~dp0 call %dir%bck_Info.bat call %dir%bck_Info2.bat call %dir%bck_Info3.bat call %dir%bck_Info4.bat 

Каждая строчка скрипта просто вызывает выполнение отдельного скрипта, которое запускает синхронизацию.

This is all very good and works comfortably, but there is no error control during synchronization. For example, if the server is not turned on, then all tasks will be promptly completed, and I, returning after an hour, will think that the synchronization has already been completed. At the same time, logs of all tasks are created using the path D: \ Sync \ GoodSync \ GoodSync \ Profile \ *. Log. It is enough just to view the log of each synchronization for the presence of the word “ERROR” - for some reason, this is how the synchronization failures are reported in the log. Therefore, it was decided to write a small program to analyze these logs after all the synchronizations, which will be launched automatically after the synchronization of all folders. The program received the proud name log_analayser and is written in the semi-script language AutoIt . If you are interested in someone, then download its full version.You can on the official site AutoIt, which contains the necessary libraries, compiler and SciTE - a cross-platform editor for the code from which you can and compile the program.

What time I spent on developing and debugging the code, the result was a file log_analayser.au3 with the following contents:

 ; LOG Analyser 1.0 ; Программа предназначена для анализа текстовых лог-файлов #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Res_Field=ProductName|LOG Analyser #AutoIt3Wrapper_Res_Fileversion=1.0.0.0 #AutoIt3Wrapper_Res_Field=OriginalFilename|log_analyser.exe #AutoIt3Wrapper_Res_Comment=Программа предназначена для анализа текстовых лог-файлов #AutoIt3Wrapper_Res_Description=Анализ лог-файлов ;**** #AutoIt3Wrapper_Res_Language=1049 #AutoIt3Wrapper_Res_ProductVersion=1.0 #AutoIt3Wrapper_Compile_Both=y #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** ;AutoItSetOption ("WinTitleMatchMode", 2) ; сопоставление заголовка окна с произвольным фрагментом ;#NoTrayIcon ; скрыть иконку из трея во время выполнения программы If WinExists('[CLASS:AutoIt v3;TITLE:' & @ScriptName & ']') Then MsgBox(48, @ScriptName, "Позволено запускать только одну копию программы!"); ;Раскоментируйте следующую строчку если нужно активировать окно вашей программы при повторном её запуске ;WinActivate('Имя вашей программы') Exit EndIf AutoItWinSetTitle(@ScriptName) #include <Array.au3> #include <_FileDirList.au3> ; настройки Local $msg_title = "LOG Analyser 1.0" Local $path = @ScriptDir Local $soft_open_log = "notepad.exe" Local $path, $dir_mode, $word, $file_analyse_name, $file_analyse_ext, $log_path, $log_msg_on Local $file_log, $word_detect, $file_analyse, $cnt_files, $i ;проверка и загрузка параметров if ($CmdLine[0] < 6) then MsgBox(0x10, $msg_title, "Отсутствуют или недостаточно параметров!" & @CRLF & @CRLF & "Работа программы прекращена") Exit else if (StringCompare($CmdLine[1], "file") = 0) then $dir_mode = 0 elseif (StringCompare($CmdLine[1], "dir") = 0) then $dir_mode = 1 else MsgBox(0x10, $msg_title, "Первый параметр должен принимать значения 'file' или 'dir'!" & @CRLF & @CRLF & "Работа программы прекращена") Exit endif $word = $CmdLine[2] if ($dir_mode = 0) then $file_analyse_name = $CmdLine[3] else $dir_analyse = $CmdLine[3] endif $file_analyse_ext = $CmdLine[4] $log_path = $CmdLine[5] if (StringCompare($CmdLine[6], "err_msg_on") = 0) then $log_msg_on = 1 elseif (StringCompare($CmdLine[6], "err_msg_off") = 0) then $log_msg_on = 0 else MsgBox(0x10, $msg_title, "Шестой параметр должен принимать значения 'log_msg_on' или 'log_msg_off'!" & @CRLF & @CRLF & "Работа программы прекращена") Exit endif endIf ; инициализация переменных $file_log = $log_path & "\" & "log_analyser" & "-" & @YEAR & "-" & @MON & "-" & @MDAY & "-" & @HOUR & "-" & @MIN & "-" & @SEC & ".log" $word_detect = 0 ; основной код программы if ($dir_mode = 0) then $file_analyse = $file_analyse_name & "." & $file_analyse_ext if (_file_analyser($file_analyse, $msg_title, $word, $file_log, $word_detect) = 1) then $word_detect = 1 endif else ; сканирование файлов для анализа $dir_arr = _FileDirList($dir_analyse, "*."&$file_analyse_ext, 1, 1, 0) ;_ArrayDisplay($dir_arr) ; проверка после сканирования - проверка на наличие файлов для анализа if ($dir_arr = 0) then MsgBox(0x10, $msg_title, "Неверный путь или не обнаружены файлы для анализа!" & @CRLF & @CRLF & "Работа программы прекращена") Exit endif $cnt_files = $dir_arr[0] ; перебор анализируемых файлов $i = 0 While $i <> $cnt_files $i = $i + 1 $file_analyse = $dir_arr[$i] if (_file_analyser($file_analyse, $msg_title, $word, $file_log, $word_detect) = 1) then $word_detect = 1 endif WEnd endif ; обработка результатов анализа if ($word_detect = 1) and ($log_msg_on = 1) then if (MsgBox (0x41034, $msg_title, "Обнаружены ошибки!" & @CRLF & "Все строки с ошибками записаны в файл: " & $file_log & @CRLF & @CRLF & "Открыть файл с ошибками?")) = 6 then ShellExecuteWait($soft_open_log, $file_log) endif endif Exit ; функция выполняет построчный поиск слова в файле и возвращает переменную информирующую о наличии слова хотя бы в одной строке ; все обнаруженные строки, содержащие указанное слово, пишутся в файл лога Func _file_analyser($file_analyse, $msg_title, $word, $file_log, $word_detect) Local $file1, $file2, $file_line, $write_once $word_detect = 0 $write_once = 0 $file1 = FileOpen($file_analyse, 0) ; проверка наличия анализируемого файла If $file1 = -1 Then FileClose($file1) MsgBox(0x10, $msg_title, "Отсутствует файл для анализа!" & @CRLF & @CRLF & "Работа программы прекращена") Exit EndIf ; построчный поиск слова в анализируемом файле While 1 $file_line = FileReadLine($file1) If @error = -1 Then ExitLoop if (StringInStr($file_line, $word) <> 0) then $word_detect = 1 ; проверка наличия файла для лога и его создание в случае отсутствия if (FileExists($file_log) = 0) then $file2 = FileOpen($file_log, 1) FileClose($file2) endif ; однакоратная запись в файл имени анализируемого файла if ($write_once = 0) then $write_once = 1 $file2 = FileOpen($file_log, 1) FileWriteLine($file2, "Анализ файла: " & $file_analyse) FileClose($file2) endif ; вывод в лог строки с ошибкой $file2 = FileOpen($file_log, 1) FileWriteLine($file2, $file_line) FileClose($file2) endif WEnd ; если были записи в файл, то отделяем их пустой строкой от следующего массива записей if ($word_detect = 1) then $file2 = FileOpen($file_log, 1) FileWriteLine($file2, @CRLF) FileClose($file2) endif FileClose($file1) Return $word_detect EndFunc 

После набора кода нажимаем кнопку F7 в редакторе SciTE и получаем на выходе файл log_analayser.exe.

Программа анализирует файл на наличие какого-либо слова, при нахождении создаётся файл лога, в который копируется найденная строка, содержащая это слово.

Программа может работать в двух режимах:

— анализ конкретного файла
— анализ папки, содержащей файлы для анализа (анализируются так же все вложенные подпапки)

При консольном вызове необходимо задать шесть параметров для программы:

1 — режим работы [file = анализ файла; dir = анализ папки, содержащей файлы]
2 — ключевое слово для поиска
3 — имя файла или полного пути к папке
4 — расширения файла или файлов для анализа в папке
5 — полный путь к папке, где будет расположен лог программы
6 — отображение окна после анализа всех файлов в случае нахождения заданного слова [err_msg_on = отображать; err_msg_off = не отображать]

Таким образом, получился новый скрипт bck_auto.bat:

 @echo Start Backup @set dir=%~dp0 call %dir%bck_all.bat log_analyser.exe dir ОШИБКА %dir%GoodSync\Profile log %dir%LOG err_msg_on exit 

Скрипт запускает файл, из которого индивидуально друг за другом вызываются задания на синхронизацию всех нужных папок, а затем вызывается анализатор логов синхронизаций, по завершении работы которого в случае ошибок показывается сообщение с предложением просмотреть строки логов, где обнаружены эти ошибки и можно понять с каким заданием случились проблемы. Эти строки пишутся в отдельный лог-файл в папке D:\Sync\LOG.
И тут меня постигла жуткая неудача. Анализатор логов не работал. Нет, он прекрасно работал на тестовых файлах, но упорно не хотел видеть ошибки в логах. Я долго не мог понять в чём причина, пока не выяснил одну жуткую вещь: мало того, что в англоязычном логе сбой выводится единственным русскоязычным словом «ОШИБКА», так ещё и кодировка этой кириллицы – Macintosh! Зачем так сделали программисты из Siber Systems я не знаю, всего скорее это результат какого-то ужасного костыля внутри софта. Ну а кто сказал, что программирование должно быть скучным?

Ничего не оставалось как подпереть один костыль другим и в результате появилась работающая конструкция:

 @echo Start Backup @set dir=%~dp0 call %dir%bck_all.bat log_analyser.exe dir Ћ˜€ЃЉЂ %dir%GoodSync\Profile log %dir%LOG err_msg_on exit 

Однако появилась следующая проблема: сам GoodSync не удаляет файлы логов, с каждым новым выполнением задания появлялись новые файлы. И если какая-то синхронизация завершилась с ошибкой, то наш анализатор всегда будет находить этот файл и бодро рапортовать об ошибке. Поэтому перед запуском синхронизаций решено было автоматически очищать папку D:\Sync от любых файлов с логами. Для этого создан элегантный скрипт clean_logs.bat:

 @echo off set dir=%~dp0 For /R %dir% %%i in (*.log) Do ( Del /q "%%i") @echo on 

Скрипт отключает вывод каких-либо сообщений, выясняет директорию запуска скрипта, сканирует все файлы (в том числе в подпапках) пока они не закончатся и удаляет все файлы с расширением log. По окончании работы вывод сообщений включается.
Скрипт bck_auto.bat преобразился:

 @echo Start Backup @set dir=%~dp0 @call clean_logs.bat call %dir%bck_all.bat log_analyser.exe dir Ћ˜€ЃЉЂ %dir%GoodSync\Profile log %dir%LOG err_msg_on exit 

Everything works very well, but the point is in automating routine actions. Why not just turn off the computer at night and go to sleep, but he synchronizes the path of a bunch of files, analyzes and turns off?

Let's refine our bck_auto.bat script:

 @echo Start Backup & PCOFF @set dir=%~dp0 start MonitorOnOff.exe 0 @call clean_logs.bat call %dir%bck_all.bat log_analyser.exe dir Ћ˜€ЃЉЂ %dir%GoodSync\Profile log %dir%LOG err_msg_off shutdown /s /t 0 exit 

The script has two new lines. The MonitorOnOff application simply turns off the monitor (so that it does not light up the room, but I manually turn it off every evening and turn on every morning is very lazy), and the shutdown command turns off the computer. In log_analyser, the parameter responsible for displaying messages when an error has been changed - after all, after synchronization, you do not need to slow down the execution of the script with this message, but allow it to turn off the computer.

The MonitorOnOff program is also written in AutoIt.

 ; Monitor On Off 1.0 ; Программа для включения/отключения монитора #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Res_Field=ProductName|Monitor On Off #AutoIt3Wrapper_Res_Fileversion=1.0.0.0 #AutoIt3Wrapper_Res_Field=OriginalFilename|MonitorOnOff.exe #AutoIt3Wrapper_Res_Comment=Программа для включения/отключения монитора #AutoIt3Wrapper_Res_Description=Программа для включения/отключения монитора ;**** #AutoIt3Wrapper_Res_Language=1049 #AutoIt3Wrapper_Res_ProductVersion=1.0 #AutoIt3Wrapper_Compile_Both=y #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** ;AutoItSetOption ("WinTitleMatchMode", 2) ; сопоставление заголовка окна с произвольным фрагментом ;#NoTrayIcon ; скрыть иконку из трея во время выполнения программы If WinExists('[CLASS:AutoIt v3;TITLE:' & @ScriptName & ']') Then MsgBox(48, @ScriptName, "Позволено запускать только одну копию программы!"); ;Раскоментируйте следующую строчку если нужно активировать окно вашей программы при повторном её запуске ;WinActivate('Имя вашей программы') Exit EndIf AutoItWinSetTitle(@ScriptName) HotKeySet("{F10}", "_Monitor_ON") HotKeySet("{F11}", "_Monitor_OFF") HotKeySet("{Esc}", "_Quit") Global Const $lciWM_SYSCommand = 274 Global Const $lciSC_MonitorPower = 61808 Global Const $lciPower_Off = 2 Global Const $lciPower_On = -1 Global $MonitorIsOff = False if ($CmdLine[0] <> 0) then _Monitor_OFF() endif While 1 Sleep(10) WEnd Func _Monitor_ON() $MonitorIsOff = False Local $Progman_hwnd = WinGetHandle('[CLASS:Progman]') DllCall('user32.dll', 'int', 'SendMessage', _ 'hwnd', $Progman_hwnd, _ 'int', $lciWM_SYSCommand, _ 'int', $lciSC_MonitorPower, _ 'int', $lciPower_On) EndFunc Func _Monitor_OFF() $MonitorIsOff = True Local $Progman_hwnd = WinGetHandle('[CLASS:Progman]') While $MonitorIsOff = True DllCall('user32.dll', 'int', 'SendMessage', _ 'hwnd', $Progman_hwnd, _ 'int', $lciWM_SYSCommand, _ 'int', $lciSC_MonitorPower, _ 'int', $lciPower_Off) _IdleWaitCommit(0) Sleep(20) WEnd EndFunc Func _IdleWaitCommit($idlesec) Local $iSave, $LastInputInfo = DllStructCreate ("uint;dword") DllStructSetData ($LastInputInfo, 1, DllStructGetSize ($LastInputInfo)) DllCall ("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr ($LastInputInfo)) Do $iSave = DllStructGetData ($LastInputInfo, 2) Sleep(60) DllCall ("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr ($LastInputInfo)) Until (DllStructGetData ($LastInputInfo, 2)-$iSave) > $idlesec Or $MonitorIsOff = False Return DllStructGetData ($LastInputInfo, 2)-$iSave EndFunc Func _Quit() _Monitor_ON() Exit EndFunc 

Запущенная программа управляется тремя клавишами: F10 включает монитор, F11 – отключает, а кнопка ESC завершает работу программы и выгружает её из памяти. При задании любого параметра при запуске программы запущенная программа сразу отключит экран.

Now everything was fine - before going to sleep, I just ran bck_all.bat, instead of “Turn off computer” and went to sleep. The monitor did not illuminate the entire room, synchronization was performed automatically and its success was automatically analyzed. In the morning, it was necessary only to look at the contents of the folder D: \ Sync \ GoodSync \ LOG \ for at least some files. But this is also not the case - why waste time if everything is fine? It is necessary to make a log analyzer log analyzer and hang it in autoload of the system so that it will work the next day when the computer is booted and disturbed my attention only when synchronization fails. This is how the check_file_exist program appeared.

 ; Check File Exist 1.0 ; Программа предназначена для проверки наличия указанного файла #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Res_Field=ProductName|Check File Exist #AutoIt3Wrapper_Res_Fileversion=1.0.0.0 #AutoIt3Wrapper_Res_Field=OriginalFilename|check_file_exist.exe #AutoIt3Wrapper_Res_Comment=Программа предназначена для проверки наличия указанного файла #AutoIt3Wrapper_Res_Description=Провека существования файла ;**** #AutoIt3Wrapper_Res_Language=1049 #AutoIt3Wrapper_Res_ProductVersion=1.0 #AutoIt3Wrapper_Compile_Both=y #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** ;AutoItSetOption ("WinTitleMatchMode", 2) ; сопоставление заголовка окна с произвольным фрагментом ;#NoTrayIcon ; скрыть иконку из трея во время выполнения программы If WinExists('[CLASS:AutoIt v3;TITLE:' & @ScriptName & ']') Then MsgBox(48, @ScriptName, "Позволено запускать только одну копию программы!"); ;Раскоментируйте следующую строчку если нужно активировать окно вашей программы при повторном её запуске ;WinActivate('Имя вашей программы') Exit EndIf AutoItWinSetTitle(@ScriptName) #include <Array.au3> #include <_FileDirList.au3> ; настройки Local $msg_title = "Check File Exist 1.0" Local $path = @ScriptDir Local $soft_open_dir = "explorer.exe" Local $path, $dir_analyse, $words, $msg_open ;проверка и загрузка параметров if ($CmdLine[0] < 5) then MsgBox(0x10, $msg_title, "Отсутствуют или недостаточно параметров!" & @CRLF & @CRLF & "Работа программы прекращена") Exit else $dir_analyse = $CmdLine[1] $file = $CmdLine[2] $words0 = $CmdLine[3] $words1 = $CmdLine[4] if (StringCompare($CmdLine[5], "msg_on") = 0) then $msg_open = 1 elseif (StringCompare($CmdLine[5], "msg_off") = 0) then $msg_open = 0 else MsgBox(0x10, $msg_title, "Пятый параметр должен принимать значения 'msg_on' или 'msg_off'!" & @CRLF & @CRLF & "Работа программы прекращена") Exit endif endIf ; сканирование директории на наличие файлов $dir_arr = _FileDirList($dir_analyse, "*"&$file&"*", 1, 0, 0) ;_ArrayDisplay($dir_arr) ; проверка наличия файла и действия if ($dir_arr = 0) then if (StringCompare($words0, "0") <> 0) then if ($msg_open = 0) then MsgBox(0x41030, $msg_title, $words0) else if (MsgBox(0x41034, $msg_title, $words0 & @CRLF & @CRLF & "Открыть папку с не обнаруженными файлами?")) = 6 then ShellExecuteWait($soft_open_dir, $dir_analyse) endif endif endif else if (StringCompare($words1, "0") <> 0) then if ($msg_open = 0) then MsgBox(0x41030, $msg_title, $words1) else if (MsgBox(0x41034, $msg_title, $words1 & @CRLF & @CRLF & "Открыть папку с обнаруженными файлами?")) = 6 then ShellExecuteWait($soft_open_dir, $dir_analyse) endif endif endif endif Exit 

По сути эта программа – немного урезанный функционал log_analyser. Программа анализирует указанную папку (без учёта подпапок) на наличие файлов и именами хотя бы частично совпадающими с указанным словом для поиска и выводит сообщение о результате проверки.

Параметры программы:

1 — полный путь к папке (без символа слеша — /)
2 — ключевое слово для поиска в именах файлов, либо полное название файла
3 — текстовая строка, выводимая при ненахождении файл, если =0 — не выводить сообщение
4 — текстовая строка, выводимая при нахождении файла, если =0 — не выводить сообщение
5 — вывод сообщения: msg_off — выводится только сообщение о наличии/отсутствии файлов, msg_on — в выведенном окне предлагается так же открыть папку, в которой обнаружены или необнаружены файлы

Теперь, для этой программы я создал скрипт Check_LOG_from_log_analyser.bat, ссылку которого разместил в обычной автозагрузке Windows:

 @set dir=%~dp0LOG start check_file_exist.exe %dir% .log 0 "Во время последней синхронизации были проблемы!" msg_on exit 

Таким образом, в финале мы получили полностью автономное решение, которое не зависит от местонахождения папки Sync и корректно отработает из любого места нашего компьютера. Решение не только работоспособно, но и стабильно – на Windows 7 х64 данный комплект скриптов отработал год и абсолютно никаких проблем с ним не возникло.

Возможно сейчас всё это кажется несколько монстрообразным, однако ничего сложно в этом нет. Если внимательно присмотреться к коду AutoIt, то базовой конструкцией является обычные циклы if-then-else-end, однотипные для любого языка программирования, в которые встроены некоторые повторяющиеся операторы и функции AutoIt, которые изучаются буквально за пару вечеров. Скриптовый язык BAT можно даже не учить, так как большинство решений типовые и уже давно описаны в интернете. Уметь пользоваться программированием не только интересно, но может быть и весьма полезно.

Ода коду от Dark Dragon




Afterword


To be honest, I assumed, but did not expect such a volume of articles for which I had to spend up to fifty hours. As a rule, on the Internet, installing your own cloud is reduced to sayings like: “Yes, there you have to execute several commands”. This is true - the installation is trivial. When you know what commands to enter into the console and what they mean. When you understand the essence of network routing. When you already have a working server and when you understand how to add a host to it. When you know how to install the site. That is, to use these several commands you need to have a certain amount of knowledge and experience. The purpose of these three articles is an attempt to create such baggage, having collected the necessary sufficient information in one place and to explain how to use it correctly. I sincerely hopeThat this series of articles will help someone make their first conscious steps in the world of free software.



Return to the beginning, to the table of contents .



The history of creating a home cloud. Part 3. Creating a personal cloud - installing and configuring Nextcloud.
Text version: 1.2.0.
Date of first publication: 08.02.2018.
Last edited on: February 08, 2018.

Update log
1.2.0 [08-02-2018]
Коррекция текста.

1.1.0 [08-02-2018]
Коррекция текста.

1.0.0 [08-02-2018]
Первая версия.
Описывается установка и настройка Nextcloud 11.0.2 в виртуальной машине VMWare, конфигурация сетевого окружения VMWare и освещаются некоторые моменты настройки, проявившиеся в процессе эксплуатации Nextcloud.



Information for the administration of the resource (suspicion of a bug)
Если в какой-то тег (например, code или blockquote) в вышеприведённом тексте обернуть следующую конструкцию:
[Definition]
failregex={«reqId»:".*",«remoteAddr»:".*",«app»:«core»,«message»:«Login failed: '.*' \(Remote IP: ''\)»,«level»:2,«time»:".*"}
ignoreregex =

То закрывающий тег фильтруется и оформление применяется до конца статьи! Подобный эффект проявляется именно в этом тексте, т.к. отдельно воспроизвести эффект мне не удалось. Парную корректность тегов (открыто/закрыто) проверил — вроде бы всё нормально. Методика повторения:
— создать черновик
— скопировать исходное форматирование этой статьи и разместить в черновике
— в тексте, в разделе «Защита для Nextcloud» обернуть вышеуказанную конструкцию, например, цитатой
— эффект проявляется, в цитату попадёт весь текст до конца статьи



Source: https://habr.com/ru/post/410011/