Ошибка 1290 mysql secure file priv как отключить

На чтение 2 мин Просмотров 2.5к. Опубликовано 06.05.2021

При запуске mysqld сервера вы можете указать параметры программы в файле параметров или в командной строке. Эти параметры предназначены для разблокировки других функций MySQL, изменения переменных или наложения ограничений.

Вот как параметры читаются на сервере MySQL:

  • mysqld считывает параметры из [mysqld] и [server] групп
  • mysqld_safe считывает параметры из [mysqld][server],[mysqld_safe]и [safe_mysqld] групп
  • mysql.server считывает параметры из [mysqld] и [mysql.server] групп.

Вы можете увидеть краткую сводку опций, поддерживаемых MySQL, используя:

Чтобы увидеть полный список, используйте команду:

$ mysqld verbose help

Одна из тех системных переменных, которые можно установить при запуске сервера, это mysqld_secure-file-priv

Содержание

  1. Что такое переменная mysqld_secure-file-priv?
  2. Изменение каталога переменных secure-file-priv
  3. Переменная Diable secure-file-priv

Что такое переменная mysqld_secure-file-priv?

Переменная secure_file_privиспользуется для ограничения эффекта операций импорта и экспорта данных. Пример пораженных операций, выполняемый  LOAD DATA и SELECT ... INTO OUTFILE отчетность и функция LOAD_FILE(). Эти операции разрешены только пользователям, имеющим такую  FILE привилегию.

Чтобы увидеть текущую настройку во время выполнения, используйте SHOW VARIABLESинструкцию.

Войдите в оболочку MySQL как пользователь root

Запускаем

mysql> SHOW VARIABLES LIKE «secure_file_priv»;

+++

| Variable_name    | Value                 |

+++

| secure_file_priv | /var/lib/mysqlfiles/ |

+++

1 row in set

Time: 0.023s

Вы можете видеть, что набор каталогов /var/lib/mysql-files/

Изменение каталога переменных secure-file-priv

Это значение можно изменить в файле опций MySQL в разделе [mysqld] .

Установите переменную в [mysqld] разделе

[mysqld]

securefilepriv=/mysqlfiles

Затем создайте настроенный каталог

sudo mkdir /mysqlfiles

sudo chown R mysql:mysql  /mysqlfiles/

Перезапустите службу MySQL, чтобы изменения вступили в силу.

sudo systemctl restart mysqld

Войдите снова, чтобы подтвердить новую настройку

mysql> SHOW VARIABLES LIKE «secure_file_priv»;

+++

| Variable_name    | Value        |

+++

| secure_file_priv | /mysqlfiles/ |

+++

1 row in set (0.00 sec)

Давайте протестируем, чтобы подтвердить, что мы можем экспортировать по указанному пути.

mysql> SELECT * FROM information_schema.processlist into outfile ‘/tmp/mysql_processes.txt’;

ERROR 1290 (HY000): The MySQL server is running with the securefilepriv option so it cannot execute this statement

Попробуем еще раз написать правильный путь.

mysql> SELECT * FROM information_schema.processlist into outfile ‘/mysqlfiles/mysql_processes.txt’;

Query OK, 1 row affected (0.00 sec)

Переменная Diable secure-file-priv

Чтобы отключить его, установите для переменной значение NULL.

[mysqld]

securefilepriv = «»

Перезапуск службы mysqld

sudo systemctl restart mysqld

Подтвердить после перезапуска службы

mysql> SHOW VARIABLES LIKE «secure_file_priv»;

+++

| Variable_name    | Value |

+++

| secure_file_priv |       |

+++

1 row in set (0.00 sec)

Попробуйте сохранить содержимое QUERY в другую директорию

mysql> SELECT * FROM information_schema.processlist into outfile ‘/tmp/mysql_processes.txt’;

Query OK, 1 row affected (0.00 sec)

Все, спасибо за внимание, теперь вы научились настраивать переменную secure-file-priv

I created a NodeJS import script if you are running nodeJS and you data is in the following form (double quote + comma and n new line)

INSERT INTO <your_table> VALUEs( **CSV LINE **)

This one is configured to run on http://localhost:5000/import.

I goes line by line and creates query string

"city","city_ascii","lat","lng","country","iso2","iso3","id"
"Tokyo","Tokyo","35.6850","139.7514","Japan","JP","JPN","1392685764",
...

