(Python + Mysql) Enter the database password automatically in a dump

Asked

Viewed 30 times

0

I am creating a Python script that backs up the company database I work on and it will run on crontab weekly.

My doubt:

How to enter the password automatically, since it is requested after the mysqldump command??

How the code is currently:

import subprocess

import os

command = 'mysqldump -u root -p testes_script > testandoo.sql'

os.system(command)
subprocess.Popen('senhatestes')

print('Dump realizado com sucesso')

Return when executing code:

Enter password:

I tried to run a subprocess. Popen('password') but was unsuccessful, the error returned is:

Traceback (most recent call last):
  File "teste_dump.py", line 7, in <module>
    subprocess.Popen('senhatestes')
  File "/usr/lib64/python3.6/subprocess.py", line 729, in _init_
    restore_signals, start_new_session)
  File "/usr/lib64/python3.6/subprocess.py", line 1364, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'senhatestes': 'senhatestes'

This is just a trial version, I need to make this dump roll before effectively writing the code I will run in production.

  • Don’t greet, don’t thank and don’t sign the publications.

1 answer

0


If you’re using linux (Ubuntu), all you need to do is create a file .my.cnf at home.

touch ~/.my.cnf

Fill in the file .my.cnf, with the following content:

[mysqldump]
user = mysqluser
password = senhasuperseguradoseubancodedadosT0p+

Change the permission of the created file (~/.my.cnf) via chmod to 600, this will prevent other user from seeing the contents of the file.

chmod 600 ~/.my.cnf

Now when executing the mysqldump, when passing the parameter -p password will no longer be requested as it will be read from the file.

mysqldump -u mysqluser -p > testandoo.sql

Note that in this example I am using another user.

The steps demonstrated here can be seen in this link.

  • 1

    Thank you so much for your contribution. It worked perfectly and solved my problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.