MySQL – How to Know When a MySQL User Was Last Authenticated

MySQL

We have some distributed servers that connect to the same MySQL server. We need to have a log with the date/time when it was the last time a MySQL User logged in. How could I do that?

Best Answer

You can do it using several ways: Create general log and store there the info like in this answer:

You would probably want to use the general query log.

The general query log is a general record of what mysqld is doing. The server writes information to this log when clients connect or disconnect, and it logs each SQL statement received from clients.

One important thing with logging for security is that an attacker cannot access the log to erase traces of their presence, so consider append-only files.

Or create a table in to the database and store there every login via stored procedure as explained in this web page

-- SET GLOBAL init_connect="";
SET GLOBAL init_connect="CALL tracking.login_trigger()";


DELIMITER //

CREATE PROCEDURE login_trigger()
SQL SECURITY DEFINER
BEGIN
  INSERT INTO login_tracking (user, host, ts)
  VALUES (SUBSTR(USER(), 1, instr(USER(), '@')-1), substr(USER(), instr(USER(), '@')+1), NOW())
  ON DUPLICATE KEY UPDATE ts = NOW();
END;

//
Related Topic