server.js

const express = require('express'),
   cors = require('cors'),
   bodyParser = require('body-parser'),
   cookieParser = require('cookie-parser'),
   session = require('express-session'),
   app = express(),
   port = process.env.PORT || 5000,
   pj = require('./config/config.json'),
   path = require('path');

app.use(bodyParser.json());
app.use(cookieParser());
app.use(cors());


app.use(
   bodyParser.urlencoded({
      extended: false,
   })
);

var Import = require('./routes/ImportRoutes.js');

app.use('/import', Import);
if (process.env.NODE_ENV === 'production') {
   // set static folder
   app.use(express.static('client/build'));

   app.get('*', (req, res) => {
      res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
   });
}

app.listen(port, function () {
   console.log('Server is running on port: ' + port);
});

ImportRoutes.js

const express = require('express'),
   cors = require('cors'),
   fs = require('fs-extra'),
   byline = require('byline'),
   db = require('../database/db'),
   importcsv = express.Router();

importcsv.use(cors());

importcsv.get('/csv', (req, res) => {

   function processFile() {
      return new Promise((resolve) => {
         let first = true;
         var sql, sqls;
         var stream = byline(
            fs.createReadStream('../PATH/TO/YOUR!!!csv', {
               encoding: 'utf8',
            })
         );

         stream
            .on('data', function (line, err) {
               if (line !== undefined) {
                  sql = 'INSERT INTO <your_table> VALUES (' + line.toString() + ');';
                  if (first) console.log(sql);
                  first = false;
                  db.sequelize.query(sql);
               }
            })
            .on('finish', () => {
               resolve(sqls);
            });
      });
   }

   async function startStream() {
      console.log('started stream');
      const sqls = await processFile();
      res.end();
      console.log('ALL DONE');
   }

   startStream();
});

module.exports = importcsv;

db.js is the config file

const Sequelize = require('sequelize');
const db = {};
const sequelize = new Sequelize(
   config.global.db,
   config.global.user,
   config.global.password,
   {
      host: config.global.host,
      dialect: 'mysql',
      logging: console.log,
      freezeTableName: true,

      pool: {
         max: 5,
         min: 0,
         acquire: 30000,
         idle: 10000,
      },
   }
);

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

Disclaimer: This is not a perfect solution — I am only posting it for devs who are under a timeline and have lots of data to import and are encountering this ridiculous issue. I lost a lot of time on this and I hope to spare another dev the same lost time.

Ubuntu 16.04 (EASY): Find out where you are allowed to write

mysql> SELECT @@GLOBAL.secure_file_priv;
+---------------------------+
| @@GLOBAL.secure_file_priv |
+---------------------------+
| /var/lib/mysql-files/     |
+---------------------------+
1 row in set (0.00 sec)

Then, just write there

mysql> SELECT * FROM train INTO OUTFILE '/var/lib/mysql-files/test.csv' FIELDS TERMINATED BY ',';
Query OK, 992931 rows affected (1.65 sec)

mysql>

Mac OSX: Mysql installed via MAMP

Find out where you are allowed to write

mysql> SELECT @@GLOBAL.secure_file_priv;
+---------------------------+
| @@GLOBAL.secure_file_priv |
+---------------------------+
| NULL                      |
+---------------------------+
1 row in set (0.00 sec)

NULL means you’re screwed so you have to create the file «~/.my.cnf»

Enable read/write for MySQL installed via MAMP (on Mac):

  1. open «MAMP» use spotlight
  2. click «Stop Servers»
  3. edit ~/.my.cnf (using vi or your favorite editor) and add the following lines:

    $ vi ~/.my.cnf

[mysqld_safe]
[mysqld]
secure_file_priv="/Users/russian_spy/"
  1. click «Start Servers» (in MAMP window)

Now check if it works:

a. start mysql (default MAMP user is root, password is also root)

$ /Applications/MAMP/Library/bin/mysql -u root -p 

b. in mysql look at the white-listed paths

mysql> SELECT @@GLOBAL.secure_file_priv;
+---------------------------+
| @@GLOBAL.secure_file_priv |
+---------------------------+
| /Users/russian_spy/          |
+---------------------------+
1 row in set (0.00 sec)

