1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu MySQL Administrator’s Bible- P11 doc

50 365 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Backups and Recovery
Chuyên ngành Database Administration
Thể loại Chương
Định dạng
Số trang 50
Dung lượng 1,33 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

To move a database from one machine to another, run the following from the machine currently holding the database the target host: shell> mysqldump --databases sakila | mysql -h destinat

Trang 1

R1Soft is that it provides what it calls near-Continuous Online Backups It does this by ing backups very frequently (every 15 minutes or less) This provides for a very small window oftime that data can be lost In addition, the R1Soft software also provides for complete bare-metalrestore for MySQL servers.

perform-The homepage of R1Soft is:www.r1soft.com

Copying Databases to Another Machine

You can copy the.frm,.MYI, and.MYDfiles for MyISAM tables and the.frmand data files(.ibdoribdata) for InnoDB between different hardware architectures that support the samefloating-point format (Endianness) This means that you can transfer InnoDB and MyISAMtables from Windows to Linux without doing a logical export and import Simply shut down thedatabase (or lock the tables involved) and usescpto copy the database Or, restore a physicalbackup to a different machine

In cases where you need to transfer databases between different architectures, you can use

mysqldumpto create a file containing SQL statements You can then transfer the dump file to

the second machine (the destination host) and feed it as input to themysqlclient

To move a database from one machine to another, run the following from the machine currently

holding the database (the target host):

shell> mysqldump databases sakila | mysql -h destination_host

sakila

For large tables, exporting a tab-delimited file and usingmysqlimportis much faster thanusingmysqldumpto exportINSERTstatements and restoring withsourceor the redirectionoperator (<) The tab=/path/to/backupoption tomysqldumpcreates a tab-delimitedASCII data file (.txt) and schema file (.sql) for each table, whenmysqldumpis run locally

First, create the backup directory and dump the database:

shell> mkdir /path/to/backup shell> mysqldump tab=/path/to/backup databases sakila

Then copy the files in/path/to/backupdirectory to the destination machine and load thefiles intomysqldthere:

shell> cat /path/to/backup/*.sql | mysql sakila shell> mysqlimport sakila /path/to/destination/copy/*.txt

The grant tables (user permissions) are stored in the mysql database If you do not have a mysql database, mysqld may not start up on the new machine Make sure to FLUSH PRIVILEGES or restart mysqld when the grant tables are imported.

Trang 2

Recovering from Crashes

Many administrators spend a significant amount of time on backups and then do not spend time

on their recovery strategies However, they make a serious mistake by not planning for how theywill recover or ever testing backups and the recovery process by performing a recovery

The recovery process is going to vary depending on your objectives It will always beginwith the restoration of a backup With physical backups you just copy the files to the serverwhere the recovery is taking place and restart the server For a logical backup the techniquesused for recovery are going to vary — recovery may consist of loading of files with thesource

command, redirecting files with the<operator, or usingmysqlimport.Often after the backup is restored you will need to restore the server to a point-in-time after thelast backup If this is the case you need to perform what is called a point-in-time recovery.You can perform a point-in-time recovery with any backup process because you are using incre-mental backups (such as the binary log files) to bring the server up to a certain point-in-timeafter restoring a previous backup

MySQL server uses a binary format for the log files to save space This means you cannot view

it directly MySQL supplies a utility calledmysqlbinlogto convert these logs to a text formatthat you can view For more on binary logging, see Chapter 16

The process for performing a point-in-time restore is as follows:

■ Restore the database using the last backup

■ Determine the first binary log and starting position needed

■ Determine the last binary log needed

■ Convert the binary log(s) to text format with the mysqlbinlog utility, using options tospecify the start and stop time

■ Import the converted binary log(s)

As with any recovery process, the first step is to restore the last backup performed This tion will vary depending on how the backup was performed For this example assume a file sys-tem snapshot was performed at midnight of the 16th of September and the logs were flushed atthe same time This means you have a physical backup and the restoration should just be copy-ing the files to the server and starting upmysqldagain

restora-Once the basic restoration is complete it is time to restore the data changes since the backupwas performed

Trang 3

Here is a listing of the binary log directory:

$ ls -lh mysql-bin*

-rw-rw 1 mysql mysql 257M Sep 16 23:48 mysql-bin.010309 -rw-rw 1 mysql mysql 257M Sep 17 00:02 mysql-bin.010310 -rw-rw 1 mysql mysql 257M Sep 17 03:48 mysql-bin.010311 -rw-rw 1 mysql mysql 257M Sep 17 19:01 mysql-bin.010312 -rw-rw 1 mysql mysql 162M Sep 17 19:03 mysql-bin.010313 -rw-rw 1 mysql mysql 8.3K Sep 17 19:01 mysql-bin.index

This means thatmysql-bin.010310is the first binary log created after the backup was formed This was determined by looking at the timestamp of the log files, which shows the lasttime the log file was modified Knowing the backup was performed at midnight you can see that

per-mysql-bin.010309was the last log written before midnight Therefore the next log file is theone with which you want to start your restoration

For this example, you need to restore the server through the last log listed, which is

mysql-bin.010313

If you have a large number of binary logs (such as in this case) to convert it would probably bebeneficial to script this process The command to convert an entire binary file will look similar

to this:

$ mysqlbinlog mysql-bin.010310 > mysql-bin.010310.sql

This would convert themysql-bin.010310log to text format and store it in the

mysql-bin.010310.sqlfile You will have to do this for each log file needed The finalpart of the process is the import of the log files into the database server:

$ mysql user=root pasword < mysql-bin.010310.sql

This would need to be done for each converted binary log Once again, scripting might behelpful

To create text files from parts of binary logs usingmysqlbinlog, specify a starting placewith either start-datetime=’YYYY-MM-DD’or start-position=#and endingplace with either stop-datetime=’YYYY-MM-DD’or stop-position=# To determinethe exact position to start or stop you have to examine the binary log contents The problem isthat this can be a large file To start you have to convert the log to text format:

$ mysqlbinlog mysql-bin.010312 > mysql-bin.010312.sql

Trang 4

Once you convert the log file you can view the text-format log with a text editor With a binarylog of 162 MB in size this may be tricky If you are looking to end at a specific time you canspecify a stopping time:

$ mysqlbinlog stop-datetime=’2008-09-17 18:42:48’ mysql-bin.010312

> mysql-bin.010312.sql

Once you have trimmed the file it becomes much easier to view with thetailcommand Nowyou will still have to potentially look through a number of entries because a busy databaseserver is going to be executing hundreds, if not thousands, of queries a second Here are the last

25 lines after trimming:

$ tail -25 mysql-bin.010312.sql use usersession/*!*/;

