Mysqld ��� ��� linux

Sergey Danielyan

Правильная установка и настройка MySQL в Linux

Эта статья, по замыслу, должна служить пошаговым руководством по корректной настройки MySQL сервера в Linux в общем и в CentOS в частности, начиная от подготовки системы и заканчивая настройкой прав пользователей.
В этот раз текста будет минимум — только команды.

Установка MySQL

Проверяем, установлен ли MySQL сервер

Если установлен, шаги по установке можете пропустить, хотя ознакомиться я все же советую с ними.

Существуют следующие основные пакеты связанные с mysql:

  • mysql — клиент mysql
  • mysql-server — сервер mysql
  • mysql-devel — для разработки и подключения библиотек и хидеров mysql
  • mysql-connector-java — JDBC коннектор (используется, например, в EJBCA)

sudo yum install mysql mysql-server mysql-devel mysql-connector-java

Теперь надо установить сервер mysql на запуск в определенные runlevel‘ы (2, 3 и 5):

Если кто забыл соответствие цифрового значения runlevel‘а символьному:

Стартуем демон mysql:

Настройка сервера

Теперь пора настроить сервер. Начнем с пользователей.

Вот состояние таблицы user до начала действий с ней:

mysql -u root
> use mysql
> select host,user from user;

5 rows in set (0.00 sec)
> quit

Как видете, безопасность на уровне плинтуса. Хорошо хоть, что анонимного пользователя нет.

Для настройки базовых вещей в сервере, запустим настройку сервера через mysql_secure_installation. На время этой установки, пароль будет security. Ваш же пароль, как понимаете, должен отличаться.

Запустится скрипт, с запросами на то или иное действие. Вот ответы:

Skip root password for root
Мы еще не устанавливали пароль для root, поэтому при запуске скрипта и запросе пароля для root , просто нажмите Enter .

Install new password for root: security
А вот тут можно установить пароль для root

Do remove an anonymous user
На вопрос о том, удалить ли анонимного пользователя, отвечаем да

Do not disallow remote connections
Не запрещаем коннект к нашему северу с удаленных серверов (если, конечно, эта опция вам нужна, в другом случае, запретите ее)

Do remove a test database
Тестовая база нам не нужна — удаляйте ее

Do reload the privileges
Перегрузим привилегии для их активации

Теперь для всех root пользователей установлен пароль.

Если в ходе этой конфигурации вы не установили пароль для root , можете сделать это так:

SET PASSWORD FOR ‘root’@’localhost’ = PASSWORD(‘security’);
SET PASSWORD FOR ‘root’@’localhost.localdomain’ = PASSWORD(‘security’);
SET PASSWORD FOR ‘root’@’127.0.0.1’ = PASSWORD(‘security’);

UPDATE mysql.user SET Password = PASSWORD(‘security’) WHERE user = ‘root’;

Если же вы не запускали конфигурацию через mysql_secure_installation или не хотите этого делать по каким-то другим причинам, следующие команды удалят any пользователей:

DROP USER »@’localhost’;
DROP USER »@’localhost.localdomain’;

Также, пароль для IPv6 localhost (@::1) можно установить таким образом:

Близится финал нашего действия. Осталось две вещи:

  • открыть порты для mysql:

sudo iptables -I INPUT -p tcp —dport 3306 -m state —state NEW,ESTABLISHED -j ACCEPT
sudo iptables -I OUTPUT -p tcp —sport 3306 -m state —state ESTABLISHED -j ACCEPT

выставить кодировку UTF-8 по-умолчанию — файл /etc/my.cnf :

[mysqld]
init_connect=‘SET collation_connection = utf8_unicode_ci’
character-set-server = utf8
collation-server = utf8_unicode_ci

[client]
default-character-set = utf8

Источник

Mysqld ��� ��� linux

Last updated on: 2019-12-20

Authored by: Jered Heeschen

MySQL is an open-source relational database that is free and widely used. It is a good choice if you know that you need a database but don’t know much about all the available options.

Читайте также:  Window run mac os

This article describes a basic installation of a MySQL database server on the Ubuntu operating system. You might need to install other packages to let applications use MySQL, like extensions for PHP. Check your application documentation for details.

Install MySQL

Install the MySQL server by using the Ubuntu operating system package manager:

The installer installs MySQL and all dependencies.

If the secure installation utility does not launch automatically after the installation completes, enter the following command:

This utility prompts you to define the mysql root password and other security-related options, including removing remote access to the root user and setting the root password.

Allow remote access

If you have iptables enabled and want to connect to the MySQL database from another machine, you must open a port in your server’s firewall (the default port is 3306). You don’t need to do this if the application that uses MySQL is running on the same server.

Run the following command to allow remote access to the mysql server:

Start the MySQL service

After the installation is complete, you can start the database service by running the following command. If the service is already started, a message informs you that the service is already running:

Launch at reboot

To ensure that the database server launches after a reboot, run the following command:

Configure interfaces

MySQL, by default is no longer bound to ( listening on ) any remotely accessible interfaces. Edit the “bind-address” directive in /etc/mysql/mysql.conf.d/mysqld.cnf:

Restart the mysql service.

Start the mysql shell

There is more than one way to work with a MySQL server, but this article focuses on the most basic and compatible approach, the mysql shell.

At the command prompt, run the following command to launch the mysql shell and enter it as the root user:

When you’re prompted for a password, enter the one that you set at installation time, or if you haven’t set one, press Enter to submit no password.

The following mysql shell prompt should appear:

Set the root password

If you logged in by entering a blank password, or if you want to change the root password that you set, you can create or change the password.

For versions earlier than MySQL 5.7, enter the following command in the mysql shell, replace password with your new password:

For version MySQL 5.7 and later, enter the following command in the mysql shell, replacing password with your new password:

To make the change take effect, reload the stored user information with the following command:

Note: We’re using all-caps for SQL commands. If you type those commands in lowercase, they’ll work. By convention, the commands are written in all-caps to make them stand out from field names and other data that’s being manipulated.

If you need to reset the root password later, see Reset a MySQL root password.

View users

MySQL stores the user information in its own database. The name of the database is mysql. Inside that database the user information is in a table, a dataset, named user. If you want to see what users are set up in the MySQL user table, run the following command:

The following list describes the parts of that command:

  • SELECT tells MySQL that you are asking for data.
  • User, Host, authentication_string tells MySQL what fields you want it to look in. Fields are categories for the data in a table. In this case, you are looking for the username, the host associated with the username, and the encrypted password entry.
  • FROM mysql.user » tells MySQL to get the data from the mysql database and the user table.
  • A semicolon (;) ends the command.
Читайте также:  Windows cmd exe error codes

Note: All SQL queries end in a semicolon. MySQL does not process a query until you type a semicolon.

User hosts

The following example is the output for the preceding query:

Users are associated with a host, specifically, the host from which they connect. The root user in this example is defined for localhost, for the IP address of localhost, and the hostname of the server. You usually need to set a user for only one host, the one from which you typically connect.

If you’re running your application on the same computer as the MySQL server, the host that it connects to by default is localhost. Any new users that you create must have localhost in their host field.

If your application connects remotely, the host entry that MySQL looks for is the IP address or DNS hostname of the remote computer (the one from which the client is coming).

Anonymous users

In the example output, one entry has a host value but no username or password. That’s an anonymous user. When a client connects with no username specified, it’s trying to connect as an anonymous user.

You usually don’t want any anonymous users, but some MySQL installations include one by default. If you see one, you should either delete the user (refer to the username with empty quotes, like ‘ ‘) or set a password for it.

Create a database

There is a difference between a database server and a database, even though those terms are often used interchangeably. MySQL is a database server, meaning it tracks databases and controls access to them. The database stores the data, and it is the database that applications are trying to access when they interact with MySQL.

Some applications create a database as part of their setup process, but others require you to create a database yourself and tell the application about it.

To create a database, log in to the mysql shell and run the following command, replacing demodb with the name of the database that you want to create:

After the database is created, you can verify its creation by running a query to list all databases. The following example shows the query and example output:

Add a database user

When applications connect to the database using the root user, they usually have more privileges than they need. You can add users that applications can use to connect to the new database. In the following example, a user named demouser is created.

To create a new user, run the following command in the mysql shell:

When you make changes to the user table in the mysql database, tell MySQL to read the changes by flushing the privileges, as follows:

Verify that the user was created by running a SELECT query again:

Grant database user permissions