c. Finally, test by exporting a table train into a CSV file

mysql> SELECT * FROM train INTO OUTFILE '/Users/russian_spy/test.csv' FIELDS TERMINATED BY ',';
Query OK, 992931 rows affected (1.65 sec)

mysql>

When you update your site with new data from a file, you may see the error “Error Code: 1290. The MySQL server is running with the –secure-file-priv option so it cannot execute this statement”.

Why did it happen all of a sudden? Is your data corrupted?

Not to worry. This is quite easy to fix and usually happens after a MySQL upgrade.

As part of our Server Management Services, we help server owners and webmasters resolve MySQL errors such as this.

Today we will help you fix error code 1290 in a few easy steps.

Why this MySQL error code 1290 appears?

From version 5.7.6 onwards MySQL introduced a new security feature.

This will prevent website attackers from loading malicious data directly into your database.

It is done by restricting the databases to load data from only a single special directory in the server.

That directory is accessible only by the server administrator, and therefore attackers won’t be able to load malware.

By default this directory will be “/var/lib/mysql-files/” in Linux servers.

So, if you have a program or script that loads site data from a different location, MySQL will think that it’s an unauthorized upload attempt, and block it.

Is there any solution?

We have two solutions for your problem with code 1290.

  • One is moving the data file into the directory
  • The other is reconfiguring and restarting MySQL server

Today, let’s discuss these in detail.

Fixing the error by moving the data file into the directory

Recently, one of our customers using Linux approached us with the error code 1290.

He said he was able to load files without failure before. But from the last few days, he is facing this error.

When checked, we found that he recently upgraded his MySQL to 5.7.6 and the default path is restricting the upload.

Let’s see how we fix this.

We asked him to use the query to determine where –secure-file-priv option is.

SHOW VARIABLES LIKE 'secure_file_priv'

This returned a variable along with its value as:

+------------------+-----------------------+
| Variable_name | Value |
+------------------+-----------------------+
| secure_file_priv | /var/lib/mysql-files/ |
+------------------+-----------------------+

We asked the customer to use  /var/lib/mysql-files/ as the file path to run LOAD DATA as this is the configured directory and he needs to move the data file here.

Finally, suggested running the LOAD DATA again with the full path.

This fixed the error.

For Windows Users

In Windows, we do the following for fixing the MySQL error 1290

We look for the file being used when the service starts at MySQL57 Windows service.

From there, we get a path similar to C:ProgramDataMySQLMySQL Server 5.7my.ini.

Open the file and under [mysqld] section we can see secure-file-priv along with value as shown:

secure-file-priv=”C:/ProgramData/MySQL/MySQL Server 5.7/Uploads”

This is the path we need to use. So, reissue the LOAD DATA statement with this right path for fixing the error.

Fixing the MySQL error 1290 by reconfiguring and restarting

In some cases, changing the directory won’t solve the issue. In such a case we need to do the following:

For Windows Users

  • Go to start menu and type services.msc then press Ctrl+Shift+Enter to run it as an administrator.
  • Locate the MySQL service and double-click to open its properties dialog.
  • Check the Path to Executable for the –defaults-file option to determine where my.ini file is located.
  • In windows, C:ProgramDataMySQLMySQL Server 5.7my.ini is the default file being used when the service starts.

MySQL error code 1290

Note: It may vary according to various versions

  • Stop the service then close the dialog.
  • From the start menu, take notepad then press Ctrl+Shift+Enter to run it as an administrator.
  • Then open my.ini file previously located in notepad and search the file for secure-file-priv.
  • finally, comment out the line by adding a # in front.

For Linux Users

In Linux, we suggest searching for either of the most common locations: /etc/my.cnf or /etc/mysql/my.cnf.

Search the file for secure-file-priv. We get it along with the value. Comment the line and restart the service.

This will fix the issue.

But, we won’t suggest this as it is not secure.

The secure way is always by moving the data file into the directory.

[Need assistance in fixing MySQL errors? Click here to talk to our experts.]

Conclusion

In short, we discussed in detail on MySQL error code 1290 and saw how our Support Engineers find fix for this in different scenarios.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Недорогой хостинг для сайтов

hosting.energy недорогой хостинг сайтов