In this case you want to execute the firstCOMMITstatement and then stop The line after the

COMMITstatement shows the log position The log position is185118473 Now you can createyour final text format file with exactly the right information:

Trang 5

$ mysqlbinlog stop-position=185118473 mysql-bin.010312 >

mysql-bin.010312.sql

This file (mysql-bin.010656.sql) is what you will want to import

$ mysql user=root password < mysql-bin.010656.sql

It would be wise to examine the resulting file to ensure it is correct before execution of the logfile

Table 13-6 lists common options for themysqlbinlogprogram

Planning for Disasters

Database recovery is part of the disaster planning process What to do, who does it, and howlong the recovery process takes when things break requires thought, planning, and usually coor-dination with other people and departments It is important that you rehearse plans and performdrills to make sure that the proper preparations are in place

A backup plan and corresponding periodic restores of your backups should be part of the ter preparation An incomplete list of issues covered could include:

disas-■ Power

■ Employee termination process

■ Data center failover plan

■ Data retention strategies

Trang 6

A disaster plan should be written down and approved by everyone involved, including ment It should include checklists and processes to carry out for various scenarios.

manage-Summary

You have multiple methods of backing up your data, and depending on your situation, someoptions are going to be better than others Do not underestimate the importance of performingbackups and testing the recovery procedure Ensure the backups and recovery processes areactually working and current by testing frequently, preferably at least once per quarter Otherperiodic tasks may include a test of the backups and recovery processes, such as periodicallyrefreshing a QA server by recovering a production backup to it

The following topics were covered in this chapter:

■ Backup and recovery terminology

■ Why backups are necessary

■ Backup methodology

■ The recovery process

■ Disaster planning

Trang 7

IN THIS CHAPTER

Learning about MySQL users Managing user accounts Resetting the root password Debugging user account problems

Managing the users for a MySQL server is one of the most

impor-tant tasks of a MySQL database administrator Because of theflexibility of the permissions system, it is not necessarily a trivialtask There are many tips to help manage users

Learning about MySQL Users

A user in MySQL is a combination of a username and host string.

A host string can be an IP address, hostname, fully qualified domainname, or netmask This means that even though they share a username,

admin@192.168.2.10is different fromadmin@’192.168.2.%’, andboth users can have different passwords and permissions In the followingexample, we set up two users with the same username and differentpasswords and permissions:

shell> mysql -u root -prootpass Welcome to the MySQL monitor Commands end with ; or \g.

Your MySQL connection id is 8 Server version: 6.0.8-alpha-community MySQL Community Server (GPL) Type ’help;’ or ’\h’ for help Type ’\c’ to clear the buffer.

mysql> GRANT USAGE ON *.* TO admin@’192.168.2.10’

