Mysql как найти пользователя

В этом учебном пособии вы узнаете, как найти всех пользователей, которые созданы в базе данных MySQL.

В MySQL есть системная таблица mysql.user. Вы можете запустить запрос к этой системной таблице, который возвращает всех пользователей, которые были созданы в MySQL, а также информацию об этих Users.

Чтобы загрузить всех пользователей в MySQL, вы можете выполнить следующий оператор SQL:

SELECT User

FROM mysql.user;

Таблица mysql.user содержит следующие столбцы:

Столбец Описание
Host Хост пользователя (то есть: localhost,% и т. д.)
User Имя пользователя (например: root, admin и т. д.)
Password Пароль хранится как хешированное значение
Select_priv Y или N (показывает, была ли привилегия назначена пользователю)
Insert_priv Y или N (показывает, была ли привилегия назначена пользователю)
Update_priv Y или N (показывает, была ли привилегия назначена пользователю)
Delete_priv Y или N (показывает, была ли привилегия назначена пользователю)
Create_priv Y или N (показывает, была ли привилегия назначена пользователю)
Drop_priv Y или N (показывает, была ли привилегия назначена пользователю)
Reload_priv Y или N (показывает, была ли привилегия назначена пользователю)
Shutdown_priv Y или N (показывает, была ли привилегия назначена пользователю)
Process_priv Y или N (показывает, была ли привилегия назначена пользователю)
File_priv Y или N (показывает, была ли привилегия назначена пользователю)
Grant_priv Y или N (показывает, была ли привилегия назначена пользователю)
References_priv Y или N (показывает, была ли привилегия назначена пользователю)
Index_priv Y или N (показывает, была ли привилегия назначена пользователю)
Alter_priv Y или N (показывает, была ли привилегия назначена пользователю)
Show_db_priv Y или N (показывает, была ли привилегия назначена пользователю)
Super_priv Y или N (показывает, была ли привилегия назначена пользователю)
Create_tmp_table_priv Y или N (показывает, была ли привилегия назначена пользователю)
Lock_tables_priv Y или N (показывает, была ли привилегия назначена пользователю)
Execute_priv Y или N (показывает, была ли привилегия назначена пользователю)
Repl_slave_priv Y или N (показывает, была ли привилегия назначена пользователю)
Repl_client_priv Y или N (показывает, была ли привилегия назначена пользователю)
Create_view_priv Y или N (показывает, была ли привилегия назначена пользователю)
Show_view_priv Y или N (показывает, была ли привилегия назначена пользователю)
Create_routine_priv Y или N (показывает, была ли привилегия назначена пользователю)
Alter_routine_priv Y или N (показывает, была ли привилегия назначена пользователю)
Create_user_priv Y или N (показывает, была ли привилегия назначена пользователю)
Event_priv Y или N (показывает, была ли привилегия назначена пользователю)
Trigger_priv Y или N (показывает, была ли привилегия назначена пользователю)
Create_tablespace Y или N (показывает, была ли привилегия назначена пользователю)
ssl_type Столбец безопасности
ssl_cipher Столбец безопасности, сохраненный как [BLOB]
x509_issuer Столбец безопасности, сохраненный как [BLOB]
x509_subject Столбец безопасности, сохраненный как [BLOB]
max_questions Столбец ресурсов
max_updates Столбец ресурсов
max_connections Столбец ресурсов
max_user_connections Столбец ресурсов
plugin Столбец безопасности
authentication_string Столбец безопасности

I’m using the MySQL command-line utility and can navigate through a database. Now I need to see a list of user accounts. How can I do this?

I’m using MySQL version 5.4.1.

Peter Mortensen's user avatar

asked Jul 16, 2009 at 3:23

burntsugar's user avatar

2

Use this query:

SELECT User FROM mysql.user;

Which will output a table like this:

+-------+
| User  |
+-------+
| root  |
+-------+
| user2 |
+-------+

As Matthew Scharley points out in the comments on this answer, you can group by the User column if you’d only like to see unique usernames.

8

I find this format the most useful as it includes the host field which is important in MySQL to distinguish between user records.

select User,Host from mysql.user;

answered Jul 6, 2012 at 18:21

spkane's user avatar

spkanespkane

6,0872 gold badges18 silver badges18 bronze badges

2

A user account comprises the username and the host level access.

Therefore, this is the query that gives all user accounts

SELECT CONCAT(QUOTE(user),'@',QUOTE(host)) UserAccount FROM mysql.user;