Right after you create a new user, it has no privileges. The user can log in, but can’t be used to make any database changes.

Give the user full permissions for your new database by running the following command:

Flush the privileges to make the change official by running the following command:

To verify that those privileges are set, run the following command:

Читайте также:  Загрузочную флешку windows с помощью acronis

MySQL returns the commands needed to reproduce that user’s permissions if you were to rebuild the server. USAGE on \*.\* means the users gets no privileges on anything by default. That command is overridden by the second command, which is the grant you ran for the new database.

Summary

If you’re just creating a database and a user, you are done. The concepts covered here should give you a solid start from which to learn more.

Share this information:

©2020 Rackspace US, Inc.

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License

Источник

MySQL

Содержание

MySQL — свободная СУБД для малых и средних приложений. Входит в состав LAMP и XAMPP.

Версии MySQL в Ubuntu

Установка

MySQL есть в репозиториях Ubuntu. Он разбит на несколько пакетов.

Для того чтобы установить MySQL сервер выполните команду:

При установке конфигурационный скрипт запросит пароль для администратора (root) базы данных.

Для того чтобы установить консольный клиент MySQL выполните команду:

Для того чтобы установить модуль для работы с MySQL в PHP выполните команду:

Настройка

Конфигурация сервера MySQL содержится в файле /etc/mysql/my.cnf.

Доступ к серверу из сети

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

Кодировки

По-умолчанию в Ubuntu MySQL устанавливается с кодировкой latin1 . В этом можно убедиться посмотрев вывод запроса:

В связи с этим, даже используя при работе с сервером команду

и используя при создании таблиц

невозможно добиться полной поддержки кодировки utf8:

Кодировка по-умолчанию все равно останется latin1, что неудобно и может привести к ошибкам.

Чтобы сервер сразу загружался с нужной кодировкой, необходимо отредактировать файл /etc/mysql/my.cnf:

В секцию [mysqld] добавьте следующие строки:

Так же желательно установить кодировку для клиента и mysqldump. Для этого в секциях [client] и [mysqldump] необходимо добавить строчку:

Перезагрузите сервер MySQL:

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

Администрирование

Установка root пароля

Восстановление забытого пароля для root’a

Схожая проблема возникает если не задать пароль при установке MySQL, в этом случае mysql использует плагин unix-socket.

Запустите mysqld с параметрами —skip-grant-tables —user=root :

Если команда не сработает, добавьте строку « skip-grant-tables » в секцию « [mysqld] » файла /etc/mysql/mysql.conf.d/mysqld.cnf . Затем выполните sudo service mysql restart . После выполнения операций удалите эту строку.

Подключитесь к MySQL-серверу командой:

Обновите пароль для root’a:

Для MySQL версий mysqldump . Основные ее параметры приведены в таблице:

Параметр Описание Пример
-u Пользователь, от лица которого будет производится дамп баз данных. -uroot
-p

Пароль пользователя. Пароль необязательно указывать, достаточно упомянуть этот параметр для того, чтобы утилита знала что подключение требует пароля. -ppassword
-p -h Хост, на котором расположена база данных. -h127.0.0.1 -A Создать бекап всех баз данных. -A -B Базы данных, которые нужно забэкапить. -B db1 db2 db3 —tables

Таблицы, которые нужно забэкапить. Перекрывает действие ключа -B —tables db1.table1 db1.table2 db2.table3 -d Создать бекап структуры таблиц. Содержимое таблиц скопировано не будет. -d —skip-extended-insert Не использовать многострочные INSERT-записи при создании дампа. —skip-extended-insert -w’where_clause ‘ Создавать дамп только тех строк, которые попадают под условие. -w’Id > 10 AND Id ‘

Отключение и включение автозагрузки сервиса

Начиная с версии Ubuntu 15.04 отключение и включение сервисов возможно одной командой, без редактирования конфигов. В примерах команд ниже слово «SERVICE» следует заменить на «mysql».

Узнать стоит ли сервис в автозагрузке:

Убрать сервис из автозагрузки в Ubuntu-16.04:

Добавить сервис в автозагрузку в Ubuntu-16.04:

MySQL Workbench

MySQL Workbench – инструмент для визуального проектирования баз данных. MySQL Workbench существует в двух вариантах:

Источник

Оцените статью