IDENTIFIED BY ’easytoguess’;

Query OK, 0 rows affected (0.22 sec) mysql> GRANT ALL ON sakila.* TO admin@’192.168.2.20’

IDENTIFIED BY ’anotherpassword’;

Trang 8

Query OK, 0 rows affected (0.41 sec) mysql> select user,host,password from mysql.user where user=’admin’; + -+ -+ -+

+ -+ -+ -+

| admin | 192.168.2.10 | *2F9A309FBEA7337E61AA2953EB48179BF9300B7C |

| admin | 192.168.2.20 | *4CBC947A0D5CF017233C027F4597C92A92D02F92 | + -+ -+ -+

2 rows in set (0.05 sec) mysql> exit

Bye

This allows for a flexible control system but can also cause confusion How the server mines who a user is and what permissions are allowed for that user will be discussed in the nextsection

deter-Access Control Lists

An ACL (Access Control List) is a list of permissions that is associated with an object This list isthe basis for MySQL server’s security model and once you understand this it helps greatly whentroubleshooting problems with users not being able to connect

MySQL keeps the ACLs (also called grant tables) cached in memory When a user tries toauthenticate or run a command, MySQL checks the authentication information and permissionsagainst the ACLs, in a predetermined order If you had two users,admin@’192.168.2.%’

and thenadmin@192.168.2.10, the useradmin@’192.168.2.%’user comes before

admin@192.168.2.10in the Access Control List When MySQL checks authentication,theadmin@’192.168.2.%’user is the first user whose credentials match the credentialsprovided Remember how users with the same username but different host strings can havedifferent passwords? The following example shows what happens in this case; the computer used

by the user has an IP address of 192.168.2.20:

shell> mysql -u admin –peasytoguess –h 192.168.1.5 ERROR 1045 (28000): Access denied for user ’admin @’192.168.2.20’ (using password: YES)

What happened was the account attempted to connect using the accountadmin@192.168 2.10, which was configured with the password ofeasytoguesss When attempting to connectthe server authenticated against the user accountadmin@192.168.2.20, which has a password

of anotherpassword

If they had same passwords the connection would be allowed — but the connection may beusing an account with different privileges than expected If you are not sure what user you areactually logged in as you can use theUSER()andCURRENT_USER()functions to determinehow you are connected

Trang 9

TheUSER()function shows which username and host the MySQL server sees the connection

as coming from TheCURRENT_USER()function shows which username and host the nection is actually authenticated Note that theSHOW GRANTSstatement with no argumentsshows the privileges for the user the connection was authenticated — the privileges for the

con-CURRENT_USER()

Wildcards

Wildcard characters (% and _) are allowed in host strings This is another source of confusion as

admin@192.168.2.10is a completely different user thanadmin@’192.168.2.%’ As statedabove, MySQL checks the access control list in order However, we did not reveal how theMySQL server orders the access control list

MySQL orders the access control list with the least specific hosts last This means that hostnamesand IPs without wildcards or netmasks are placed before hostnames and IPs with wildcards andnetmasks MySQL matches the most specific user and hostname

In the following example, after deleting the users from the previous example,admin@192.168 2.10is given full read/write permissions to thesakiladatabase, andadmin@’19.168.2.%’isgiven read-only permissions to thesakiladatabase:

mysql> DROP USER admin@192.168.2.20;

Query OK, 0 rows affected (0.01 sec) mysql> DROP USER admin@192.168.2.10;

Query OK, 0 rows affected (0.01 sec)

mysql> SELECT USER, HOST, PASSWORD FROM MYSQL.USER WHERE USER=’admin’;

Empty set (0.01 sec) mysql> GRANT SELECT ON sakila.* TO admin@’1921.68.2.%’

Your MySQL connection id is 8 Server version: 6.0.8-alpha-community MySQL Community Server (GPL) Type ’help;’ or ’\h’ for help Type ’\c’ to clear the buffer.

Trang 10

mysql> SHOW GRANTS\G

*************************** 1 row ***************************

Grants for admin@192.168.2.10: GRANT USAGE ON *.* TO ’admin’@’192 168.2.10’ IDENTIFIED BY PASSWORD ’*2C6396ADEEF1AF865672D48735 C0E3EC8B1A9CEC’

System tables

All the user and permission information is stored in themysqldatabase in a set of tables known

as the grant tables If you execute’SHOW DATABASES’on a typical default install of MySQL itwill look like the following:

mysql> SHOW DATABASES;

3 rows in set (0.02 sec)

Theinformation_schemadatabase really is not a database but an interface to various systemmetadata (see Chapter 21 for more information about theinformation_schemadatabase).Thetestdatabase is an empty database used for testing purposes and as mentioned themysql