answered Sep 29, 2013 at 22:29

RolandoMySQLDBA's user avatar

RolandoMySQLDBARolandoMySQLDBA

43.7k16 gold badges91 silver badges132 bronze badges

3

To avoid repetitions of users when they connect from a different origin:

select distinct User from mysql.user;

Peter Mortensen's user avatar

answered Sep 29, 2013 at 22:01

Nicolas Manzini's user avatar

Nicolas ManziniNicolas Manzini

8,3306 gold badges63 silver badges81 bronze badges

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:

SELECT User, Host FROM mysql.user;

+------------------+-----------+
| User             | Host      |
+------------------+-----------+
| root             | localhost |
| root             | demohost  |
| root             | 127.0.0.1 |
| debian-sys-maint | localhost |
|                  | %         |
+------------------+-----------+

answered Oct 26, 2016 at 10:33

VPK's user avatar

VPKVPK

3,0101 gold badge28 silver badges35 bronze badges

If you are referring to the actual MySQL users, try:

select User from mysql.user;

answered Jul 16, 2009 at 3:28

Jesse Vogt's user avatar

Jesse VogtJesse Vogt

16.1k16 gold badges59 silver badges72 bronze badges

SELECT * FROM mysql.user;

It’s a big table so you might want to be more selective on what fields you choose.

answered Jul 16, 2009 at 3:29

Etzeitet's user avatar

EtzeitetEtzeitet

1,9852 gold badges18 silver badges22 bronze badges

2

Log in to MySQL as root and type the following query:

select User from mysql.user;

+------+
| User |
+------+
| amon |
| root |
| root |
+------+

Peter Mortensen's user avatar

answered Mar 4, 2014 at 6:46

sandip divekar's user avatar

sandip divekarsandip divekar

1,6185 gold badges22 silver badges40 bronze badges

2

The mysql.db table is possibly more important in determining user rights. I think an entry in it is created if you mention a table in the GRANT command. In my case the mysql.users table showed no permissions for a user when it obviously was able to connect and select, etc.

mysql> select * from mysql.db;
mysql> select * from db;
+---------------+-----------------+--------+-------------+-------------+-------------+--------
| Host          | Db              | User   | Select_priv | Insert_priv | Update_priv | Del...

Palec's user avatar

Palec

12.5k8 gold badges66 silver badges137 bronze badges

answered Dec 27, 2014 at 20:09

Brad Dre's user avatar

Brad DreBrad Dre

3,4152 gold badges19 silver badges21 bronze badges

1

I use this to sort the users, so the permitted hosts are more easy to spot:

mysql> SELECT User,Host FROM mysql.user ORDER BY User,Host;

answered Nov 2, 2016 at 19:01

Tobias Holm's user avatar

Tobias HolmTobias Holm

2512 silver badges6 bronze badges

Peter and Jesse are correct, but just make sure you first select the «mysql» database.

use mysql;
select User from mysql.user;

That should do your trick.

Peter Mortensen's user avatar

answered May 5, 2012 at 12:19

Armin Nehzat's user avatar

3

This displays the list of unique users:

SELECT DISTINCT User FROM mysql.user;

Peter Mortensen's user avatar

answered Sep 9, 2016 at 11:12

Nikhil Chavda's user avatar

$>  mysql -u root -p -e 'Select user from mysql.user' > allUsersOnDatabase.txt

Executing this command on a Linux command line prompt will first ask for the password of MySQL root user. On providing the correct password it will print all the database users to the text file.

Peter Mortensen's user avatar

answered Feb 21, 2017 at 10:04

Dr. Mian's user avatar

Dr. MianDr. Mian

3,25410 gold badges44 silver badges69 bronze badges

I found his one more useful as it provides additional information about DML and DDL privileges

SELECT user, Select_priv, Insert_priv , Update_priv, Delete_priv, 
       Create_priv, Drop_priv, Shutdown_priv, Create_user_priv 
FROM mysql.user;

Community's user avatar

answered Aug 28, 2017 at 23:10

Alper t. Turker's user avatar

Alper t. TurkerAlper t. Turker

34k9 gold badges82 silver badges115 bronze badges

1

SELECT User FROM mysql.user;

Use the above query to get the MySQL users.

Peter Mortensen's user avatar

answered Feb 15, 2019 at 5:19

Arun Karnawat's user avatar

To see your users, it would be to use the mysql database.

USE mysql;

And then make the select.

SELECT user,host FROM user;

Another option is to put the BD.Table.