При запуске mysqldсервера вы можете указать параметры программы в файле параметров или в командной строке. Эти параметры предназначены для разблокировки других функций MySQL, изменения переменных или наложения ограничений.

Вот как параметры читаются на сервере MySQL:

  • mysqld считывает параметры из [mysqld] и [server] групп
  • mysqld_safe считывает параметры из [mysqld][server], [mysqld_safe]и [safe_mysqld] групп
  • mysql.server cчитывает параметры из [mysqld] и [mysql.server] групп.

Вы можете увидеть краткую сводку опций, поддерживаемых MySQL, используя:

$ mysqld --help

Чтобы увидеть полный список, используйте команду:

$ mysqld --verbose --help

Одна из тех системных переменных, которые можно установить при запуске сервера, это mysqld_secure-file-priv

Что такое переменная mysqld_secure-file-priv?

Переменная secure_file_privиспользуется для ограничения эффекта операций импорта и экспорта данных. Пример пораженных операций, выполняемый  LOAD DATA и SELECT ... INTO OUTFILE отчетность и функция LOAD_FILE(). Эти операции разрешены только пользователям, имеющим такое  FILE право.

Чтобы увидеть текущую настройку во время выполнения, используйте SHOW VARIABLESинструкцию.

Войдите в оболочку MySQL как пользователь root

$ mysql -u root -p
mysql> SHOW VARIABLES LIKE "secure_file_priv";
+------------------+-----------------------+
| Variable_name    | Value                 |
+------------------+-----------------------+
| secure_file_priv | /var/lib/mysql-files/ |
+------------------+-----------------------+
1 row in set
Time: 0.023s

Вы можете видеть, что набор каталогов /var/lib/mysql-files/

Изменение каталога переменных secure-file-priv

Это значение можно изменить в файле опций MySQL в разделе [mysqld] .

sudo vim /etc/my.cnf

Установите переменную в [mysqld] разделе

[mysqld]
secure-file-priv=/mysqlfiles

Затем создайте настроенный каталог

sudo mkdir /mysqlfiles
sudo chown -R mysql:mysql  /mysqlfiles/

Перезапустите службу MySQL, чтобы изменения вступили в силу.

sudo systemctl restart mysqld

Войдите снова, чтобы подтвердить новую настройку

mysql> SHOW VARIABLES LIKE "secure_file_priv";
+------------------+--------------+
| Variable_name    | Value        |
+------------------+--------------+
| secure_file_priv | /mysqlfiles/ |
+------------------+--------------+
1 row in set (0.00 sec)

Давайте протестируем, чтобы подтвердить, что мы можем экспортировать по указанному пути.

mysql> SELECT * FROM information_schema.processlist into outfile '/tmp/mysql_processes.txt';
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

Попробуем еще раз написать правильный путь.

mysql> SELECT * FROM information_schema.processlist into outfile '/mysqlfiles/mysql_processes.txt';
Query OK, 1 row affected (0.00 sec)

Переменная Diable secure-file-priv

Чтобы отключить его, установите для переменной значение NULL.

[mysqld]
secure-file-priv = ""

Перезапуск службы mysqld

sudo systemctl restart mysqld

Подтвердить после перезапуска службы

mysql> SHOW VARIABLES LIKE "secure_file_priv";
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| secure_file_priv |       |
+------------------+-------+
1 row in set (0.00 sec)

Попробуйте сохранить содержимое QUERY по другому пути

mysql> SELECT * FROM information_schema.processlist into outfile '/tmp/mysql_processes.txt';
Query OK, 1 row affected (0.00 sec)

Это было успешно. Вы научились настраивать secure-file-privпеременную в соответствии со своим вариантом использования. До следующего раза, благодарим за использование нашего руководства для решения проблемы « Сервер MySQL работает с ошибкой –secure-file-priv » при попытке загрузить или сохранить данные.

Рекомендуемый контент


MySQL database provides you with queries to import and export data using the LOAD DATA and SELECT INTO FILE statements.

For example, suppose you have a students table in your database as follows:

+----+---------+---------+-------+--------+
| id | name    | subject | score | gender |
+----+---------+---------+-------+--------+
|  1 | Mark    | English |     7 | male   |
|  2 | Natalia | Math    |     8 | female |
|  3 | Gary    | Math    |     6 | male   |
|  4 | Joe     | English |     8 | male   |
|  5 | Sarah   | Math    |     6 | female |
|  6 | Peter   | English |     6 | male   |
+----+---------+---------+-------+--------+