database stores the user information In addition to the grant tables, themysqldatabase hastables containing other system information For example, a table calledeventis used by the

Trang 11

event scheduler (see Chapter 7 for more information about events) Because of new additionssuch as this, the tables in themysqldatabase vary from version to version Here are the tables

in a server runningmysqld 6.0.8-alpha:

mysql> SHOW TABLES;

+ -+

| Tables_in_mysql | + -+

25 rows in set (0.18 sec)

The tables that are of interest when it comes user management arecolumns_priv,db,host,

procs_priv,tables_priv, anduser It is possible to directly manipulate these tables usingSQL to add, delete, or update user information In fact, that used to be the only way privilegeswere managed These days, however, it is much easier and less error prone to use theGRANT,

REVOKE,CREATE USER,DROP USER, andRENAME USERcommands designed for user ment We will cover the commands used to manipulate users in the next section

Trang 12

manage-One of the more common problems of a database administrator is seeing what users are alreadyexist and what privileges they have If you are logged in to the server with appropriate privi-leges, the following will show all usernames, hosts, and password hashes on the system:

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

| production_ | slave | *891A44E50A5E8286F04BC1EFB0292BE3 |

7 rows in set (0.00 sec)

If a user has a blank password, the password field will be empty.

Managing User Accounts

MySQL server provides a number of commands used for managing users To create a user, youcan use theCREATE USERcommand To drop a user, you should use theDROP USERcommand

In the following example, we create a user and give them privileges and finally drop the user

mysql> CREATE USER ’ops’@’192.168.%’ IDENTIFIED BY ’password’;

Query OK, 0 rows affected (0.00 sec) mysql> GRANT ALL PRIVILEGES ON test.* TO ’ops’@’192.168.%’;

Query OK, 0 rows affected (0.00 sec) mysql> DROP USER ’ops’@’192.168.%’;

Query OK, 0 rows affected (0.00 sec)

Trang 13

mysql> select User,Host,Password from user;

2 rows in set (0.00 sec)

The CREATE USER and GRANT USER commands (covered in the next section) can both be used to create users without passwords This is very insecure and should be avoided! Always use the IDENTIFIED BY clause when using these commands.

Dropping the user removes all their privileges Even if you recreate the exact same usernameand host the new user does not retain the privileges of the previous user You are starting fromscratch Here is an example showing this:

mysql> CREATE USER ’ops’@’192.168.%’ IDENTIFIED BY ’password’;

Query OK, 0 rows affected (0.00 sec) mysql> GRANT ALL PRIVILEGES ON test.* TO ’ops’@’192.168.%’;

Query OK, 0 rows affected (0.00 sec) mysql> DROP USER ’ops’@’192.168.%’;

Query OK, 0 rows affected (0.00 sec) mysql> SELECT user,host,password FROM mysql.user;

2 rows in set (0.00 sec) mysql> CREATE USER ’ops’@’192.168.%’ IDENTIFIED BY ’password’;

Query OK, 0 rows affected (0.00 sec) mysql> SHOW GRANTS FOR ’ops’@’192.168.%’;

Trang 14

TheRENAME USERcommand renames an existing account TheRENAME COMMANDwill return anerror if the new user already exists.

mysql> CREATE USER ’ops’@’192.168.%’ IDENTIFIED BY ’password’; Query OK, 0 rows affected (0.00 sec)

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

3 rows in set (0.00 sec) mysql> CREATE USER ’support’@’192.168.%’;

Query OK, 0 rows affected (0.00 sec) mysql> SELECT user,host,password FROM mysql.user;

4 rows in set (0.00 sec) mysql> RENAME USER ’ops’@’192.168.%’ TO ’support’@’192.168.%’; ERROR 1396 (HY000): Operation RENAME USER failed for ’ops’@

Trang 15

When a user is renamed, the password is retained by the new user The user privileges are notmigrated AlsoRENAME USERdoes not change any database object properties (tables, views,stored routines, and triggers) that the user created.

GRANT and REVOKE commands

There are two commands that are used to control a user’s privileges TheGRANTcommand isused to give an existing user privileges, andREVOKEis used to remove privileges If a user doesnot exist,GRANTwill create a new user at the same time you are giving them privileges

It is not recommended that you use GRANT to create a user, because it is too easy to forget to specify a password when using the GRANT syntax Users should be created with CREATE USER first, then given permissions with GRANT.

There are five levels that privileges can be granted

Global

Global privileges apply to all databases on a MySQL server These privileges are stored

in themysql.usertable You use theGRANT privilege_list ON *.*andREVOKE privilege_list ON *.*statements to grant and revoke only global level privileges

The following example will grant all privileges (except theGRANT PRIVILEGESprivilege) to the

