- Создание пользователей MySQL/MariaDB и предоставление прав доступа
- Создание пользователя и выдача прав
- 1. С помощью команды GRANT.
- 2. С помощью команды CREATE USER.
- Посмотреть существующих пользователей и их привилегии
- Смена пароля
- MySQL
- MariaDB
- Смена пароля пользователю root после установки
- MySQL mysqladmin -u root password
- MySQL 8 и выше
- Сброс пароля для root
- Другие примеры
- 1. Особые права
- 2. Удаленное подключение
- 3. Права на резервное копирование
- 4. Права доступа к определенной таблице
- 5. Удаление пользователя
- 6. Права на создание других пользователей
- Возможные ошибки
- Linux mysql create users
Создание пользователей MySQL/MariaDB и предоставление прав доступа
Учетные записи в СУБД MySQL/MariaDB представлены в виде связки @ . Это может вызвать путаницу, поэтому необходимо быть внимательнее, например, учетные записи root@localhost и root@192.168.0.15 — разные.
Создание пользователя и выдача прав
Рассмотрим два варианта создания учетных записей в СУБД MySQL/MariaDB.
1. С помощью команды GRANT.
Данный метод позволяет одной командой сразу и создать пользователя, и дать ему права. Но, начиная с MySQL 8, она возвращает ошибку — разработчики запретили ее использование и сначала требуется создать пользователя (с помощью CREATE USER).
> GRANT ON TO [IDENTIFIED BY ] ;
Например, эта команда предоставляет права доступа пользователю и, если его не существует, создает его:
> GRANT ALL PRIVILEGES ON *.* TO ‘dbuser’@’localhost’ IDENTIFIED BY ‘password’ WITH GRANT OPTION;
ALL PRIVILEGES: предоставляет полные права на использование данных.
*.* : права предоставляются на все базы и все таблицы.
dbuser: имя учетной записи.
localhost: доступ для учетной записи будет предоставлен только с локального компьютера.
password: пароль, который будет задан пользователю.
WITH GRANT OPTION: будут предоставлены дополнительные права на изменение структуры баз и таблиц.
2. С помощью команды CREATE USER.
Данный метод является универсальным. Он позволяет создать пользователя в системе без каких либо прав. После права назначаются командой GRANT.
Пример создания учетной записи:
> CREATE USER ‘dbuser’@’localhost’ IDENTIFIED BY ‘password’;
После можно задать права командой:
> GRANT ALL PRIVILEGES ON *.* TO ‘dbuser’@’localhost’;
Посмотреть существующих пользователей и их привилегии
> SELECT user, host FROM mysql.user;
Список привилегий (для кажого пользователя смотряться отдельно):
> SHOW GRANTS FOR ‘root’@’localhost’;
* где ‘root’@’localhost’ — учетная запись, для которой смотрим привилегии; если упустить FOR, команда выдаст результат для пользователя, под которым выполнено подключение к СУБД.
Смена пароля
Команды отличаются в зависимости от версии СУБД.
MySQL
Версия 5.7.6 и более современная:
> ALTER USER ‘root’@’localhost’ IDENTIFIED BY ‘New_Password’;
Версия 5.7.5 и древнее:
> SET PASSWORD FOR ‘root’@’localhost’ = PASSWORD(‘New_Password’);
* посмотреть версию СУБД можно командой mysql -V.
MariaDB
В MariaDB команда для смены пароля одна, независимо от версии:
> SET PASSWORD FOR ‘root’@’localhost’ = PASSWORD(‘New_Password’);
* в данном примере будет задан пароль New_Password для пользователя root.
Смена пароля пользователю root после установки
Для старых версий СУБД и новых процедуры различаются.
MySQL mysqladmin -u root password
Для смены пароля root необходимо выполнить команду в оболочке mysql по инструкции, описанной выше.
MySQL 8 и выше
Пароль создается автоматически при установке системы. Его можно посмотреть командой:
grep ‘password’ /var/log/mysqld.log
Мы увидим что-то на подобие:
2021-08-16T20:14:13.173577Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: oi25?wznro%W
* где oi25?wznro%W — пароль для пользователя root.
Заходим в оболочку sql с помощью данного пароля:
Сброс пароля для root
При необходимости, мы можем сбросить пароль для суперпользователя mysql. Для этого необходимо запустить сервер баз данных в безопасном режиме и ввести команду на смену пароля.
Для начала необходимо остановить сервис:
systemctl stop mysql
systemctl stop mariadb
Создаем каталог /var/run/mysqld и зададим для него нужные права:
mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld
* в некоторых системах данного каталога может не быть, однако, для безопасного режима mysql он необходим.
Запускаем в безопасном режиме СУБД:
Запускаем оболочку sql — система не потребует пароль:
Выполняем запрос FLUSH PRIVILEGES:
Выходим из оболочки:
Уничтожаем процесс, который запустили ранее:
После, запускаем mysql в нормальном режиме:
systemctl start mysql
systemctl start mariadb
Другие примеры
Рассмотрим часто встречаемые операции по работе с пользователями сервера баз данных.
1. Особые права
Предоставление особых прав пользователю:
> GRANT SELECT, UPDATE ON base1.* TO ‘dbuser’@’localhost’ IDENTIFIED BY ‘password’;
* права на выборку и обновление данных во всех таблицах базы base1 для пользователя dbuser
** список всех возможных прав: all privileges, alter, create, create temporary tables, delete, drop, execute, file, index, insert, lock tables, process, references, reload, replication client, replication slave, select, show databases, shutdown, super, update, usage
2. Удаленное подключение
Разрешение на удаленное подключение и использование базы MySQL:
> GRANT ALL PRIVILEGES ON *.* TO ‘dbuser’@’192.168.0.55’ IDENTIFIED BY ‘password’;
* предоставит права пользователю dbuser, который будет подключаться с компьютера с IP-адресом 192.168.0.55.
3. Права на резервное копирование
Создание учетной записи MySQL с правами создания резервных копий:
> GRANT SELECT, SHOW VIEW, RELOAD, REPLICATION CLIENT, EVENT, TRIGGER, LOCK TABLES ON *.* TO ‘backup’@’localhost’ IDENTIFIED BY ‘backup’;
4. Права доступа к определенной таблице
По сути, это такое же предоставление прав, но с указанием конкретной таблицы после базы:
> GRANT ALL PRIVILEGES ON base1.table1 TO ‘dbuser’@’localhost’ IDENTIFIED BY ‘password’;
* в данном примере предоставлены все права на таблицу table1 в базе base1.
5. Удаление пользователя
Нам может также понадобиться удалить ранее созданного пользователя. Это делается в два этапа:
> REVOKE ALL PRIVILEGES, GRANT OPTION FROM ‘dbuser’@’localhost’;
> DROP USER ‘dbuser’@’localhost’;
* в данном примере мы первой командой отняли все права у пользователя dbuser (localhost) и второй — удалили его.
6. Права на создание других пользователей
Чтобы наш пользователь мог создавать других пользоватлей, задаем права:
GRANT CREATE USER ON *.* TO ‘creator’@’localhost’;
* в данном примере мы даем права учетной записи creator, которая может подключаться к серверу с локального хоста.
Если нужно, чтобы из под данной учетной записи можно было также назначать права, добавим:
GRANT CREATE USER ON *.* TO ‘creator’@’localhost’ WITH GRANT OPTION;
* обратите внимание, что мы просто добавили WITH GRANT OPTION.
Возможные ошибки
1. ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
Причина: в новых версиях по умолчанию активированы политики на проверку сложности пароля. Их список можно посмотреть командой:
> SHOW VARIABLES LIKE ‘validate_password%’;
Вывод команды будет, примерно, следующим:
+—————————————+———+
| Variable_name | Value |
+—————————————+———+
| validate_password_check_user_name | OFF |
| validate_password_dictionary_file | |
| validate_password_length | 8 |
| validate_password_mixed_case_count | 1 |
| validate_password_number_count | 1 |
| validate_password_policy | MEDIUM |
| validate_password_special_char_count | 1 |
+—————————————+———+
- validate_password_check_user_name — пароль не должен совпадать с именем пользователя.
- validate_password_dictionary_file — использовать специальный файл со словарем запрещенных паролей.
- validate_password_length — минимальная длина пароля.
- validate_password_mixed_case_count — сколько, как минимум, должно быть символов в малой и большой раскладках.
- validate_password_number_count — какое минимальное количество цифр использовать в пароле.
- validate_password_policy — позволяет задать определенный набор правил. Доступны значения LOW (или 0), MEDIUM (1), STRONG (2).
- validate_password_special_char_count — минимальное количество специальных символов (например, # или !).
- Привести пароль в соответствие требованиям политик.
- Отключить политику, которая не позволяет использовать желаемый пароль. Например, чтобы отключить требование использовать цифры вводим:
> SET GLOBAL validate_password_number_count = 0;
2. ERROR 1728 (HY000): Cannot load from mysql.tables_priv. The table is probably corrupted
Причина: система считает, что таблица tables_priv в базе mysql неисправна.
Решение: чаще всего, ошибка возникает при переносе баз с одного сервера в другой. Если версии СУБД разные, таблица tables_priv может работать со сбоями. Для исправления необходимо выполнить команду mysql_upgrade — она проверяет все таблицы на совместимость с текущей версией MySQL/MariaDB и вносит исправления. Применение команды:
Источник
Linux mysql create users
The CREATE USER statement creates new MySQL accounts. An error occurs if you try to create an account that already exists.
To use CREATE USER , you must have the global CREATE USER privilege, or the INSERT privilege for the mysql system database. When the read_only system variable is enabled, CREATE USER additionally requires the SUPER privilege.
Under some circumstances, CREATE USER may be recorded in server logs or on the client side in a history file such as
/.mysql_history , which means that cleartext passwords may be read by anyone having read access to that information. For information about the conditions under which this occurs for the server logs and how to control it, see Section 6.1.2.3, “Passwords and Logging”. For similar information about client-side logging, see Section 4.5.1.3, “mysql Client Logging”.
For each account, CREATE USER creates a new row in the mysql.user system table with no privileges and assigns the account an authentication plugin. Depending on the syntax used, CREATE USER may also assign the account a password.
An account when first created has no privileges. To assign privileges, use the GRANT statement.
Each user value naming an account may be followed by an optional auth_option value that specifies how authentication occurs for clients that use the account. This part of CREATE USER syntax is shared with GRANT , so the description here applies to GRANT as well.
Each account name uses the format described in Section 6.2.4, “Specifying Account Names”. For example:
The host name part of the account name, if omitted, defaults to ‘%’ .
The server assigns an authentication plugin and password to each account as follows, depending on whether the user specification clause includes IDENTIFIED BY or IDENTIFIED WITH to specify authentication information:
With IDENTIFIED BY , the server assigns the plugin implicitly. The ‘ auth_string ‘ value is cleartext and is passed to the plugin for possible hashing. The result returned by the plugin is stored as the password. A plugin may use the value as specified, in which case no hashing occurs. If the optional PASSWORD keyword is given, the behavior is the same except that if the plugin requires a hashed string, the string is assumed to be already hashed in the format the plugin requires, and is stored as is as the password.
With IDENTIFIED WITH , the server assigns the specified plugin and the account has no password. If the optional AS ‘ auth_string ‘ clause is given, the string is stored as is as the password. If the plugin requires a hashed string, the string is assumed to be already hashed in the format the plugin requires.
With neither IDENTIFIED BY nor IDENTIFIED WITH , the server assigns the plugin implicitly and the account has no password.
If the account has no password, the password information in the account row in the mysql.user table remains empty, which is insecure. To set the password, use SET PASSWORD . See Section 13.7.1.7, “SET PASSWORD Statement”.
For implicit plugin assignment, the default plugin becomes the value of the plugin column in the account’s mysql.user system table row. The default plugin is mysql_native_password unless the —default-authentication-plugin option is set otherwise at server startup.
For client connections that use a given account, the server invokes the authentication plugin assigned to the account and the client must provide credentials as required by the authentication method that the plugin implements. If the server cannot find the plugin, either at account-creation time or connect time, an error occurs.
If an account’s mysql.user table row has a nonempty plugin column:
The server authenticates client connection attempts using the named plugin.
Changes to the account password using SET PASSWORD with PASSWORD() must be made with the old_passwords system variable set to the value required by the authentication plugin, so that PASSWORD() uses the appropriate password hashing method. If the plugin is mysql_old_password , the password can also be changed using SET PASSWORD with OLD_PASSWORD() , which uses pre-4.1 password hashing regardless of the value of old_passwords .
If an account’s mysql.user table row has an empty plugin column:
The server authenticates client connection attempts using the mysql_native_password or mysql_old_password authentication plugin, depending on the hash format of the password stored in the Password column.
Changes to the account password using SET PASSWORD can be made with PASSWORD() , with old_passwords set to 0 or 1 for 4.1 or pre-4.1 password hashing, respectively, or with OLD_PASSWORD() , which uses pre-4.1 password hashing regardless of the value of old_passwords .
To specify an authentication plugin for an account, use IDENTIFIED WITH auth_plugin . The plugin name can be a quoted string literal or an unquoted name. ‘ auth_string ‘ is an optional quoted string literal to pass to the plugin. The plugin interprets the meaning of the string, so its format is plugin specific and it is stored in the authentication_string column as given. (This value is meaningful only for plugins that use that column.) Consult the documentation for a given plugin for information about the authentication string values it accepts, if any.
The server assigns the given authentication plugin to the account but no password. Clients must provide no password when they connect. However, an account with no password is insecure. To ensure that an account uses a specific authentication plugin and has a password with the corresponding hash format, specify the plugin explicitly with IDENTIFIED WITH , then use SET PASSWORD to set the password:
Changes to the account password using SET PASSWORD with PASSWORD() must be made with the old_passwords system variable set to the value required by the account’s authentication plugin, so that PASSWORD() uses the appropriate password hashing method. Therefore, to use the sha256_password or mysql_old_password plugin instead, name that plugin in the CREATE USER statement and set old_passwords to 2 or 1, respectively, before using SET PASSWORD . (Use of mysql_old_password is not recommended. It is deprecated; expect support for it to removed in a future MySQL release.)
To specify a password for an account at account-creation time, use IDENTIFIED BY with the literal cleartext password value:
The server assigns an authentication plugin to the account implicitly, as described previously, and assigns the given password. Clients must provide the given password when they connect.
If the implicitly assigned plugin is mysql_native_password , the old_passwords system variable must be set to 0. Otherwise, CREATE USER does not hash the password in the format required by the plugin and an error occurs:
To avoid specifying the cleartext password if you know its hash value (the value that PASSWORD() would return for the password), specify the hash value preceded by the keyword PASSWORD :
The server assigns an authentication plugin to the account implicitly, as described previously, and assigns the given password. The password hash must be in the format required by the assigned plugin. Clients must provide the password when they connect.
To enable the user to connect with no password, include no IDENTIFIED BY clause:
The server assigns an authentication plugin to the account implicitly, as described previously, but no password. Clients must provide no password when they connect. However, an account with no password is insecure. To avoid this, use SET PASSWORD to set the account password.
As mentioned previously, implicit plugin assignment depends on the default authentication plugin. Permitted values of —default-authentication-plugin are mysql_native_plugin and sha256_password , but not mysql_old_password . This means it is not possible to set the default plugin so as to be able to create an account that uses mysql_old_password with CREATE USER . IDENTIFIED BY syntax. To create an account that uses mysql_old_password , use CREATE USER . IDENTIFIED WITH to name the plugin explicitly, then set the password:
However, the preceding procedure is not recommended because mysql_old_password is deprecated.
For additional information about setting passwords and authentication plugins, see Section 6.2.9, “Assigning Account Passwords”, and Section 6.2.11, “Pluggable Authentication”.
Источник