Linux Tutorial – Puntata 33

di jolek78

Care/i fruitrici e fruitori del blog, in questi post – ogni domenica mattina – si parlerà del sistema operativo GNU/Linux e degli strumenti per utilizzarlo al massimo delle potenzialità. Cercheremo di spiegare come funziona, cosa è il kernel, come costruirsi una vpn, come settare un firewall e giocare col terminale, usare adb e altro. Se il capitalismo della sorveglianza ci vuole passivi consumatori-consumatrici di servizi noi si risponde con un po’ di “cultura informatica” e un MARAMEO (quasi affettuoso). Buona lettura!

Signore e signori, mesdames et messieurs, fruitori della bottega e non, mi fermo qui. Per un po’ almeno. Questo era un esperimento per capire come il pubblico della bottega avrebbe preso l’introduzione di un argomento cosi’ differente dal solito come Linux, l’open source, ma sopratutto il “codice”. Taaaanto codice. E no, non è stato un gran successo. Poche interazioni, poche visite, a fronte pero’ di tanto lavoro dietro. Quindi questa è l’ultima puntata, almeno per un po’, di questa rubrica. Io la domenica mattina continuerò a bere il mio the, a fare i miei esperimenti. Ma prometto che smetterò di tediarvi con questa enorme “spataffiata” di comandi settimanale. Giurin giurello. Ora pero’ bando alle ciance, accendete la macchina virtuale della bottega. Si comincia.

mariadb
Quando mi affacciai nel mondo Linux, dovetti fare i conti con il linguaggio SQL, e uno dei primi database con cui mi trovai a lavorare fu MySQL, un database open source che si affiancava a un altro linguaggio di programmazione, questa volta per pagine web, chiamato PHP.  Il quadrinomio Linux, Apache, MySQL e PHP veniva chiamato in gergo LAMP, ovvero un insieme di software che permettevano di avere un server web funzionante utilizzando il meglio che la comunità open source aveva da offrire a quei tempi. MySQL mi rimase nel cuore, tanto che realizzammo, insieme a un esteso gruppo di amici, un database online per immagini astronomiche. Poi passo’ il tempo, quasi dieci anni, e MySQL si ritrovo’ a far parte della grande famiglia della Oracle. Fu infatti prima acquistato dalla Sun Microsystem e poi, successivamente, la Sun venne acquistata dalla Oracle, famosa per il suo straordinario database, ma non di certo famosa per il suo supporto alla comunità opensource. Fu cosi’ che il fondatore di MySQL, Michael Widenius, temendo la scomparsa definitiva del più celebre database opensource, creo’ un fork chiamato MariaDB che riprendeva l’essenza di MySQL, ma che ne estendeva le sue funzionalità a un livello superiore. Il tentativo quindi, all’interno di questa puntata, sarà di creare un piccolo database per archiviare i libri che abbiamo il libreria.

install
Partiamo proprio dalle basi. Che cos’e’ un database? È banalmente una “base di dati”, cioè un posto dove archiviare dati ed elencarli in maniera tale da poterli ritrovare facilmente. La prima cosa che dobbiamo fare, dunque, è installare il server:

bottega@bottegadelbarbieri  ~  sudo apt install mariadb-server mariadb-client -y
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
galera-3 libcgi-fast-perl libcgi-pm-perl libconfig-inifiles-perl libdbd-mysql-perl libdbi-perl libfcgi-perl libhtml-template-perl libterm-readkey-perl mariadb-client-10.3 mariadb-client-core-10.3 mariadb-common mariadb-server-10.3 mariadb-server-core-10.3
Suggested packages:
libclone-perl libmldbm-perl libnet-daemon-perl libsql-statement-perl libipc-sharedcache-perl mailx mariadb-test tinyca
The following NEW packages will be installed
galera-3 libcgi-fast-perl libcgi-pm-perl libconfig-inifiles-perl libdbd-mysql-perl libdbi-perl libfcgi-perl libhtml-template-perl libterm-readkey-perl mariadb-client mariadb-client-10.3 mariadb-client-core-10.3 mariadb-common mariadb-server mariadb-server-10.3 mariadb-server-core-10.3
0 to upgrade, 16 to newly install, 0 to remove and 0 not to upgrade.
Need to get 19.3 MB of archives.
After this operation, 163 MB of additional disk space will be used.
[....]
Setting up libdbi-perl:amd64 (1.643-1ubuntu0.1) ...
Setting up libcgi-fast-perl (1:2.15-1) ...
Setting up mariadb-client-10.3 (1:10.3.31-0ubuntu0.20.04.1) ...
Setting up libdbd-mysql-perl:amd64 (4.050-3) ...
Setting up mariadb-server-10.3 (1:10.3.31-0ubuntu0.20.04.1) ...
Setting up mariadb-client (1:10.3.31-0ubuntu0.20.04.1) ...
Setting up mariadb-server (1:10.3.31-0ubuntu0.20.04.1) ...
Processing triggers for systemd (245.4-4ubuntu3.13) ...
Processing triggers for man-db (2.9.1-1) ...
Processing triggers for menu (2.1.47ubuntu4) ..