’ops’@’192.168.%’user These privileges apply for all databases on the server:

GRANT RELOAD,SHUTDOWN ON *.* TO ’ops’@’192.168.%’;

The next example will grant onlySELECT,INSERT,UPDATE, andDELETEprivileges to the user

’ops’@’192.168.%’on all databases on the server:

GRANT SELECT, INSERT, UPDATE, DELETE ON *.* TO ’ops’@’192.168.%’;

The users with username of root created by default is only special because of the permissions it has The root username has no significance and can be deleted from

a fresh installation with no issues (servers currently in use may be depending on the root user for backups or some other important task) To create a new user with all privileges:

CREATE USER superuser@localhost IDENTIFIED BY ’superpass’;

GRANT ALL ON *.* TO superuser@localhost;

Database

Database privileges apply to all objects of a specified database These privileges are stored inthemysql.dbandmysql.hosttables TheGRANT ALL ON db_name.*andREVOKE ALL ON db_name.*commands grant and revoke only database level privileges

The following example will grant all privileges (except theGRANT PRIVILEGESprivilege) to the

’ops’@’192.168.%’user These privileges apply only to the databaseuser_db:

GRANT ALL ON user_db.* TO ’ops’@’192.168.%’;

Trang 16

The next example will grant onlySELECT,INSERT,UPDATE, andDELETEprivileges to the user

’ops’@’192.168.%’on the databaseuser_db:

GRANT SELECT, INSERT, UPDATE, DELETE ON user_db.* TO ’ops’

@’192.168.%’;

Table

Table privileges apply to all columns in a given table These privileges are stored in the

mysql.tables_privtable TheGRANT ALL ON db_name.table_nameandREVOKE ALL ON db_name.table_namecommands grant and revoke only table level privileges

The following example will grant all privileges (except theGRANT PRIVILEGESprivilege) tothe’ops’@’192.168.%’user These privileges apply only to the tabletable_nameof thedatabaseuser_db:

GRANT ALL ON user_db.table_name TO ’ops’@’192.168.%’;

The next example will grant onlySELECT,INSERT,UPDATE, andDELETEprivileges to the user

’ops’@’192.168.%’on to the tabletable_nameof the databaseuser_db:

GRANT SELECT, INSERT, UPDATE, DELETE ON user_db.table_name TO

’ops’@’192.168.%’;

If you had only specifiedtable_namerather thandb_name.table_name, theGRANTor

REVOKEstatement applies to the tabletable_namein the default database To keep from ing unexpected results, we would recommend you use the"full" database_name.table_name

hav-format instead

Column

Column level privileges apply to one or more columns in a given table These privileges arestored in themysql.columns_privtable When using theREVOKEcommand to removecolumn level privileges, you must specify the same columns that were granted The column orcolumns for which the privileges are to be granted are enclosed within parentheses

The following example will grantSELECT,INSERT, andUPDATEprivileges to the user

’ops’@’192.168.%’on the columns col1 and col2 of the tabletable_namelocated in thedatabaseuser_db:

GRANT SELECT (col1,col2), INSERT (col1,col2), UPDATE (col1,col2)

ON user_db.table_name TO ’ops’@’192.168.%’;

Trang 17

TheCREATE ROUTINE,ALTER ROUTINE,EXECUTE, andGRANTprivileges apply to stored tines (functions and procedures) They can be granted at the global and database levels Also,except forCREATE ROUTINE, these privileges can be granted at the routine level for individualroutines The privileges are stored in themysql.procs_privtable

rou-GRANT CREATE ROUTINE ON database.* TO ’ops’@’192.168.2.%’;

GRANT EXECUTE ON PROCEDURE database.backup_proc TO ’backup’@

ALL Grants all privileges to specified user except the GRANT OPTION.

ALTER Allows user to ALTER TABLE.

ALTER ROUTINE Allows user to alter or drop stored routines.

CREATE Allows user to execute the CREATE TABLE command.

CREATE ROUTINE Allows user to create stored routines.

CREATE TEMPORARY TABLES

Allows user to execute the CREATE TEMPORARY TABLE command.

CREATE USER Allows user to execute CREATE USER, DROP USER, RENAME USER

and REVOKE ALL PRIVILEGES statements for user creation.

CREATE VIEW Allows user to execute the CREATE VIEW command to create views.

DELETE Allows user to execute the DELETE command.

DROP Allows user to execute the DROP command.

EXECUTE Allows user to run stored routines.

FILE Allows user to execute both SELECT INTO OUTFILE and LOAD

DATA INFILE.

GRANT OPTION Allows user to grant other users privileges.

INDEX Allows user to execute CREATE INDEX and DROP INDEX.

continued

Trang 18

TABLE 14-1 (continued )

Privilege Description