When you want to export the table as a text file, you can use the SELECT INTO FILE statement as shown below:

SELECT * FROM students INTO OUTFILE "/tmp/out.txt";

The SQL statement above should produce the file out.txt in the tmp/ directory as a result of the query execution.

However, MySQL frequently throws the following error when you run a data import or export statement:

mysql> SELECT * FROM students INTO OUTFILE "/tmp/out.txt";
ERROR 1290 (HY000): The MySQL server is running with 
the --secure-file-priv option so it cannot execute this statement

The --secure-file-priv option is a system variable used by MySQL to limit the ability of the users to export or import data from the database server.

The option is added to your MySQL database as a global variable named secure_file_priv, so you can check the current value of the option using the SHOW VARIABLES statement.

Here’s an example of retrieving the secure_file_priv value:

mysql> SHOW VARIABLES LIKE 'secure_file_priv';
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| secure_file_priv | NULL  |
+------------------+-------+

The secure_file_priv option can have three possible values:

  • NULL value means the data export or import is disabled
  • Empty value means data export or import is enabled
  • Directory path value means data export or import is enabled only in the specified path

The secure_file_priv value is a read-only value, so you can’t change it directly using SQL query.

The following statement tries to change the secure_file_priv value to tmp/ folder:

SET GLOBAL secure_file_priv = "/tmp/";

The response would be as follows:

ERROR 1238 (HY000): Variable 'secure_file_priv' is a read only variable

To change the value of secure_file_priv variable, you need to create a MySQL configuration file that sets the value of the variable under [mysqld] options.

You need to put the following content in your my.cnf (Mac, Linux) or my.ini (Windows) file:

[mysqld]
secure_file_priv = ""

Once you edit the configuration file, save it and restart your MySQL server. You should be able to import or export data using MySQL LOAD DATA and SELECT INTO FILE statements.

Here’s an example of a successful data export query:

mysql> SELECT * FROM students INTO OUTFILE "/tmp/out.txt";
Query OK, 6 rows affected (0.00 sec)

Now the result of the SELECT statement above is saved as out.txt file.

You can import the same text file back into an SQL table by using the LOAD DATA statement.

First, create a copy of your table using CREATE TABLE ... LIKE statement as shown below:

CREATE TABLE students_copy LIKE students;

Then, load the data from the out.txt file with the following SQL query:

mysql> LOAD DATA INFILE '/tmp/out.txt' INTO TABLE students_copy;
Query OK, 6 rows affected (0.00 sec)
Records: 6  Deleted: 0  Skipped: 0  Warnings: 0

The query above will put the out.txt data into the students_copy table.

What to do when you have no configuration file

Sometimes, your MySQL installation didn’t come with a config file.

This happens to me when I install the official MySQL community edition for Mac OS, which doesn’t add a default my.cnf file to start the server.

In that case, you should create your own configuration file in a location that will be picked up by MySQL.

MySQL will look in the following locations for a .cnf file:

  • /etc/my.cnf
  • /etc/mysql/my.cnf
  • /usr/local/mysql/etc/my.cnf
  • ~/.my.cnf

Or if you’re using Windows:

  • C:Windowsmy.ini
  • C:Windowsmy.cnf
  • C:my.ini
  • C:my.cnf
  • C:Program FilesMySQLMySQL Server x.xmy.ini
  • C:Program FilesMySQLMySQL Server x.xmy.cnf

As for me, I created a new ~/.my.cnf file in my Mac machine with the following command:

cd ~
touch .my.cnf
vim .my.cnf 

The content of the .my.cnf file is as follows:

[mysqld]
secure_file_priv = ""

Save all changes and exit the Vim session by pressing semicolon : + wq and then hit Enter.

That will be enough to change the value of the secure_file_priv variable on your computer.

And that’s how you fix the --secure-file-priv option error and allow data import/ export using SQL query. Nicely done! 👍

Понравилась статья? Поделить с друзьями:
  • Ошибка 129 роблокс
  • Ошибка 129 консультант плюс другой пользователь передает параметры
  • Ошибка 129 компрессор
  • Ошибка 129 ивеко дейли
  • Ошибка 129 додж караван