skip-networking
Dopo l’installazione, dovremo avviare MariaDB in “safe mode”, ovvero in modalità “troncata” in attesa della sua prima configurazione. Dunque:

bottega@bottegadelbarbieri  ~  sudo mysqld_safe --skip-grant-tables --skip-networking &
[1] 127995

secure installation
E ora, dopo averlo avviato, passiamo alla prima configurazione. Semplice come bere un bicchier d’acqua:

bottega@bottegadelbarbieri  ~  sudo mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] Y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
... Success!

By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] Y
... Success!

Normally, root should only be allowed to connect from 'localhost'. This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] Y
... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] Y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] Y
... Success!

Cleaning up...

All done! If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

enable mariadb
Ora avviamo il demone e verifichiamo lo stato del database:

bottega@bottegadelbarbieri  ~  sudo systemctl enable mariadb

bottega@bottegadelbarbieri  ~  sudo systemctl status mariadb 
[sudo] password for bottega: 
● mariadb.service - MariaDB 10.3.31 database server
Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2021-11-06 11:39:58 GMT; 3h 26min ago
Docs: man:mysqld(8)
https://mariadb.com/kb/en/library/systemd/
Process: 150585 ExecStartPre=/usr/bin/install -m 755 -o mysql -g root -d /var/run/mysqld (code=exited, status=0/SUCCESS)
Process: 150586 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
Process: 150588 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= || VAR=`cd /usr/bin/..; /usr/bin/galera_recovery`; [ $? -eq 0 ] && systemctl set-environment _WSREP_START_POSITION=$VAR || exit 1 (code=exited, status=0/SUCCESS)
Process: 150666 ExecStartPost=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
Process: 150668 ExecStartPost=/etc/mysql/debian-start (code=exited, status=0/SUCCESS)
Main PID: 150635 (mysqld)
Status: "Taking your SQL requests now..."
Tasks: 31 (limit: 2267)
Memory: 69.6M
CGroup: /system.slice/mariadb.service
└─150635 /usr/sbin/mysqld

primo login – root:
A questo punto configuriamo i permessi dell’utente root

bottega@bottegadelbarbieri  ~  mysql -u root -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 56
Server version: 10.3.31-MariaDB-0ubuntu0.20.04.1 Ubuntu 20.04

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> USE mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [mysql]> UPDATE user SET plugin='mysql_native_password' WHERE User='root';
Query OK, 0 rows affected (0.012 sec)
Rows matched: 1 Changed: 0 Warnings: 0


MariaDB [mysql]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.001 sec)

MariaDB [mysql]> \quit;
Bye

secondo login – root:
Facciamo il reboot al database, e poi logghiamoci per la seconda volta:

bottega@bottegadelbarbieri  ~  sudo systemctl restart mariadb

bottega@bottegadelbarbieri  ~  sudo mysql -u root-p

Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 36
Server version: 10.3.31-MariaDB-0ubuntu0.20.04.1 Ubuntu 20.04

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

create database // create user
A questo punto creiamo prima un database, books, e poi un utente, bottegadb, a cui daremo i permessi per gestirlo:

MariaDB [(none)]> CREATE DATABASE books;
Query OK, 1 row affected (0.000 sec)

MariaDB [(none)]> CREATE USER 'bottegadb'@'localhost' IDENTIFIED BY 'Bottega##';
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> GRANT ALL PRIVILEGES ON books . * TO 'bottegadb'@'localhost';
Query OK, 0 rows affected (0.000 sec)