INSERT Allows user to execute the INSERT command.

LOCK TABLES Allows user to execute LOCK TABLES (user must also have SELECT

privileges on the table).

PROCESS Allows user to see all processes when executing SHOW

PROCESSLIST.

REFERENCES This privilege is not currently implemented.

RELOAD Allows user to execute FLUSH.

REPLICATION CLIENT

Allows user to execute both SHOW MASTER STATUS and SHOW SLAVE STATUS commands.

REPLICATION SLAVE

Needed by the replication slave to read binary logs from the master SELECT Allows users to execute SELECT statement.

SHOW DATABASES When user executes SHOW DATABASES command will return a list of

all databases.

SHOW VIEW Allows user to execute the SHOW CREATE VIEW command.

SHUTDOWN Allows user to execute ’mysqladmin shutdown’.

SUPER Allows user to execute CHANGE MASTER, KILL, PURGE MASTER

LOGS, and SET GLOBAL commands Also will allow user to always connect even if max_connections has been reached.

UPDATE Allows user to execute UPDATE command USAGE Allows user to connect.

As you can see there are quite a few allowable privileges This, in combination with the fiveprivilege levels (global, database, table, column, and routine), allow for any level of granularityneeded by a database administrator This granularity creates complexity, but the end result is amore controllable and secure system

Privileges are checked until either access is allowed or the end of the ACL is reached.

If you want to query the table production.employee, then MySQL server first checks to see if you have global access privileges If so, the query is executed If you do not have global access then MySQL server checks for privileges at the database level (production) If you do not have privileges at the database level, then the table level (employee) privileges are checked.

If this fails the column level privileges are checked and if this fails the user is denied access If a check returns positive at any level mysqld stops checking privileges.

Trang 19

TheREVOKEstatement is used to remove privileges from a user account Just as with theGRANT

statement there are five levels that you can revoke privileges from: global, database, table, umn, and routine

col-The following example would revoke all privileges for the user’ops’@’localhost’:

mysql> REVOKE ALL PRIVILEGES, GRANT OPTION FROM ’ops’@’localhost’;

Even if you revoke all privileges, the user is not dropped (they are still visible in the mysql.user system table) At this point, the user has the USAGE privilege, which means they can still connect to the server and execute a few commands such as SHOW VARIABLES

and SELECT NOW() To drop a user, you must use the DROP USER It is a best practice to always drop users after revoking all their privileges.

What if the’ops’@’localhost’had globalSELECT,INSERT,UPDATE,DELETE, and

DROPprivileges but you wanted to only remove theDROPprivilege? The following wouldaccomplish this:

mysql> REVOKE DROP ON *.* FROM ’ops’@’localhost’;

If the user’ops’localhost’hadSELECT,INSERT,UPDATE, andDELETEprivileges on thetableuser_accountsof the databaseproduction, you could revoke theDELETEprivileges onthis one table like this:

mysql> REVOKE DELETE ON production.user_accounts FROM

’ops’@’localhost’;

As you have probably noticed theREVOKEcommand very similar of theGRANTcommand

SHOW GRANTS and mk-show-grants

TheSHOW GRANTScommand is used to show a user’s privileges This is done by displaying a list

of all the GRANT statement(s) that could then be used to duplicate the privileges of a user Ifthe user has theGRANT PRIVILEGESprivilege, then the user can also view the grants of otherusers

Here is a simple example which shows the grants for the current user:

mysql> SHOW GRANTS\G

*************************** 1 row ***************************

Grants for root@localhost: GRANT ALL PRIVILEGES ON *.* TO ’root’@

’localhost’ IDENTIFIED BY PASSWORD ’*3800D13EE735ED411CBC3F23B2 A2E19C63CE0BEC’ WITH GRANT OPTION

1 row in set (0.00 sec)

Trang 20

This was done with the root user who has all privileges, including theGRANT OPTION Becausethis user has theGRANT OPTION, it can grant privileges to other users, and use theSHOW GRANTScommand to display grants for other users.

Remember, if you need to see a list of users on the server SELECT user,host FROM mysql.user will return all users.

Now to take a look at the privileges for’over_lords’@’%’:

mysql> SHOW GRANTS FOR ’over_lords’@’%’\G

Here is a sample of themk-show-grantscommand on a system with more users Passwordhashes have been removed:

shell> /mk-show-grants -u root -ppassword Grants dumped by mk-show-grants @VERSION@

Dumped from server Localhost via UNIX socket, MySQL 6.0.8-alpha at 2009-01-06 01:48:50

Grants for ’monitoring’@’10.%’

GRANT REPLICATION SLAVE ON *.* TO ’monitoring’@’10.%’ FIED BY PASSWORD ’PASSWORD_HASH’;