For example :

SELECT user,host FROM mysql.user;

answered Mar 27, 2022 at 16:59

Javier G.Raya's user avatar

Javier G.RayaJavier G.Raya

2301 gold badge3 silver badges15 bronze badges

Summary: this tutorial shows you how to list users in a MySQL database.

Are you looking for the MySQL SHOW USERS command? Unfortunately, MySQL does not have the SHOW USERS command like SHOW DATABASES, SHOW TABLES, etc., therefore to list all users in a MySQL database server, you use the following query:

SELECT 
   user 
FROM 
   mysql.user;
Code language: SQL (Structured Query Language) (sql)

In this statement, we queried user data from the user table of the mysql database.

To execute this query, you must log in to the MySQL database server as an administrator.

>mysql -u root -p
Enter password: ***********
mysql> use mysql;
Database changed
mysql> SELECT user FROM user;
Code language: SQL (Structured Query Language) (sql)

The following shows the output of the query above:

+-----------+
| user      |
+-----------+
| mysql.sys |
| mysqlxsys |
| root      |
+-----------+
3 rows in set (0.00 sec)
Code language: SQL (Structured Query Language) (sql)

As you can see, we have three users in our local database.

To get more information on the user table, you can preview its columns using the following command:

DESC user;Code language: SQL (Structured Query Language) (sql)

For example, to show users and other information such as host, account locking, and password expiration status, you use the following query:

SELECT 
    user, 
    host, 
    account_locked, 
    password_expired
FROM
    user;
Code language: SQL (Structured Query Language) (sql)

Here is the output of the query.

MySQL SHOW USERS

Show current user

To get the information on the  current user, you use the user() function as shown in the following statement:

mysql> SELECT user();
+-----------------+
| user()          |
+-----------------+
| local@localhost |
+-----------------+
1 row in set (0.00 sec)
Code language: SQL (Structured Query Language) (sql)

Or you use the current_user() function:

mysql> SELECT current_user();
+----------------+
| current_user() |
+----------------+
| local@localhost |
+----------------+
1 row in set (0.00 sec)Code language: SQL (Structured Query Language) (sql)

In this case, the current user is local@localhost.

Show current logged users

To list all users that are currently logged in the MySQL database server, you execute the following statement:

SELECT 
    user, 
    host, 
    db, 
    command 
FROM 
    information_schema.processlist;

+-------+-----------------+---------------+---------+
| user  | host            | db            | command |
+-------+-----------------+---------------+---------+
| local | localhost:50591 | classicmodels | Sleep   |
| root  | localhost:50557 | NULL          | Query   |
+-------+-----------------+---------------+---------+
2 rows in set (0.00 sec)
Code language: SQL (Structured Query Language) (sql)

As use can see, there are two users that are currently logged in the MySQL database, one is executing a query while the other is “sleep”.

In this tutorial, you have learned how to list all users in a MySQL database server by querying data from the user table in the mysql database.

Was this tutorial helpful?

In this article i will show how to list MySQL users, their passwords and granted privileges from the command-line prompt.

MySQL account consists of two components: user and host.

This allows the same user to use different MySQL accounts with different privileges, depending on which host they are connecting from.

In the Host field, besides of the common IP addresses and host names, you can see the % sign, that is a wildcard character that means “any” host.

Important Notice: The % character does not include the localhost, as the localhost means a connection over a UNIX socket instead of a standard TCP/IP.

Show all MySQL users:

mysql> SELECT user FROM mysql.user;

List only unique user names:

mysql> SELECT DISTINCT user FROM mysql.user;

Show MySQL users and hosts they are allowed to connect from:

mysql> SELECT user,host FROM mysql.user;

Show MySQL users, their passwords and hosts:

mysql> SELECT user,host,password FROM mysql.user;

in MySQL 5.7 and higher:

mysql> SELECT host,user,authentication_string FROM mysql.user;

Cool Tip: Need to change MySQL user password? This can be easily done from the command-line prompt! Read more →

Show User Privileges In MySQL

In MySQL, you can use the SHOW GRANTS command to show privileges granted to a user.

Without any additional parameters, the SHOW GRANTS command lists the privileges granted to the current user account with which you have connected to the server.

The SHOW GRANTS requires the SELECT privilege for the mysql database, except to see the privileges for the current user, so if you have such privilege you can also list the privileges granted to the other MySQL users.

Cool Tip: Create a MySQL database and GRANT ALL PRIVILEGES on it to a user! Simple and clear MySQL tutorial with good examples! Read more →