MariaDB [mysql]> SHOW GRANTS for bottegadb@localhost;
+------------------------------------------------------------------------------------------------------------------+
| Grants for bottegadb@localhost                                                                                   |
+------------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `bottegadb`@`localhost` IDENTIFIED BY PASSWORD '*E011AAC1300172FA66C680DAB0D6EF69A7190CFA' |
| GRANT ALL PRIVILEGES ON `books`.* TO `bottegadb`@`localhost`                                                     |
+------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.000 sec)

MariaDB [(none)]> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| books              |
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
4 rows in set (0.038 sec)

MariaDB [(none)]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> \quit ;
Bye

login – bottegadb
Siamo pronti per il primo login:

bottega@bottegadelbarbieri  ~  sudo mysql -u bottegadb -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 16
Server version: 10.3.31-MariaDB-0ubuntu0.20.04.1 Ubuntu 20.04

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show databases ;
+--------------------+
| Database           |
+--------------------+
| books              |
| information_schema |
+--------------------+
2 rows in set (0.001 sec)

MariaDB [(none)]> use books ;
Database changed

Ora pero’ fate un piccolo lavoro d’immaginazione. Immaginate che ci sia una sorta di matrioska, dove dentro una scatola grande c’e’ una scatola media e dentro la scatola media c’e’ la scatola piccola. Dunque, la scatola grande è tutto MariaDB, la scatola media è il singolo database di MariaDB, la scatola piccola sono le “tables” di MariaDB. Immaginato questo, vi sarà subito chiaro che il database books e’ soltanto uno dei tanti database che possiamo avere dentro MariaDB. E se questo è vero, sarà anche vero che al suo interno possiamo avere tante tavole strutturate in maniera differente.

 

create table
Dunque andiamone a creare due. Una in cui inseriremo i dati dei libri e un’altra in cui inseriremo la loro posizione nella nostra libreria

MariaDB [books]> create table books_index( title VARCHAR(40), author VARCHAR(40), publisher VARCHAR(20), isbn VARCHAR(20), year INT );
Query OK, 0 rows affected (0.024 sec)

MariaDB [books]> create table books_position( bookshelf INT, position VARCHAR(4), isbn VARCHAR(20), year INT );
Query OK, 0 rows affected (0.019 sec)

MariaDB [books]> show tables;
+-----------------+
| Tables_in_books |
+-----------------+
| books_index     |
| books_position  |
+-----------------+
2 rows in set (0.000 sec)

books_index // books_position
Decidiamo che la numerazione per le librerie parte da sinistra (sempre da sinistra…), e che invece la posizione va per lettere dalla a alla z, dall’alto verso il basso. Sinistra, alto. Suona bene. E poi decidiamo i campi.

– books_index     >> title, author, publisher, isbn, year
– books_position >> bookshelf, position, isbn, year

MariaDB [books]> insert into books_index ( title, author, publisher, isbn, year ) values ( 'the intelligence trap' ,'david robson' ,'hodder' , '9781473669857', 2020),
-> ( 'quiet power' ,'susan cain' ,'penguin books' , '9780241977910', 2016),
-> ( 'the tiranny of merit' ,'michael sandel' ,'penguin books' , '9780141991177', 2021),
-> ( 'nudge' ,'richard thaler' ,'penguin books' , '9700241552100', 2021),
-> ( 'thinking fast and slow' ,'daniel kahneman' ,'penguin books' , '9780141033570', 2012),
-> ( 'dataism' ,'steve lohr' ,'oneworld' , '9781780748368', 2015),
-> ( 'democracy hacked' ,'martin moore' ,'oneworld' , '9781786075758', 2018),
-> ( 'people vs tech' ,'jamie bartlett' ,'penguin books' , '9781785039065', 2018),
-> ( 'homo deus' ,'yuval harari' ,'penguin books' , '9781784703936', 2016);
Query OK, 9 rows affected (0.041 sec)
Records: 9 Duplicates: 0 Warnings: 0