IDENTI - Grants for ’monitoring’@’localhost’

GRANT ALL PRIVILEGES ON *.* TO ’monitoring’@’localhost’ FIED BY PASSWORD ’PASSWORD_HASH’;

IDENTI-GRANT USAGE ON *.* TO ’company’@’%.company.com’ IDENTIFIED BY PASSWORD ’PASSWORD_HASH’;

GRANT ALL PRIVILEGES ON `company_production`.* TO ’company’@’% company.com’ WITH GRANT OPTION;

Grants for ’webuser’@’10.%’

GRANT USAGE ON *.* TO ’webuser’@’10.%’ IDENTIFIED BY PASSWORD

’PASSWORD_HASH’;

GRANT ALL PRIVILEGES ON `company_production`.* TO ’webuser’@’10.%’ WITH GRANT OPTION;

Grants for ’webuser’@’localhost’

GRANT USAGE ON *.* TO ’webuser’@’localhost’ IDENTIFIED BY PASSWORD ’PASSWORD_HASH’;

GRANT ALL PRIVILEGES ON `webuser_load_test`.* TO ’webuser’@

Trang 21

GRANT ALL PRIVILEGES ON `webuser_production`.* TO ’webuser’@

’localhost’ WITH GRANT OPTION;

Grants for ’production_slave’@’8.%’

GRANT REPLICATION CLIENT, REPLICATION SLAVE ON *.* TO

’production_slave’@’8.%’ IDENTIFIED BY PASSWORD ’PASSWORD_HASH’;

Grants for ’production_slave’@’192.168.1.191’

GRANT REPLICATION SLAVE ON *.* TO ’production_slave’@’192.168.1.191’

IDENTIFIED BY PASSWORD ’PASSWORD_HASH’;

Grants for ’production_slave’@’preview.company.com’

GRANT REPLICATION SLAVE ON *.* TO ’production_slave’@

’preview.company.com’ IDENTIFIED BY PASSWORD ’PASSWORD_HASH’;

Grants for ’root’@’localhost’

GRANT ALL PRIVILEGES ON *.* TO ’root’@’localhost’ IDENTIFIED BY PASSWORD ’PASSWORD_HASH’ WITH GRANT OPTION;

Grants for ’tempuser’@’%’

GRANT ALL PRIVILEGES ON *.* TO ’tempuser’@’%’ IDENTIFIED BY PASSWORD ’PASSWORD_HASH’;

ahell>

To send this output to a file:

shell> /mk-show-grants -u root -ppassword > grants.sql

Resetting the Root Password

There are times when the password for the root user is lost It is not a trivial matter to reset thepassword and requires a server restart However, there are times when this proves necessary

There are two methods for recovering the password Both have their benefits and drawbacks

A simple recovery method that works on any server platform uses the’skip-grants-table’

option in your configuration file When the server is restarted with this option it starts

‘‘wide open’’ with anyone able to log in with all privileges without even specifying a name This is a huge security risk and must be carefully considered on production system

user-We would recommend that when you add’skip-grants-table’that you also add the

’bind-address=127.0.0.1’option, which does not allow remote network connections tothe MySQL server This minimizes the risk somewhat

Here is the procedure:

1 Edit the configuration file and add theskip-grant-tablesand (optionally) the

bind-addressoption to themysqldsection

2 Restart the MySQL server

Trang 22

3 Connect to themysqldserver using themysqlclient No password or user needs to bespecified If you also used theskip-networkingoption, you must run themysqlclientfrom the server itself.

mysql> FLUSH PRIVILEGES;

What happens here is that theUPDATEstatement resets the password for all existing rootaccounts and theFLUSH PRIVILEGESstatement tells the server to reload the grant tablesinto memory

5 Exit themysqlclient and test your new password If everything works correctly, remove

skip-grants-tableandskip-networkingfrom the configuration file, and restartthe MySQL server

This is a straightforward procedure and in an emergency might be the only method you havetime to perform However, as pointed out, it is not inherently secure

The second method of resetting the root password is more secure The basis for this recoverymethod is using an initialization file at server startup to execute the sameUPDATEandFLUSH PRIVILEGEScommands we used in the previous example It varies somewhat from Windowsservers to Unix-based servers, so approaches for both will be outlined

Windows server

1 Log on to your system as a user with Administrator privileges.

2 Stop the MySQL server if it is currently running.

If MySQL is running as a Windows service, click on Start MenuSettingsControlPanelAdministrative ToolsServices Then find the MySQL service in the list, rightclick on it, and then left-click on Stop

If your MySQL server is not running as a service, you may need to use the Task Manager

to force it to stop

3 With your favorite text editor, create a text file, and place the following statements in it:

UPDATE mysql.user SET Password=PASSWORD(’New_Password’) WHERE User=’root’;

FLUSH PRIVILEGES;

Trang 23

ReplaceNew_Passwordwith the password that you want to use (but leave the quotationmarks) Each of the statements must be written on a single line.

4 Save the file For this example, the filename will beC:\reset_pass.txt

5 Open a console window to get to the command prompt Click on Start MenuRun andthen typecmd

6 Start the MySQL server with the init-fileoption It might look something like this:

C:\> C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld console init-file=C:\reset_pass.txt

If you installed MySQL to another location adjust the directory accordingly

The server executes the contents of the file named by the init-fileoption at startupwhile displaying any output to the console

If you installed MySQL using the MySQL Installation Wizard, you also may need to specify

a defaults-fileoption The appropriate defaults-filesetting can be foundusing the Services Manager:

Click Start MenuControl PanelAdministrative ToolsServicesFind the MySQL service in the list, right-click on it, and choose the Properties option ThePath to executable field contains the defaults-filesetting

If you can not get the MySQL server to start from the command line, you can edit theserver configuration file and add theinit-fileoption in yourmysqldsection and thenrestart the server using the Services manager

7 After the server has started successfully and you have confirmed the new password work,

delete the initialization fileC:\reset_pass.txt, and remove theinit-fileoptionfrom your configuration file if necessary and restart it in the normal manner

Unix-based server

You can use the following procedure for resetting the password for any MySQL root accounts on

a Unix-based sever:

1 Create a text file and place the following statements in it Replace the password with the

password that you want to use

UPDATE mysql.user SET Password=PASSWORD(’MyNewPass’) WHERE User=’root’;

FLUSH PRIVILEGES;

TheUPDATEandFLUSHstatements each must be written on a single line TheUPDATE

statement resets the password for all existing root accounts, and theFLUSHstatement tellsthe server to reload the grant tables into memory

2 Save the file For this example, the file will be named/home/kmurphy/mysql-init.The file contains the root user password Be certain that it cannot be read byother users

Trang 24

Edit your/etc/my.cnf file Under[myqld]addinit-file=/home/kmurphy/ mysql-init.

3 Shut down the MySQL server in your normal manner.

4 Start the MySQL server in your normal manner.

The server executes the contents of the file named by theinit-fileoption at startup,changing each root account password to the new password specified

5 After the server has started successfully and you have verified the new password works,

delete the initialization file and editmy.cnffile to remove theinit-fileline

Debugging User Account Problems

There are times when users will come to the database administrator with complaints that anewly created account isn’t working When this happens, there are some common issues youcan look for to help when troubleshooting

1 row in set (0.00 sec)

The user comes to you and says their new account is not working You check the error they areseeing:

shell> mysql -u ops -p Enter password:

ERROR 1045 (28000): Access denied for user ’ops’@’localhost’ (using password: YES)

Trang 25

In this case, if there was not a miscommunication about what the password should be andyou need to reset the password, then log in as a user who hasGRANTprivileges and do thefollowing:

mysql> SET PASSWORD FOR ops@’192.168.%’ = PASSWORD(’New_Password’);

Query OK, 0 rows affected (0.00 sec)

And now the user can log in with the new password:

shell> mysql -u ops -p Enter password: ************

Welcome to the MySQL monitor Commands end with ; or \g.

Your MySQL connection id is 8 Server version: 6.0.8-alpha MySQL Community Server (GPL) Type ’help;’ or ’\h’ for help Type ’\c’ to clear the buffer.

mysql>

Access issues

A more subtle issue is that of access The user has the right username and password, butthe host is either set incorrectly or there are multiple hosts listed with the same usernameand the ‘‘wrong’’ host is being used in authentication You saw this issue earlier with the

admin@127.0.0.1andadmin@localhostusers

If a user does not have the expected permissions, checkSHOW GRANTSwith no ments to see what user and permissions the server is using Also bothSELECT USER(),

argu-CURRENT_USER(), andSELECT user, host, password FROM mysql.user WHERE user=’<username>’;are useful to help troubleshoot issues where the permissions are not asthey are expected

Client does not support authentication protocol

Back inmysqldversion 4.1 a new authentication protocol was used by default This protocol ismore secure and should be used if possible The problem is that some clients only support theolder protocol For example, older Perl libraries can only support the older protocol, and at thetime of this book’s writing, PHP did not support the new protocol

To fix the problem, runmysqland log in as user with theSUPERprivilege Then use followingcommand which will change the password of the user to the old format:

mysql> SET PASSWORD FOR ops@’192.168.%’ = OLD_PASSWORD(’

My_Password’);

Ngày đăng: 21/01/2014, 22:20

TỪ KHÓA LIÊN QUAN