Show privileges granted to the current MySQL user:

mysql> SHOW GRANTS;

Show privileges granted to the MySQL user (if you don’t specify a host for the user name, MySQL assumes % as the host):

mysql> SHOW GRANTS FOR 'user_name';

Show privileges granted to a particular MySQL user account from a given host:

mysql> SHOW GRANTS FOR 'user_name'@'host';

– e.g. –

mysql> SHOW GRANTS FOR 'root'@'localhost';
mysql> SHOW GRANTS FOR 'root'@'%';
mysql> SHOW GRANTS FOR 'admin'@'192.168.0.1';

Was it useful? Share this post with the world!

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

В данной статье будет рассмотрено как посмотреть список пользователей MySQL присутствующих на сервере в операционной системе Ubuntu 20.04.

Как и в любой другой СУБД в MySQL можно посмотреть список всех доступных пользователей.

Шаг 1. Вход в консоль MySQL

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

mysql -u alex -p

3DILRfg4f8EzblbbZvVGLMAAAAASUVORK5CYII=

Если вход в оболочку осуществляется впервые, то необходимо войти под пользователем root. Далее отобразится фраза с предложением ввести пароль пользователя. На этом этапе необходимо ввести пароль именно пользователя БД, а не пользователя, присутствующего в операционной системе. В качестве безопасности пароль не отображается при вводе в терминале.

Шаг 2. Просмотр доступных полей

Пользователи в MySQL хранятся в базе данных под названием mysql в таблице user. Для того чтобы получить список пользователей MySQL нужно вывести содержимое этой таблицы. Однако из-за большого числа столбцов, вывод команды не отображается корректно. В этом случае вывести список пользователей в читаемом формате можно задав необходимые столбцы.

Таблица user имеет 51 столбец. Выполнив SQL запрос представленный ниже, можно получить наименования и описания всех столбов в этой таблице.

DESCRIBE mysql.user;

x0FZ0VQIC1AAAAAElFTkSuQmCC

В данном случае для просмотра всех доступных пользователей можно вывести всего лишь один столбец — user при помощи SQL запроса:

SELECT user FROM mysql.user;

f9g8hhekoo07gAAAABJRU5ErkJggg==

Как посмотреть текущего пользователя

Чтобы узнать из-под какого пользователя запущена текущая сессия в СУБД необходимо выполнить следующий SQL запрос:

SELECT user();

IE2EAAAAASUVORK5CYII=

Также можно выполнить специальную команду, присутствующую в оболочке MySQL — status. Данная команда отображает такую информацию как версию сервера MySQL, номер подключения, включен ли SSL, а также содержит параметр Current user — в котором отображается текущий пользователь. Вывод команды можно увидеть ниже:

status

vG3FopZ2ZpNwL92BE5j7JdQcnaNVqALZeSERh46iLj0MYJ12kk26XRLMTMGYe4hQIHTlw4pkJdQ9b0od6QZ1MIC+qISyJSFofvAw8huuqKjyFlPmO5aicg0CoYtF1VEAtnjMKCyNhUUxkI03Hd9f+38HDIOPHFsTRQAAAABJRU5ErkJggg==

Как посмотреть активных пользователей

Для вывода всех пользователей, которые подключены к СУБД в текущий момент необходимо выполнить следующий SQL запрос:

SELECT SUBSTRING_INDEX(host, ':', 1) AS host_short, GROUP_CONCAT(DISTINCT user) AS users, COUNT(*) AS threads FROM information_schema.processlist GROUP BY host_short ORDER BY COUNT(*), host_short;

sMht1yAB5R8HgYlJEdmLp2fkHdBiC0bbmmcGQzoyf8fuuVPLPQ57Y0AAAAASUVORK5CYII=

Выводы

В данной статье было рассмотрено как вывести список пользователей MySQL. Сделать это можно несколькими способами. Данная операция является одной из самых распространенных при администрировании сервера СУБД. Если у вас остались вопросы задавайте их в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Бывший системный администратор и DevOps инженер. Ныне работаю по направлению DevSecOps. Использую Linux более 5 лет. Помимо Linux интересую языком программирования Python, базами данных и языком SQL а также информационной безопасностью.

Понравилась статья? Поделить с друзьями:
  • Как найти музыку не знавший названия
  • Руки ветки как исправить
  • Как найти свои пресеты в лайтрум
  • Как исправить ошибку в упд прошлого периода
  • Как составить на бумаге свои мечты