MariaDB [books]> select * from books_index;
+------------------------+-----------------+---------------+---------------+------+
| title                  | author          | publisher     | isbn          | year |
+------------------------+-----------------+---------------+---------------+------+
| the intelligence trap  | david robson    | hodder        | 9781473669857 | 2020 |
| quiet power            | susan cain      | penguin books | 9780241977910 | 2016 |
| the tiranny of merit   | michael sandel  | penguin books | 9780141991177 | 2021 |
| nudge                  | richard thaler  | penguin books | 9700241552100 | 2021 |
| thinking fast and slow | daniel kahneman | penguin books | 9780141033570 | 2012 |
| dataism                | steve lohr      | oneworld      | 9781780748368 | 2015 |
| democracy hacked       | martin moore    | oneworld      | 9781786075758 | 2018 |
| people vs tech         | jamie bartlett  | penguin books | 9781785039065 | 2018 |
| homo deus              | yuval harari    | penguin books | 9781784703936 | 2016 |
+------------------------+-----------------+---------------+---------------+------+
9 rows in set (0.011 sec)



MariaDB [books]> insert into books_position ( bookshelf, position, isbn, year) values (9, 'a', 9781473669857, 2020);
-> (1, 'a', 9780241977910, 2016),
-> (1, 'a', 9780141991177, 2021),
-> (1, 'a', 9700241552100, 2021),
-> (1, 'a', 9780141033570, 2012),
-> (1, 'a', 9781780748368, 2015),
-> (1, 'a', 9781786075758, 2018),
-> (1, 'a', 9781785039065, 2018),
-> (1, 'a', 9781784703936, 2016);
Query OK, 9 rows affected (0.003 sec)
Records: 9 Duplicates: 0 Warnings: 0

MariaDB [books]> select * from books_position;
+-----------+----------+---------------+------+
| bookshelf | position | isbn          | year |
+-----------+----------+---------------+------+
| 1         | a        | 9781473669857 | 2020 |
| 1         | a        | 9780241977910 | 2016 |
| 1         | a        | 9780141991177 | 2021 |
| 1         | a        | 9700241552100 | 2021 |
| 1         | a        | 9780141033570 | 2012 |
| 1         | a        | 9781780748368 | 2015 |
| 1         | a        | 9781786075758 | 2018 |
| 1         | a        | 9781785039065 | 2018 |
| 1         | a        | 9781784703936 | 2016 |
+-----------+----------+---------------+------+
9 rows in set (0.000 sec)

where *
E ora facciamo una ricerca semplice. Dopo aver messo tutto nelle due tables, e dopo aver salvato il database è il momento di far funzionare questo sistema. Mettiamoci a cercare, dentro books_index, un libro che ha al suo interno la parola “trap”:

MariaDB [books]> SELECT * FROM books_index WHERE title LIKE '%trap' ;
+-----------------------+--------------+-----------+---------------+------+
| title                 | author       | publisher | isbn          | year |
+-----------------------+--------------+-----------+---------------+------+
| the intelligence trap | david robson | hodder    | 9781473669857 | 2020 |
+-----------------------+--------------+-----------+---------------+------+
1 row in set (0.000 sec)

Bene, questo libro esiste e si chiama “the intelligence trap”. Il suo isbn e’ noto e, come avete notato, abbiamo inserito quel campo in entrambe le tables. Ora facendo la ricerca per isbn dentro books_position:

MariaDB [books]> SELECT * FROM books_position WHERE isbn = "9781473669857";
+-----------+----------+---------------+------+
| bookshelf | position | isbn          | year |
+-----------+----------+---------------+------+
| 1         | a        | 9781473669857 | 2020 |
+-----------+----------+---------------+------+
1 row in set (0.000 sec)

Ergo, il libro è posizionato nella prima libreria da sinistra (1), nel primo scaffale dall’alto (a). Comodo no? E poi… non dite che l’informatica non è utile…

A rivederci in un prossimo futuro (forse)!
jolek78

>> Indice <<
Puntata 32 < >

Il logo “Tux Linux” e’ stato realizzato e distribuito dall’artista deiby-ybied su Deviantart in licenza Creative Commons BY-NC-SA 3.0

jolek78 on Email
jolek78
Un tizio che pensava di essere uno scienziato. Si ritrovò divulgatore scientifico. Poi si addormentò su un aereo e si risvegliò informatico. Ma era sempre lui.

2 commenti

  • Andrea Ettore BERNAGOZZI

    Grazie del lavoro, per davvero, e buon tè!

  • Peccato.
    Adesso che avrai più tempo libero la domenica mattina, puoi indagare su un particolare tè verde, proveniente dalla foresta Lao, non lontano da Phonsavan, le cui piante hanno 3-4 secoli. È considerati tra i migliori al mondo.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *